babylon.max.js 4.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529
  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. }
  7319. else {
  7320. var totalPoints = new Array();
  7321. totalPoints.push(points[0].clone());
  7322. Array.prototype.push.apply(totalPoints, points);
  7323. totalPoints.push(points[points.length - 1].clone());
  7324. for (var i = 0; i < totalPoints.length - 3; i++) {
  7325. amount = 0;
  7326. for (var c = 0; c < nbPoints; c++) {
  7327. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7328. amount += step;
  7329. }
  7330. }
  7331. i--;
  7332. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7333. }
  7334. return new Curve3(catmullRom);
  7335. };
  7336. /**
  7337. * Returns the Curve3 stored array of successive Vector3
  7338. */
  7339. Curve3.prototype.getPoints = function () {
  7340. return this._points;
  7341. };
  7342. /**
  7343. * Returns the computed length (float) of the curve.
  7344. */
  7345. Curve3.prototype.length = function () {
  7346. return this._length;
  7347. };
  7348. /**
  7349. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7350. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7351. * curveA and curveB keep unchanged.
  7352. */
  7353. Curve3.prototype.continue = function (curve) {
  7354. var lastPoint = this._points[this._points.length - 1];
  7355. var continuedPoints = this._points.slice();
  7356. var curvePoints = curve.getPoints();
  7357. for (var i = 1; i < curvePoints.length; i++) {
  7358. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7359. }
  7360. var continuedCurve = new Curve3(continuedPoints);
  7361. return continuedCurve;
  7362. };
  7363. Curve3.prototype._computeLength = function (path) {
  7364. var l = 0;
  7365. for (var i = 1; i < path.length; i++) {
  7366. l += (path[i].subtract(path[i - 1])).length();
  7367. }
  7368. return l;
  7369. };
  7370. return Curve3;
  7371. }());
  7372. BABYLON.Curve3 = Curve3;
  7373. // Vertex formats
  7374. var PositionNormalVertex = /** @class */ (function () {
  7375. function PositionNormalVertex(position, normal) {
  7376. if (position === void 0) { position = Vector3.Zero(); }
  7377. if (normal === void 0) { normal = Vector3.Up(); }
  7378. this.position = position;
  7379. this.normal = normal;
  7380. }
  7381. PositionNormalVertex.prototype.clone = function () {
  7382. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7383. };
  7384. return PositionNormalVertex;
  7385. }());
  7386. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7387. var PositionNormalTextureVertex = /** @class */ (function () {
  7388. function PositionNormalTextureVertex(position, normal, uv) {
  7389. if (position === void 0) { position = Vector3.Zero(); }
  7390. if (normal === void 0) { normal = Vector3.Up(); }
  7391. if (uv === void 0) { uv = Vector2.Zero(); }
  7392. this.position = position;
  7393. this.normal = normal;
  7394. this.uv = uv;
  7395. }
  7396. PositionNormalTextureVertex.prototype.clone = function () {
  7397. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7398. };
  7399. return PositionNormalTextureVertex;
  7400. }());
  7401. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7402. // Temporary pre-allocated objects for engine internal use
  7403. // usage in any internal function :
  7404. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7405. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7406. var Tmp = /** @class */ (function () {
  7407. function Tmp() {
  7408. }
  7409. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7410. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7411. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7412. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7413. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7414. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7415. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7416. Matrix.Zero(), Matrix.Zero(),
  7417. Matrix.Zero(), Matrix.Zero(),
  7418. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7419. return Tmp;
  7420. }());
  7421. BABYLON.Tmp = Tmp;
  7422. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7423. var MathTmp = /** @class */ (function () {
  7424. function MathTmp() {
  7425. }
  7426. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7427. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7428. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7429. return MathTmp;
  7430. }());
  7431. })(BABYLON || (BABYLON = {}));
  7432. //# sourceMappingURL=babylon.math.js.map
  7433. var BABYLON;
  7434. (function (BABYLON) {
  7435. var Scalar = /** @class */ (function () {
  7436. function Scalar() {
  7437. }
  7438. /**
  7439. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7440. */
  7441. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7442. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7443. var num = a - b;
  7444. return -epsilon <= num && num <= epsilon;
  7445. };
  7446. /**
  7447. * Returns a string : the upper case translation of the number i to hexadecimal.
  7448. */
  7449. Scalar.ToHex = function (i) {
  7450. var str = i.toString(16);
  7451. if (i <= 15) {
  7452. return ("0" + str).toUpperCase();
  7453. }
  7454. return str.toUpperCase();
  7455. };
  7456. /**
  7457. * Returns -1 if value is negative and +1 is value is positive.
  7458. * Returns the value itself if it's equal to zero.
  7459. */
  7460. Scalar.Sign = function (value) {
  7461. value = +value; // convert to a number
  7462. if (value === 0 || isNaN(value))
  7463. return value;
  7464. return value > 0 ? 1 : -1;
  7465. };
  7466. /**
  7467. * Returns the value itself if it's between min and max.
  7468. * Returns min if the value is lower than min.
  7469. * Returns max if the value is greater than max.
  7470. */
  7471. Scalar.Clamp = function (value, min, max) {
  7472. if (min === void 0) { min = 0; }
  7473. if (max === void 0) { max = 1; }
  7474. return Math.min(max, Math.max(min, value));
  7475. };
  7476. /**
  7477. * Returns the log2 of value.
  7478. */
  7479. Scalar.Log2 = function (value) {
  7480. return Math.log(value) * Math.LOG2E;
  7481. };
  7482. /**
  7483. * Loops the value, so that it is never larger than length and never smaller than 0.
  7484. *
  7485. * This is similar to the modulo operator but it works with floating point numbers.
  7486. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7487. * With t = 5 and length = 2.5, the result would be 0.0.
  7488. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7489. */
  7490. Scalar.Repeat = function (value, length) {
  7491. return value - Math.floor(value / length) * length;
  7492. };
  7493. /**
  7494. * Normalize the value between 0.0 and 1.0 using min and max values
  7495. */
  7496. Scalar.Normalize = function (value, min, max) {
  7497. return (value - min) / (max - min);
  7498. };
  7499. /**
  7500. * Denormalize the value from 0.0 and 1.0 using min and max values
  7501. */
  7502. Scalar.Denormalize = function (normalized, min, max) {
  7503. return (normalized * (max - min) + min);
  7504. };
  7505. /**
  7506. * Calculates the shortest difference between two given angles given in degrees.
  7507. */
  7508. Scalar.DeltaAngle = function (current, target) {
  7509. var num = Scalar.Repeat(target - current, 360.0);
  7510. if (num > 180.0) {
  7511. num -= 360.0;
  7512. }
  7513. return num;
  7514. };
  7515. /**
  7516. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7517. *
  7518. * The returned value will move back and forth between 0 and length
  7519. */
  7520. Scalar.PingPong = function (tx, length) {
  7521. var t = Scalar.Repeat(tx, length * 2.0);
  7522. return length - Math.abs(t - length);
  7523. };
  7524. /**
  7525. * Interpolates between min and max with smoothing at the limits.
  7526. *
  7527. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7528. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7529. */
  7530. Scalar.SmoothStep = function (from, to, tx) {
  7531. var t = Scalar.Clamp(tx);
  7532. t = -2.0 * t * t * t + 3.0 * t * t;
  7533. return to * t + from * (1.0 - t);
  7534. };
  7535. /**
  7536. * Moves a value current towards target.
  7537. *
  7538. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7539. * Negative values of maxDelta pushes the value away from target.
  7540. */
  7541. Scalar.MoveTowards = function (current, target, maxDelta) {
  7542. var result = 0;
  7543. if (Math.abs(target - current) <= maxDelta) {
  7544. result = target;
  7545. }
  7546. else {
  7547. result = current + Scalar.Sign(target - current) * maxDelta;
  7548. }
  7549. return result;
  7550. };
  7551. /**
  7552. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7553. *
  7554. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7555. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7556. */
  7557. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7558. var num = Scalar.DeltaAngle(current, target);
  7559. var result = 0;
  7560. if (-maxDelta < num && num < maxDelta) {
  7561. result = target;
  7562. }
  7563. else {
  7564. target = current + num;
  7565. result = Scalar.MoveTowards(current, target, maxDelta);
  7566. }
  7567. return result;
  7568. };
  7569. /**
  7570. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7571. */
  7572. Scalar.Lerp = function (start, end, amount) {
  7573. return start + ((end - start) * amount);
  7574. };
  7575. /**
  7576. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7577. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7578. */
  7579. Scalar.LerpAngle = function (start, end, amount) {
  7580. var num = Scalar.Repeat(end - start, 360.0);
  7581. if (num > 180.0) {
  7582. num -= 360.0;
  7583. }
  7584. return start + num * Scalar.Clamp(amount);
  7585. };
  7586. /**
  7587. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7588. */
  7589. Scalar.InverseLerp = function (a, b, value) {
  7590. var result = 0;
  7591. if (a != b) {
  7592. result = Scalar.Clamp((value - a) / (b - a));
  7593. }
  7594. else {
  7595. result = 0.0;
  7596. }
  7597. return result;
  7598. };
  7599. /**
  7600. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7601. */
  7602. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7603. var squared = amount * amount;
  7604. var cubed = amount * squared;
  7605. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7606. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7607. var part3 = (cubed - (2.0 * squared)) + amount;
  7608. var part4 = cubed - squared;
  7609. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7610. };
  7611. /**
  7612. * Returns a random float number between and min and max values
  7613. */
  7614. Scalar.RandomRange = function (min, max) {
  7615. if (min === max)
  7616. return min;
  7617. return ((Math.random() * (max - min)) + min);
  7618. };
  7619. /**
  7620. * This function returns percentage of a number in a given range.
  7621. *
  7622. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7623. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7624. */
  7625. Scalar.RangeToPercent = function (number, min, max) {
  7626. return ((number - min) / (max - min));
  7627. };
  7628. /**
  7629. * This function returns number that corresponds to the percentage in a given range.
  7630. *
  7631. * PercentToRange(0.34,0,100) will return 34.
  7632. */
  7633. Scalar.PercentToRange = function (percent, min, max) {
  7634. return ((max - min) * percent + min);
  7635. };
  7636. /**
  7637. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7638. * @param angle The angle to normalize in radian.
  7639. * @return The converted angle.
  7640. */
  7641. Scalar.NormalizeRadians = function (angle) {
  7642. // More precise but slower version kept for reference.
  7643. // angle = angle % Tools.TwoPi;
  7644. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7645. //if (angle > Math.PI) {
  7646. // angle -= Tools.TwoPi;
  7647. //}
  7648. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7649. return angle;
  7650. };
  7651. /**
  7652. * Two pi constants convenient for computation.
  7653. */
  7654. Scalar.TwoPi = Math.PI * 2;
  7655. return Scalar;
  7656. }());
  7657. BABYLON.Scalar = Scalar;
  7658. })(BABYLON || (BABYLON = {}));
  7659. //# sourceMappingURL=babylon.math.scalar.js.map
  7660. //# sourceMappingURL=babylon.mixins.js.map
  7661. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7662. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7663. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7664. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7665. //# sourceMappingURL=babylon.webgl2.js.map
  7666. var BABYLON;
  7667. (function (BABYLON) {
  7668. var __decoratorInitialStore = {};
  7669. var __mergedStore = {};
  7670. var _copySource = function (creationFunction, source, instanciate) {
  7671. var destination = creationFunction();
  7672. // Tags
  7673. if (BABYLON.Tags) {
  7674. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7675. }
  7676. var classStore = getMergedStore(destination);
  7677. // Properties
  7678. for (var property in classStore) {
  7679. var propertyDescriptor = classStore[property];
  7680. var sourceProperty = source[property];
  7681. var propertyType = propertyDescriptor.type;
  7682. if (sourceProperty !== undefined && sourceProperty !== null) {
  7683. switch (propertyType) {
  7684. case 0: // Value
  7685. case 6: // Mesh reference
  7686. case 11: // Camera reference
  7687. destination[property] = sourceProperty;
  7688. break;
  7689. case 1: // Texture
  7690. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7691. break;
  7692. case 2: // Color3
  7693. case 3: // FresnelParameters
  7694. case 4: // Vector2
  7695. case 5: // Vector3
  7696. case 7: // Color Curves
  7697. case 10: // Quaternion
  7698. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7699. break;
  7700. }
  7701. }
  7702. }
  7703. return destination;
  7704. };
  7705. function getDirectStore(target) {
  7706. var classKey = target.getClassName();
  7707. if (!__decoratorInitialStore[classKey]) {
  7708. __decoratorInitialStore[classKey] = {};
  7709. }
  7710. return __decoratorInitialStore[classKey];
  7711. }
  7712. /**
  7713. * Return the list of properties flagged as serializable
  7714. * @param target: host object
  7715. */
  7716. function getMergedStore(target) {
  7717. var classKey = target.getClassName();
  7718. if (__mergedStore[classKey]) {
  7719. return __mergedStore[classKey];
  7720. }
  7721. __mergedStore[classKey] = {};
  7722. var store = __mergedStore[classKey];
  7723. var currentTarget = target;
  7724. var currentKey = classKey;
  7725. while (currentKey) {
  7726. var initialStore = __decoratorInitialStore[currentKey];
  7727. for (var property in initialStore) {
  7728. store[property] = initialStore[property];
  7729. }
  7730. var parent_1 = void 0;
  7731. var done = false;
  7732. do {
  7733. parent_1 = Object.getPrototypeOf(currentTarget);
  7734. if (!parent_1.getClassName) {
  7735. done = true;
  7736. break;
  7737. }
  7738. if (parent_1.getClassName() !== currentKey) {
  7739. break;
  7740. }
  7741. currentTarget = parent_1;
  7742. } while (parent_1);
  7743. if (done) {
  7744. break;
  7745. }
  7746. currentKey = parent_1.getClassName();
  7747. currentTarget = parent_1;
  7748. }
  7749. return store;
  7750. }
  7751. function generateSerializableMember(type, sourceName) {
  7752. return function (target, propertyKey) {
  7753. var classStore = getDirectStore(target);
  7754. if (!classStore[propertyKey]) {
  7755. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7756. }
  7757. };
  7758. }
  7759. function generateExpandMember(setCallback, targetKey) {
  7760. if (targetKey === void 0) { targetKey = null; }
  7761. return function (target, propertyKey) {
  7762. var key = targetKey || ("_" + propertyKey);
  7763. Object.defineProperty(target, propertyKey, {
  7764. get: function () {
  7765. return this[key];
  7766. },
  7767. set: function (value) {
  7768. if (this[key] === value) {
  7769. return;
  7770. }
  7771. this[key] = value;
  7772. target[setCallback].apply(this);
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. };
  7778. }
  7779. function expandToProperty(callback, targetKey) {
  7780. if (targetKey === void 0) { targetKey = null; }
  7781. return generateExpandMember(callback, targetKey);
  7782. }
  7783. BABYLON.expandToProperty = expandToProperty;
  7784. function serialize(sourceName) {
  7785. return generateSerializableMember(0, sourceName); // value member
  7786. }
  7787. BABYLON.serialize = serialize;
  7788. function serializeAsTexture(sourceName) {
  7789. return generateSerializableMember(1, sourceName); // texture member
  7790. }
  7791. BABYLON.serializeAsTexture = serializeAsTexture;
  7792. function serializeAsColor3(sourceName) {
  7793. return generateSerializableMember(2, sourceName); // color3 member
  7794. }
  7795. BABYLON.serializeAsColor3 = serializeAsColor3;
  7796. function serializeAsFresnelParameters(sourceName) {
  7797. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7798. }
  7799. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7800. function serializeAsVector2(sourceName) {
  7801. return generateSerializableMember(4, sourceName); // vector2 member
  7802. }
  7803. BABYLON.serializeAsVector2 = serializeAsVector2;
  7804. function serializeAsVector3(sourceName) {
  7805. return generateSerializableMember(5, sourceName); // vector3 member
  7806. }
  7807. BABYLON.serializeAsVector3 = serializeAsVector3;
  7808. function serializeAsMeshReference(sourceName) {
  7809. return generateSerializableMember(6, sourceName); // mesh reference member
  7810. }
  7811. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7812. function serializeAsColorCurves(sourceName) {
  7813. return generateSerializableMember(7, sourceName); // color curves
  7814. }
  7815. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7816. function serializeAsColor4(sourceName) {
  7817. return generateSerializableMember(8, sourceName); // color 4
  7818. }
  7819. BABYLON.serializeAsColor4 = serializeAsColor4;
  7820. function serializeAsImageProcessingConfiguration(sourceName) {
  7821. return generateSerializableMember(9, sourceName); // image processing
  7822. }
  7823. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7824. function serializeAsQuaternion(sourceName) {
  7825. return generateSerializableMember(10, sourceName); // quaternion member
  7826. }
  7827. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7828. /**
  7829. * Decorator used to define property that can be serialized as reference to a camera
  7830. * @param sourceName defines the name of the property to decorate
  7831. */
  7832. function serializeAsCameraReference(sourceName) {
  7833. return generateSerializableMember(11, sourceName); // camera reference member
  7834. }
  7835. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7836. var SerializationHelper = /** @class */ (function () {
  7837. function SerializationHelper() {
  7838. }
  7839. SerializationHelper.Serialize = function (entity, serializationObject) {
  7840. if (!serializationObject) {
  7841. serializationObject = {};
  7842. }
  7843. // Tags
  7844. if (BABYLON.Tags) {
  7845. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7846. }
  7847. var serializedProperties = getMergedStore(entity);
  7848. // Properties
  7849. for (var property in serializedProperties) {
  7850. var propertyDescriptor = serializedProperties[property];
  7851. var targetPropertyName = propertyDescriptor.sourceName || property;
  7852. var propertyType = propertyDescriptor.type;
  7853. var sourceProperty = entity[property];
  7854. if (sourceProperty !== undefined && sourceProperty !== null) {
  7855. switch (propertyType) {
  7856. case 0: // Value
  7857. serializationObject[targetPropertyName] = sourceProperty;
  7858. break;
  7859. case 1: // Texture
  7860. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7861. break;
  7862. case 2: // Color3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 3: // FresnelParameters
  7866. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7867. break;
  7868. case 4: // Vector2
  7869. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7870. break;
  7871. case 5: // Vector3
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 6: // Mesh reference
  7875. serializationObject[targetPropertyName] = sourceProperty.id;
  7876. break;
  7877. case 7: // Color Curves
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 8: // Color 4
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 9: // Image Processing
  7884. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7885. break;
  7886. case 10: // Quaternion
  7887. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7888. break;
  7889. case 11: // Camera reference
  7890. serializationObject[targetPropertyName] = sourceProperty.id;
  7891. break;
  7892. }
  7893. }
  7894. }
  7895. return serializationObject;
  7896. };
  7897. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7898. if (rootUrl === void 0) { rootUrl = null; }
  7899. var destination = creationFunction();
  7900. if (!rootUrl) {
  7901. rootUrl = "";
  7902. }
  7903. // Tags
  7904. if (BABYLON.Tags) {
  7905. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7906. }
  7907. var classStore = getMergedStore(destination);
  7908. // Properties
  7909. for (var property in classStore) {
  7910. var propertyDescriptor = classStore[property];
  7911. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7912. var propertyType = propertyDescriptor.type;
  7913. if (sourceProperty !== undefined && sourceProperty !== null) {
  7914. var dest = destination;
  7915. switch (propertyType) {
  7916. case 0: // Value
  7917. dest[property] = sourceProperty;
  7918. break;
  7919. case 1: // Texture
  7920. if (scene) {
  7921. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7922. }
  7923. break;
  7924. case 2: // Color3
  7925. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7926. break;
  7927. case 3: // FresnelParameters
  7928. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7929. break;
  7930. case 4: // Vector2
  7931. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7932. break;
  7933. case 5: // Vector3
  7934. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7935. break;
  7936. case 6: // Mesh reference
  7937. if (scene) {
  7938. dest[property] = scene.getLastMeshByID(sourceProperty);
  7939. }
  7940. break;
  7941. case 7: // Color Curves
  7942. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7943. break;
  7944. case 8: // Color 4
  7945. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7946. break;
  7947. case 9: // Image Processing
  7948. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7949. break;
  7950. case 10: // Quaternion
  7951. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7952. break;
  7953. case 11: // Camera reference
  7954. if (scene) {
  7955. dest[property] = scene.getCameraByID(sourceProperty);
  7956. }
  7957. break;
  7958. }
  7959. }
  7960. }
  7961. return destination;
  7962. };
  7963. SerializationHelper.Clone = function (creationFunction, source) {
  7964. return _copySource(creationFunction, source, false);
  7965. };
  7966. SerializationHelper.Instanciate = function (creationFunction, source) {
  7967. return _copySource(creationFunction, source, true);
  7968. };
  7969. return SerializationHelper;
  7970. }());
  7971. BABYLON.SerializationHelper = SerializationHelper;
  7972. })(BABYLON || (BABYLON = {}));
  7973. //# sourceMappingURL=babylon.decorators.js.map
  7974. var BABYLON;
  7975. (function (BABYLON) {
  7976. /**
  7977. * Wrapper class for promise with external resolve and reject.
  7978. */
  7979. var Deferred = /** @class */ (function () {
  7980. /**
  7981. * Constructor for this deferred object.
  7982. */
  7983. function Deferred() {
  7984. var _this = this;
  7985. this.promise = new Promise(function (resolve, reject) {
  7986. _this._resolve = resolve;
  7987. _this._reject = reject;
  7988. });
  7989. }
  7990. Object.defineProperty(Deferred.prototype, "resolve", {
  7991. /**
  7992. * The resolve method of the promise associated with this deferred object.
  7993. */
  7994. get: function () {
  7995. return this._resolve;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(Deferred.prototype, "reject", {
  8001. /**
  8002. * The reject method of the promise associated with this deferred object.
  8003. */
  8004. get: function () {
  8005. return this._reject;
  8006. },
  8007. enumerable: true,
  8008. configurable: true
  8009. });
  8010. return Deferred;
  8011. }());
  8012. BABYLON.Deferred = Deferred;
  8013. })(BABYLON || (BABYLON = {}));
  8014. //# sourceMappingURL=babylon.deferred.js.map
  8015. var BABYLON;
  8016. (function (BABYLON) {
  8017. /**
  8018. * A class serves as a medium between the observable and its observers
  8019. */
  8020. var EventState = /** @class */ (function () {
  8021. /**
  8022. * Create a new EventState
  8023. * @param mask defines the mask associated with this state
  8024. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8025. * @param target defines the original target of the state
  8026. * @param currentTarget defines the current target of the state
  8027. */
  8028. function EventState(mask, skipNextObservers, target, currentTarget) {
  8029. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8030. this.initalize(mask, skipNextObservers, target, currentTarget);
  8031. }
  8032. /**
  8033. * Initialize the current event state
  8034. * @param mask defines the mask associated with this state
  8035. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8036. * @param target defines the original target of the state
  8037. * @param currentTarget defines the current target of the state
  8038. * @returns the current event state
  8039. */
  8040. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8041. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8042. this.mask = mask;
  8043. this.skipNextObservers = skipNextObservers;
  8044. this.target = target;
  8045. this.currentTarget = currentTarget;
  8046. return this;
  8047. };
  8048. return EventState;
  8049. }());
  8050. BABYLON.EventState = EventState;
  8051. /**
  8052. * Represent an Observer registered to a given Observable object.
  8053. */
  8054. var Observer = /** @class */ (function () {
  8055. /**
  8056. * Creates a new observer
  8057. * @param callback defines the callback to call when the observer is notified
  8058. * @param mask defines the mask of the observer (used to filter notifications)
  8059. * @param scope defines the current scope used to restore the JS context
  8060. */
  8061. function Observer(
  8062. /**
  8063. * Defines the callback to call when the observer is notified
  8064. */
  8065. callback,
  8066. /**
  8067. * Defines the mask of the observer (used to filter notifications)
  8068. */
  8069. mask,
  8070. /**
  8071. * Defines the current scope used to restore the JS context
  8072. */
  8073. scope) {
  8074. if (scope === void 0) { scope = null; }
  8075. this.callback = callback;
  8076. this.mask = mask;
  8077. this.scope = scope;
  8078. /** @hidden */
  8079. this._willBeUnregistered = false;
  8080. /**
  8081. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8082. */
  8083. this.unregisterOnNextCall = false;
  8084. }
  8085. return Observer;
  8086. }());
  8087. BABYLON.Observer = Observer;
  8088. /**
  8089. * Represent a list of observers registered to multiple Observables object.
  8090. */
  8091. var MultiObserver = /** @class */ (function () {
  8092. function MultiObserver() {
  8093. }
  8094. /**
  8095. * Release associated resources
  8096. */
  8097. MultiObserver.prototype.dispose = function () {
  8098. if (this._observers && this._observables) {
  8099. for (var index = 0; index < this._observers.length; index++) {
  8100. this._observables[index].remove(this._observers[index]);
  8101. }
  8102. }
  8103. this._observers = null;
  8104. this._observables = null;
  8105. };
  8106. /**
  8107. * Raise a callback when one of the observable will notify
  8108. * @param observables defines a list of observables to watch
  8109. * @param callback defines the callback to call on notification
  8110. * @param mask defines the mask used to filter notifications
  8111. * @param scope defines the current scope used to restore the JS context
  8112. * @returns the new MultiObserver
  8113. */
  8114. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8115. if (mask === void 0) { mask = -1; }
  8116. if (scope === void 0) { scope = null; }
  8117. var result = new MultiObserver();
  8118. result._observers = new Array();
  8119. result._observables = observables;
  8120. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8121. var observable = observables_1[_i];
  8122. var observer = observable.add(callback, mask, false, scope);
  8123. if (observer) {
  8124. result._observers.push(observer);
  8125. }
  8126. }
  8127. return result;
  8128. };
  8129. return MultiObserver;
  8130. }());
  8131. BABYLON.MultiObserver = MultiObserver;
  8132. /**
  8133. * The Observable class is a simple implementation of the Observable pattern.
  8134. *
  8135. * 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.
  8136. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8137. * 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).
  8138. * 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.
  8139. */
  8140. var Observable = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observable
  8143. * @param onObserverAdded defines a callback to call when a new observer is added
  8144. */
  8145. function Observable(onObserverAdded) {
  8146. this._observers = new Array();
  8147. this._eventState = new EventState(0);
  8148. if (onObserverAdded) {
  8149. this._onObserverAdded = onObserverAdded;
  8150. }
  8151. }
  8152. /**
  8153. * Create a new Observer with the specified callback
  8154. * @param callback the callback that will be executed for that Observer
  8155. * @param mask the mask used to filter observers
  8156. * @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.
  8157. * @param scope optional scope for the callback to be called from
  8158. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8159. * @returns the new observer created for the callback
  8160. */
  8161. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8162. if (mask === void 0) { mask = -1; }
  8163. if (insertFirst === void 0) { insertFirst = false; }
  8164. if (scope === void 0) { scope = null; }
  8165. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8166. if (!callback) {
  8167. return null;
  8168. }
  8169. var observer = new Observer(callback, mask, scope);
  8170. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8171. if (insertFirst) {
  8172. this._observers.unshift(observer);
  8173. }
  8174. else {
  8175. this._observers.push(observer);
  8176. }
  8177. if (this._onObserverAdded) {
  8178. this._onObserverAdded(observer);
  8179. }
  8180. return observer;
  8181. };
  8182. /**
  8183. * Remove an Observer from the Observable object
  8184. * @param observer the instance of the Observer to remove
  8185. * @returns false if it doesn't belong to this Observable
  8186. */
  8187. Observable.prototype.remove = function (observer) {
  8188. if (!observer) {
  8189. return false;
  8190. }
  8191. var index = this._observers.indexOf(observer);
  8192. if (index !== -1) {
  8193. this._observers.splice(index, 1);
  8194. return true;
  8195. }
  8196. return false;
  8197. };
  8198. /**
  8199. * Remove a callback from the Observable object
  8200. * @param callback the callback to remove
  8201. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8202. * @returns false if it doesn't belong to this Observable
  8203. */
  8204. Observable.prototype.removeCallback = function (callback, scope) {
  8205. for (var index = 0; index < this._observers.length; index++) {
  8206. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8207. this._observers.splice(index, 1);
  8208. return true;
  8209. }
  8210. }
  8211. return false;
  8212. };
  8213. Observable.prototype._deferUnregister = function (observer) {
  8214. var _this = this;
  8215. observer.unregisterOnNextCall = false;
  8216. observer._willBeUnregistered = true;
  8217. BABYLON.Tools.SetImmediate(function () {
  8218. _this.remove(observer);
  8219. });
  8220. };
  8221. /**
  8222. * Notify all Observers by calling their respective callback with the given data
  8223. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8224. * @param eventData defines the data to send to all observers
  8225. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8226. * @param target defines the original target of the state
  8227. * @param currentTarget defines the current target of the state
  8228. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8229. */
  8230. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8231. if (mask === void 0) { mask = -1; }
  8232. if (!this._observers.length) {
  8233. return true;
  8234. }
  8235. var state = this._eventState;
  8236. state.mask = mask;
  8237. state.target = target;
  8238. state.currentTarget = currentTarget;
  8239. state.skipNextObservers = false;
  8240. state.lastReturnValue = eventData;
  8241. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8242. var obs = _a[_i];
  8243. if (obs._willBeUnregistered) {
  8244. continue;
  8245. }
  8246. if (obs.mask & mask) {
  8247. if (obs.scope) {
  8248. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8249. }
  8250. else {
  8251. state.lastReturnValue = obs.callback(eventData, state);
  8252. }
  8253. if (obs.unregisterOnNextCall) {
  8254. this._deferUnregister(obs);
  8255. }
  8256. }
  8257. if (state.skipNextObservers) {
  8258. return false;
  8259. }
  8260. }
  8261. return true;
  8262. };
  8263. /**
  8264. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8265. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8266. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8267. * and it is crucial that all callbacks will be executed.
  8268. * The order of the callbacks is kept, callbacks are not executed parallel.
  8269. *
  8270. * @param eventData The data to be sent to each callback
  8271. * @param mask is used to filter observers defaults to -1
  8272. * @param target defines the callback target (see EventState)
  8273. * @param currentTarget defines he current object in the bubbling phase
  8274. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8275. */
  8276. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8277. var _this = this;
  8278. if (mask === void 0) { mask = -1; }
  8279. // create an empty promise
  8280. var p = Promise.resolve(eventData);
  8281. // no observers? return this promise.
  8282. if (!this._observers.length) {
  8283. return p;
  8284. }
  8285. var state = this._eventState;
  8286. state.mask = mask;
  8287. state.target = target;
  8288. state.currentTarget = currentTarget;
  8289. state.skipNextObservers = false;
  8290. // execute one callback after another (not using Promise.all, the order is important)
  8291. this._observers.forEach(function (obs) {
  8292. if (state.skipNextObservers) {
  8293. return;
  8294. }
  8295. if (obs._willBeUnregistered) {
  8296. return;
  8297. }
  8298. if (obs.mask & mask) {
  8299. if (obs.scope) {
  8300. p = p.then(function (lastReturnedValue) {
  8301. state.lastReturnValue = lastReturnedValue;
  8302. return obs.callback.apply(obs.scope, [eventData, state]);
  8303. });
  8304. }
  8305. else {
  8306. p = p.then(function (lastReturnedValue) {
  8307. state.lastReturnValue = lastReturnedValue;
  8308. return obs.callback(eventData, state);
  8309. });
  8310. }
  8311. if (obs.unregisterOnNextCall) {
  8312. _this._deferUnregister(obs);
  8313. }
  8314. }
  8315. });
  8316. // return the eventData
  8317. return p.then(function () { return eventData; });
  8318. };
  8319. /**
  8320. * Notify a specific observer
  8321. * @param observer defines the observer to notify
  8322. * @param eventData defines the data to be sent to each callback
  8323. * @param mask is used to filter observers defaults to -1
  8324. */
  8325. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8326. if (mask === void 0) { mask = -1; }
  8327. var state = this._eventState;
  8328. state.mask = mask;
  8329. state.skipNextObservers = false;
  8330. observer.callback(eventData, state);
  8331. };
  8332. /**
  8333. * Gets a boolean indicating if the observable has at least one observer
  8334. * @returns true is the Observable has at least one Observer registered
  8335. */
  8336. Observable.prototype.hasObservers = function () {
  8337. return this._observers.length > 0;
  8338. };
  8339. /**
  8340. * Clear the list of observers
  8341. */
  8342. Observable.prototype.clear = function () {
  8343. this._observers = new Array();
  8344. this._onObserverAdded = null;
  8345. };
  8346. /**
  8347. * Clone the current observable
  8348. * @returns a new observable
  8349. */
  8350. Observable.prototype.clone = function () {
  8351. var result = new Observable();
  8352. result._observers = this._observers.slice(0);
  8353. return result;
  8354. };
  8355. /**
  8356. * Does this observable handles observer registered with a given mask
  8357. * @param mask defines the mask to be tested
  8358. * @return whether or not one observer registered with the given mask is handeled
  8359. **/
  8360. Observable.prototype.hasSpecificMask = function (mask) {
  8361. if (mask === void 0) { mask = -1; }
  8362. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8363. var obs = _a[_i];
  8364. if (obs.mask & mask || obs.mask === mask) {
  8365. return true;
  8366. }
  8367. }
  8368. return false;
  8369. };
  8370. return Observable;
  8371. }());
  8372. BABYLON.Observable = Observable;
  8373. })(BABYLON || (BABYLON = {}));
  8374. //# sourceMappingURL=babylon.observable.js.map
  8375. var BABYLON;
  8376. (function (BABYLON) {
  8377. var SmartArray = /** @class */ (function () {
  8378. function SmartArray(capacity) {
  8379. this.length = 0;
  8380. this.data = new Array(capacity);
  8381. this._id = SmartArray._GlobalId++;
  8382. }
  8383. SmartArray.prototype.push = function (value) {
  8384. this.data[this.length++] = value;
  8385. if (this.length > this.data.length) {
  8386. this.data.length *= 2;
  8387. }
  8388. };
  8389. SmartArray.prototype.forEach = function (func) {
  8390. for (var index = 0; index < this.length; index++) {
  8391. func(this.data[index]);
  8392. }
  8393. };
  8394. SmartArray.prototype.sort = function (compareFn) {
  8395. this.data.sort(compareFn);
  8396. };
  8397. SmartArray.prototype.reset = function () {
  8398. this.length = 0;
  8399. };
  8400. SmartArray.prototype.dispose = function () {
  8401. this.reset();
  8402. if (this.data) {
  8403. this.data.length = 0;
  8404. this.data = [];
  8405. }
  8406. };
  8407. SmartArray.prototype.concat = function (array) {
  8408. if (array.length === 0) {
  8409. return;
  8410. }
  8411. if (this.length + array.length > this.data.length) {
  8412. this.data.length = (this.length + array.length) * 2;
  8413. }
  8414. for (var index = 0; index < array.length; index++) {
  8415. this.data[this.length++] = (array.data || array)[index];
  8416. }
  8417. };
  8418. SmartArray.prototype.indexOf = function (value) {
  8419. var position = this.data.indexOf(value);
  8420. if (position >= this.length) {
  8421. return -1;
  8422. }
  8423. return position;
  8424. };
  8425. SmartArray.prototype.contains = function (value) {
  8426. return this.data.indexOf(value) !== -1;
  8427. };
  8428. // Statics
  8429. SmartArray._GlobalId = 0;
  8430. return SmartArray;
  8431. }());
  8432. BABYLON.SmartArray = SmartArray;
  8433. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8434. __extends(SmartArrayNoDuplicate, _super);
  8435. function SmartArrayNoDuplicate() {
  8436. var _this = _super !== null && _super.apply(this, arguments) || this;
  8437. _this._duplicateId = 0;
  8438. return _this;
  8439. }
  8440. SmartArrayNoDuplicate.prototype.push = function (value) {
  8441. _super.prototype.push.call(this, value);
  8442. if (!value.__smartArrayFlags) {
  8443. value.__smartArrayFlags = {};
  8444. }
  8445. value.__smartArrayFlags[this._id] = this._duplicateId;
  8446. };
  8447. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8448. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8449. return false;
  8450. }
  8451. this.push(value);
  8452. return true;
  8453. };
  8454. SmartArrayNoDuplicate.prototype.reset = function () {
  8455. _super.prototype.reset.call(this);
  8456. this._duplicateId++;
  8457. };
  8458. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8459. if (array.length === 0) {
  8460. return;
  8461. }
  8462. if (this.length + array.length > this.data.length) {
  8463. this.data.length = (this.length + array.length) * 2;
  8464. }
  8465. for (var index = 0; index < array.length; index++) {
  8466. var item = (array.data || array)[index];
  8467. this.pushNoDuplicate(item);
  8468. }
  8469. };
  8470. return SmartArrayNoDuplicate;
  8471. }(SmartArray));
  8472. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8473. })(BABYLON || (BABYLON = {}));
  8474. //# sourceMappingURL=babylon.smartArray.js.map
  8475. var BABYLON;
  8476. (function (BABYLON) {
  8477. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8478. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8479. var LoadFileError = /** @class */ (function (_super) {
  8480. __extends(LoadFileError, _super);
  8481. function LoadFileError(message, request) {
  8482. var _this = _super.call(this, message) || this;
  8483. _this.request = request;
  8484. _this.name = "LoadFileError";
  8485. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8486. return _this;
  8487. }
  8488. // Polyfill for Object.setPrototypeOf if necessary.
  8489. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8490. return LoadFileError;
  8491. }(Error));
  8492. BABYLON.LoadFileError = LoadFileError;
  8493. var RetryStrategy = /** @class */ (function () {
  8494. function RetryStrategy() {
  8495. }
  8496. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8497. if (maxRetries === void 0) { maxRetries = 3; }
  8498. if (baseInterval === void 0) { baseInterval = 500; }
  8499. return function (url, request, retryIndex) {
  8500. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8501. return -1;
  8502. }
  8503. return Math.pow(2, retryIndex) * baseInterval;
  8504. };
  8505. };
  8506. return RetryStrategy;
  8507. }());
  8508. BABYLON.RetryStrategy = RetryStrategy;
  8509. // Screenshots
  8510. var screenshotCanvas;
  8511. var cloneValue = function (source, destinationObject) {
  8512. if (!source)
  8513. return null;
  8514. if (source instanceof BABYLON.Mesh) {
  8515. return null;
  8516. }
  8517. if (source instanceof BABYLON.SubMesh) {
  8518. return source.clone(destinationObject);
  8519. }
  8520. else if (source.clone) {
  8521. return source.clone();
  8522. }
  8523. return null;
  8524. };
  8525. var Tools = /** @class */ (function () {
  8526. function Tools() {
  8527. }
  8528. /**
  8529. * Interpolates between a and b via alpha
  8530. * @param a The lower value (returned when alpha = 0)
  8531. * @param b The upper value (returned when alpha = 1)
  8532. * @param alpha The interpolation-factor
  8533. * @return The mixed value
  8534. */
  8535. Tools.Mix = function (a, b, alpha) {
  8536. return a * (1 - alpha) + b * alpha;
  8537. };
  8538. Tools.Instantiate = function (className) {
  8539. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8540. return Tools.RegisteredExternalClasses[className];
  8541. }
  8542. var arr = className.split(".");
  8543. var fn = (window || this);
  8544. for (var i = 0, len = arr.length; i < len; i++) {
  8545. fn = fn[arr[i]];
  8546. }
  8547. if (typeof fn !== "function") {
  8548. return null;
  8549. }
  8550. return fn;
  8551. };
  8552. /**
  8553. * Provides a slice function that will work even on IE
  8554. * @param data defines the array to slice
  8555. * @param start defines the start of the data (optional)
  8556. * @param end defines the end of the data (optional)
  8557. * @returns the new sliced array
  8558. */
  8559. Tools.Slice = function (data, start, end) {
  8560. if (data.slice) {
  8561. return data.slice(start, end);
  8562. }
  8563. return Array.prototype.slice.call(data, start, end);
  8564. };
  8565. Tools.SetImmediate = function (action) {
  8566. if (window.setImmediate) {
  8567. window.setImmediate(action);
  8568. }
  8569. else {
  8570. setTimeout(action, 1);
  8571. }
  8572. };
  8573. Tools.IsExponentOfTwo = function (value) {
  8574. var count = 1;
  8575. do {
  8576. count *= 2;
  8577. } while (count < value);
  8578. return count === value;
  8579. };
  8580. /**
  8581. * Returns the nearest 32-bit single precision float representation of a Number
  8582. * @param value A Number. If the parameter is of a different type, it will get converted
  8583. * to a number or to NaN if it cannot be converted
  8584. * @returns number
  8585. */
  8586. Tools.FloatRound = function (value) {
  8587. if (Math.fround) {
  8588. return Math.fround(value);
  8589. }
  8590. return (Tools._tmpFloatArray[0] = value);
  8591. };
  8592. /**
  8593. * Find the next highest power of two.
  8594. * @param x Number to start search from.
  8595. * @return Next highest power of two.
  8596. */
  8597. Tools.CeilingPOT = function (x) {
  8598. x--;
  8599. x |= x >> 1;
  8600. x |= x >> 2;
  8601. x |= x >> 4;
  8602. x |= x >> 8;
  8603. x |= x >> 16;
  8604. x++;
  8605. return x;
  8606. };
  8607. /**
  8608. * Find the next lowest power of two.
  8609. * @param x Number to start search from.
  8610. * @return Next lowest power of two.
  8611. */
  8612. Tools.FloorPOT = function (x) {
  8613. x = x | (x >> 1);
  8614. x = x | (x >> 2);
  8615. x = x | (x >> 4);
  8616. x = x | (x >> 8);
  8617. x = x | (x >> 16);
  8618. return x - (x >> 1);
  8619. };
  8620. /**
  8621. * Find the nearest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next nearest power of two.
  8624. */
  8625. Tools.NearestPOT = function (x) {
  8626. var c = Tools.CeilingPOT(x);
  8627. var f = Tools.FloorPOT(x);
  8628. return (c - x) > (x - f) ? f : c;
  8629. };
  8630. Tools.GetExponentOfTwo = function (value, max, mode) {
  8631. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8632. var pot;
  8633. switch (mode) {
  8634. case BABYLON.Engine.SCALEMODE_FLOOR:
  8635. pot = Tools.FloorPOT(value);
  8636. break;
  8637. case BABYLON.Engine.SCALEMODE_NEAREST:
  8638. pot = Tools.NearestPOT(value);
  8639. break;
  8640. case BABYLON.Engine.SCALEMODE_CEILING:
  8641. default:
  8642. pot = Tools.CeilingPOT(value);
  8643. break;
  8644. }
  8645. return Math.min(pot, max);
  8646. };
  8647. Tools.GetFilename = function (path) {
  8648. var index = path.lastIndexOf("/");
  8649. if (index < 0)
  8650. return path;
  8651. return path.substring(index + 1);
  8652. };
  8653. /**
  8654. * Extracts the "folder" part of a path (everything before the filename).
  8655. * @param uri The URI to extract the info from
  8656. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8657. * @returns The "folder" part of the path
  8658. */
  8659. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8660. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8661. var index = uri.lastIndexOf("/");
  8662. if (index < 0) {
  8663. if (returnUnchangedIfNoSlash) {
  8664. return uri;
  8665. }
  8666. return "";
  8667. }
  8668. return uri.substring(0, index + 1);
  8669. };
  8670. Tools.GetDOMTextContent = function (element) {
  8671. var result = "";
  8672. var child = element.firstChild;
  8673. while (child) {
  8674. if (child.nodeType === 3) {
  8675. result += child.textContent;
  8676. }
  8677. child = child.nextSibling;
  8678. }
  8679. return result;
  8680. };
  8681. Tools.ToDegrees = function (angle) {
  8682. return angle * 180 / Math.PI;
  8683. };
  8684. Tools.ToRadians = function (angle) {
  8685. return angle * Math.PI / 180;
  8686. };
  8687. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8688. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8689. var output = "";
  8690. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8691. var i = 0;
  8692. var bytes = new Uint8Array(buffer);
  8693. while (i < bytes.length) {
  8694. chr1 = bytes[i++];
  8695. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8696. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8697. enc1 = chr1 >> 2;
  8698. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8699. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8700. enc4 = chr3 & 63;
  8701. if (isNaN(chr2)) {
  8702. enc3 = enc4 = 64;
  8703. }
  8704. else if (isNaN(chr3)) {
  8705. enc4 = 64;
  8706. }
  8707. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8708. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8709. }
  8710. return "data:image/png;base64," + output;
  8711. };
  8712. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8713. if (bias === void 0) { bias = null; }
  8714. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8715. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8716. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8717. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8718. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8719. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8720. }
  8721. if (bias) {
  8722. minimum.x -= minimum.x * bias.x + bias.y;
  8723. minimum.y -= minimum.y * bias.x + bias.y;
  8724. minimum.z -= minimum.z * bias.x + bias.y;
  8725. maximum.x += maximum.x * bias.x + bias.y;
  8726. maximum.y += maximum.y * bias.x + bias.y;
  8727. maximum.z += maximum.z * bias.x + bias.y;
  8728. }
  8729. return {
  8730. minimum: minimum,
  8731. maximum: maximum
  8732. };
  8733. };
  8734. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8735. if (bias === void 0) { bias = null; }
  8736. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8737. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8738. if (!stride) {
  8739. stride = 3;
  8740. }
  8741. for (var index = start; index < start + count; index++) {
  8742. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8743. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8744. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8745. }
  8746. if (bias) {
  8747. minimum.x -= minimum.x * bias.x + bias.y;
  8748. minimum.y -= minimum.y * bias.x + bias.y;
  8749. minimum.z -= minimum.z * bias.x + bias.y;
  8750. maximum.x += maximum.x * bias.x + bias.y;
  8751. maximum.y += maximum.y * bias.x + bias.y;
  8752. maximum.z += maximum.z * bias.x + bias.y;
  8753. }
  8754. return {
  8755. minimum: minimum,
  8756. maximum: maximum
  8757. };
  8758. };
  8759. Tools.Vector2ArrayFeeder = function (array) {
  8760. return function (index) {
  8761. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8762. var length = isFloatArray ? array.length / 2 : array.length;
  8763. if (index >= length) {
  8764. return null;
  8765. }
  8766. if (isFloatArray) {
  8767. var fa = array;
  8768. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8769. }
  8770. var a = array;
  8771. return a[index];
  8772. };
  8773. };
  8774. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8775. if (bias === void 0) { bias = null; }
  8776. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8777. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8778. var i = 0;
  8779. var cur = feeder(i++);
  8780. while (cur) {
  8781. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8782. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8783. cur = feeder(i++);
  8784. }
  8785. if (bias) {
  8786. minimum.x -= minimum.x * bias.x + bias.y;
  8787. minimum.y -= minimum.y * bias.x + bias.y;
  8788. maximum.x += maximum.x * bias.x + bias.y;
  8789. maximum.y += maximum.y * bias.x + bias.y;
  8790. }
  8791. return {
  8792. minimum: minimum,
  8793. maximum: maximum
  8794. };
  8795. };
  8796. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8797. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8798. return null;
  8799. return Array.isArray(obj) ? obj : [obj];
  8800. };
  8801. // Misc.
  8802. Tools.GetPointerPrefix = function () {
  8803. var eventPrefix = "pointer";
  8804. // Check if pointer events are supported
  8805. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8806. eventPrefix = "mouse";
  8807. }
  8808. return eventPrefix;
  8809. };
  8810. /**
  8811. * @param func - the function to be called
  8812. * @param requester - the object that will request the next frame. Falls back to window.
  8813. */
  8814. Tools.QueueNewFrame = function (func, requester) {
  8815. if (!Tools.IsWindowObjectExist()) {
  8816. return setTimeout(func, 16);
  8817. }
  8818. if (!requester) {
  8819. requester = window;
  8820. }
  8821. if (requester.requestAnimationFrame) {
  8822. return requester.requestAnimationFrame(func);
  8823. }
  8824. else if (requester.msRequestAnimationFrame) {
  8825. return requester.msRequestAnimationFrame(func);
  8826. }
  8827. else if (requester.webkitRequestAnimationFrame) {
  8828. return requester.webkitRequestAnimationFrame(func);
  8829. }
  8830. else if (requester.mozRequestAnimationFrame) {
  8831. return requester.mozRequestAnimationFrame(func);
  8832. }
  8833. else if (requester.oRequestAnimationFrame) {
  8834. return requester.oRequestAnimationFrame(func);
  8835. }
  8836. else {
  8837. return window.setTimeout(func, 16);
  8838. }
  8839. };
  8840. Tools.RequestFullscreen = function (element) {
  8841. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8842. if (!requestFunction)
  8843. return;
  8844. requestFunction.call(element);
  8845. };
  8846. Tools.ExitFullscreen = function () {
  8847. if (document.exitFullscreen) {
  8848. document.exitFullscreen();
  8849. }
  8850. else if (document.mozCancelFullScreen) {
  8851. document.mozCancelFullScreen();
  8852. }
  8853. else if (document.webkitCancelFullScreen) {
  8854. document.webkitCancelFullScreen();
  8855. }
  8856. else if (document.msCancelFullScreen) {
  8857. document.msCancelFullScreen();
  8858. }
  8859. };
  8860. Tools.SetCorsBehavior = function (url, element) {
  8861. if (url && url.indexOf("data:") === 0) {
  8862. return;
  8863. }
  8864. if (Tools.CorsBehavior) {
  8865. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8866. element.crossOrigin = Tools.CorsBehavior;
  8867. }
  8868. else {
  8869. var result = Tools.CorsBehavior(url);
  8870. if (result) {
  8871. element.crossOrigin = result;
  8872. }
  8873. }
  8874. }
  8875. };
  8876. // External files
  8877. Tools.CleanUrl = function (url) {
  8878. url = url.replace(/#/mg, "%23");
  8879. return url;
  8880. };
  8881. Tools.LoadImage = function (url, onLoad, onError, database) {
  8882. if (url instanceof ArrayBuffer) {
  8883. url = Tools.EncodeArrayBufferTobase64(url);
  8884. }
  8885. url = Tools.CleanUrl(url);
  8886. url = Tools.PreprocessUrl(url);
  8887. var img = new Image();
  8888. Tools.SetCorsBehavior(url, img);
  8889. var loadHandler = function () {
  8890. img.removeEventListener("load", loadHandler);
  8891. img.removeEventListener("error", errorHandler);
  8892. onLoad(img);
  8893. };
  8894. var errorHandler = function (err) {
  8895. img.removeEventListener("load", loadHandler);
  8896. img.removeEventListener("error", errorHandler);
  8897. Tools.Error("Error while trying to load image: " + url);
  8898. if (onError) {
  8899. onError("Error while trying to load image: " + url, err);
  8900. }
  8901. };
  8902. img.addEventListener("load", loadHandler);
  8903. img.addEventListener("error", errorHandler);
  8904. var noIndexedDB = function () {
  8905. img.src = url;
  8906. };
  8907. var loadFromIndexedDB = function () {
  8908. if (database) {
  8909. database.loadImageFromDB(url, img);
  8910. }
  8911. };
  8912. //ANY database to do!
  8913. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8914. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8915. }
  8916. else {
  8917. if (url.indexOf("file:") !== -1) {
  8918. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8919. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8920. try {
  8921. var blobURL;
  8922. try {
  8923. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8924. }
  8925. catch (ex) {
  8926. // Chrome doesn't support oneTimeOnly parameter
  8927. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8928. }
  8929. img.src = blobURL;
  8930. }
  8931. catch (e) {
  8932. img.src = "";
  8933. }
  8934. return img;
  8935. }
  8936. }
  8937. noIndexedDB();
  8938. }
  8939. return img;
  8940. };
  8941. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8942. url = Tools.CleanUrl(url);
  8943. url = Tools.PreprocessUrl(url);
  8944. // If file and file input are set
  8945. if (url.indexOf("file:") !== -1) {
  8946. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8947. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8948. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8949. }
  8950. }
  8951. var loadUrl = Tools.BaseUrl + url;
  8952. var aborted = false;
  8953. var fileRequest = {
  8954. onCompleteObservable: new BABYLON.Observable(),
  8955. abort: function () { return aborted = true; },
  8956. };
  8957. var requestFile = function () {
  8958. var request = new XMLHttpRequest();
  8959. var retryHandle = null;
  8960. fileRequest.abort = function () {
  8961. aborted = true;
  8962. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8963. request.abort();
  8964. }
  8965. if (retryHandle !== null) {
  8966. clearTimeout(retryHandle);
  8967. retryHandle = null;
  8968. }
  8969. };
  8970. var retryLoop = function (retryIndex) {
  8971. request.open('GET', loadUrl, true);
  8972. if (useArrayBuffer) {
  8973. request.responseType = "arraybuffer";
  8974. }
  8975. if (onProgress) {
  8976. request.addEventListener("progress", onProgress);
  8977. }
  8978. var onLoadEnd = function () {
  8979. request.removeEventListener("loadend", onLoadEnd);
  8980. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8981. fileRequest.onCompleteObservable.clear();
  8982. };
  8983. request.addEventListener("loadend", onLoadEnd);
  8984. var onReadyStateChange = function () {
  8985. if (aborted) {
  8986. return;
  8987. }
  8988. // In case of undefined state in some browsers.
  8989. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8990. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8991. request.removeEventListener("readystatechange", onReadyStateChange);
  8992. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8993. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8994. return;
  8995. }
  8996. var retryStrategy = Tools.DefaultRetryStrategy;
  8997. if (retryStrategy) {
  8998. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8999. if (waitTime !== -1) {
  9000. // Prevent the request from completing for retry.
  9001. request.removeEventListener("loadend", onLoadEnd);
  9002. request = new XMLHttpRequest();
  9003. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9004. return;
  9005. }
  9006. }
  9007. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9008. if (onError) {
  9009. onError(request, e);
  9010. }
  9011. else {
  9012. throw e;
  9013. }
  9014. }
  9015. };
  9016. request.addEventListener("readystatechange", onReadyStateChange);
  9017. request.send();
  9018. };
  9019. retryLoop(0);
  9020. };
  9021. // Caching all files
  9022. if (database && database.enableSceneOffline) {
  9023. var noIndexedDB_1 = function () {
  9024. if (!aborted) {
  9025. requestFile();
  9026. }
  9027. };
  9028. var loadFromIndexedDB = function () {
  9029. // TODO: database needs to support aborting and should return a IFileRequest
  9030. if (aborted) {
  9031. return;
  9032. }
  9033. if (database) {
  9034. database.loadFileFromDB(url, function (data) {
  9035. if (!aborted) {
  9036. onSuccess(data);
  9037. }
  9038. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9039. }, onProgress ? function (event) {
  9040. if (!aborted) {
  9041. onProgress(event);
  9042. }
  9043. } : undefined, noIndexedDB_1, useArrayBuffer);
  9044. }
  9045. };
  9046. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9047. }
  9048. else {
  9049. requestFile();
  9050. }
  9051. return fileRequest;
  9052. };
  9053. /**
  9054. * Load a script (identified by an url). When the url returns, the
  9055. * content of this file is added into a new script element, attached to the DOM (body element)
  9056. */
  9057. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9058. var head = document.getElementsByTagName('head')[0];
  9059. var script = document.createElement('script');
  9060. script.type = 'text/javascript';
  9061. script.src = scriptUrl;
  9062. script.onload = function () {
  9063. if (onSuccess) {
  9064. onSuccess();
  9065. }
  9066. };
  9067. script.onerror = function (e) {
  9068. if (onError) {
  9069. onError("Unable to load script '" + scriptUrl + "'", e);
  9070. }
  9071. };
  9072. head.appendChild(script);
  9073. };
  9074. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9075. var reader = new FileReader();
  9076. var request = {
  9077. onCompleteObservable: new BABYLON.Observable(),
  9078. abort: function () { return reader.abort(); },
  9079. };
  9080. reader.onloadend = function (e) {
  9081. request.onCompleteObservable.notifyObservers(request);
  9082. };
  9083. reader.onload = function (e) {
  9084. //target doesn't have result from ts 1.3
  9085. callback(e.target['result']);
  9086. };
  9087. reader.onprogress = progressCallback;
  9088. reader.readAsDataURL(fileToLoad);
  9089. return request;
  9090. };
  9091. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9092. var reader = new FileReader();
  9093. var request = {
  9094. onCompleteObservable: new BABYLON.Observable(),
  9095. abort: function () { return reader.abort(); },
  9096. };
  9097. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9098. reader.onerror = function (e) {
  9099. Tools.Log("Error while reading file: " + fileToLoad.name);
  9100. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9101. };
  9102. reader.onload = function (e) {
  9103. //target doesn't have result from ts 1.3
  9104. callback(e.target['result']);
  9105. };
  9106. if (progressCallBack) {
  9107. reader.onprogress = progressCallBack;
  9108. }
  9109. if (!useArrayBuffer) {
  9110. // Asynchronous read
  9111. reader.readAsText(fileToLoad);
  9112. }
  9113. else {
  9114. reader.readAsArrayBuffer(fileToLoad);
  9115. }
  9116. return request;
  9117. };
  9118. //returns a downloadable url to a file content.
  9119. Tools.FileAsURL = function (content) {
  9120. var fileBlob = new Blob([content]);
  9121. var url = window.URL || window.webkitURL;
  9122. var link = url.createObjectURL(fileBlob);
  9123. return link;
  9124. };
  9125. // Misc.
  9126. Tools.Format = function (value, decimals) {
  9127. if (decimals === void 0) { decimals = 2; }
  9128. return value.toFixed(decimals);
  9129. };
  9130. Tools.CheckExtends = function (v, min, max) {
  9131. if (v.x < min.x)
  9132. min.x = v.x;
  9133. if (v.y < min.y)
  9134. min.y = v.y;
  9135. if (v.z < min.z)
  9136. min.z = v.z;
  9137. if (v.x > max.x)
  9138. max.x = v.x;
  9139. if (v.y > max.y)
  9140. max.y = v.y;
  9141. if (v.z > max.z)
  9142. max.z = v.z;
  9143. };
  9144. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9145. for (var prop in source) {
  9146. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9147. continue;
  9148. }
  9149. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9150. continue;
  9151. }
  9152. var sourceValue = source[prop];
  9153. var typeOfSourceValue = typeof sourceValue;
  9154. if (typeOfSourceValue === "function") {
  9155. continue;
  9156. }
  9157. try {
  9158. if (typeOfSourceValue === "object") {
  9159. if (sourceValue instanceof Array) {
  9160. destination[prop] = [];
  9161. if (sourceValue.length > 0) {
  9162. if (typeof sourceValue[0] == "object") {
  9163. for (var index = 0; index < sourceValue.length; index++) {
  9164. var clonedValue = cloneValue(sourceValue[index], destination);
  9165. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9166. destination[prop].push(clonedValue);
  9167. }
  9168. }
  9169. }
  9170. else {
  9171. destination[prop] = sourceValue.slice(0);
  9172. }
  9173. }
  9174. }
  9175. else {
  9176. destination[prop] = cloneValue(sourceValue, destination);
  9177. }
  9178. }
  9179. else {
  9180. destination[prop] = sourceValue;
  9181. }
  9182. }
  9183. catch (e) {
  9184. // Just ignore error (it could be because of a read-only property)
  9185. }
  9186. }
  9187. };
  9188. Tools.IsEmpty = function (obj) {
  9189. for (var i in obj) {
  9190. if (obj.hasOwnProperty(i)) {
  9191. return false;
  9192. }
  9193. }
  9194. return true;
  9195. };
  9196. Tools.RegisterTopRootEvents = function (events) {
  9197. for (var index = 0; index < events.length; index++) {
  9198. var event = events[index];
  9199. window.addEventListener(event.name, event.handler, false);
  9200. try {
  9201. if (window.parent) {
  9202. window.parent.addEventListener(event.name, event.handler, false);
  9203. }
  9204. }
  9205. catch (e) {
  9206. // Silently fails...
  9207. }
  9208. }
  9209. };
  9210. Tools.UnregisterTopRootEvents = function (events) {
  9211. for (var index = 0; index < events.length; index++) {
  9212. var event = events[index];
  9213. window.removeEventListener(event.name, event.handler);
  9214. try {
  9215. if (window.parent) {
  9216. window.parent.removeEventListener(event.name, event.handler);
  9217. }
  9218. }
  9219. catch (e) {
  9220. // Silently fails...
  9221. }
  9222. }
  9223. };
  9224. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9225. if (mimeType === void 0) { mimeType = "image/png"; }
  9226. // Read the contents of the framebuffer
  9227. var numberOfChannelsByLine = width * 4;
  9228. var halfHeight = height / 2;
  9229. //Reading datas from WebGL
  9230. var data = engine.readPixels(0, 0, width, height);
  9231. //To flip image on Y axis.
  9232. for (var i = 0; i < halfHeight; i++) {
  9233. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9234. var currentCell = j + i * numberOfChannelsByLine;
  9235. var targetLine = height - i - 1;
  9236. var targetCell = j + targetLine * numberOfChannelsByLine;
  9237. var temp = data[currentCell];
  9238. data[currentCell] = data[targetCell];
  9239. data[targetCell] = temp;
  9240. }
  9241. }
  9242. // Create a 2D canvas to store the result
  9243. if (!screenshotCanvas) {
  9244. screenshotCanvas = document.createElement('canvas');
  9245. }
  9246. screenshotCanvas.width = width;
  9247. screenshotCanvas.height = height;
  9248. var context = screenshotCanvas.getContext('2d');
  9249. if (context) {
  9250. // Copy the pixels to a 2D canvas
  9251. var imageData = context.createImageData(width, height);
  9252. var castData = (imageData.data);
  9253. castData.set(data);
  9254. context.putImageData(imageData, 0, 0);
  9255. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9256. }
  9257. };
  9258. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9259. if (mimeType === void 0) { mimeType = "image/png"; }
  9260. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9261. if (successCallback) {
  9262. successCallback(base64Image);
  9263. }
  9264. else {
  9265. // We need HTMLCanvasElement.toBlob for HD screenshots
  9266. if (!screenshotCanvas.toBlob) {
  9267. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9268. screenshotCanvas.toBlob = function (callback, type, quality) {
  9269. var _this = this;
  9270. setTimeout(function () {
  9271. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9272. for (var i = 0; i < len; i++) {
  9273. arr[i] = binStr.charCodeAt(i);
  9274. }
  9275. callback(new Blob([arr], { type: type || 'image/png' }));
  9276. });
  9277. };
  9278. }
  9279. screenshotCanvas.toBlob(function (blob) {
  9280. var url = URL.createObjectURL(blob);
  9281. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9282. if (("download" in document.createElement("a"))) {
  9283. var a = window.document.createElement("a");
  9284. a.href = url;
  9285. if (fileName) {
  9286. a.setAttribute("download", fileName);
  9287. }
  9288. else {
  9289. var date = new Date();
  9290. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9291. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9292. }
  9293. window.document.body.appendChild(a);
  9294. a.addEventListener("click", function () {
  9295. if (a.parentElement) {
  9296. a.parentElement.removeChild(a);
  9297. }
  9298. });
  9299. a.click();
  9300. }
  9301. else {
  9302. var newWindow = window.open("");
  9303. if (!newWindow)
  9304. return;
  9305. var img = newWindow.document.createElement("img");
  9306. img.onload = function () {
  9307. // no longer need to read the blob so it's revoked
  9308. URL.revokeObjectURL(url);
  9309. };
  9310. img.src = url;
  9311. newWindow.document.body.appendChild(img);
  9312. }
  9313. });
  9314. }
  9315. };
  9316. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9317. if (mimeType === void 0) { mimeType = "image/png"; }
  9318. var width;
  9319. var height;
  9320. // If a precision value is specified
  9321. if (size.precision) {
  9322. width = Math.round(engine.getRenderWidth() * size.precision);
  9323. height = Math.round(width / engine.getAspectRatio(camera));
  9324. }
  9325. else if (size.width && size.height) {
  9326. width = size.width;
  9327. height = size.height;
  9328. }
  9329. //If passing only width, computing height to keep display canvas ratio.
  9330. else if (size.width && !size.height) {
  9331. width = size.width;
  9332. height = Math.round(width / engine.getAspectRatio(camera));
  9333. }
  9334. //If passing only height, computing width to keep display canvas ratio.
  9335. else if (size.height && !size.width) {
  9336. height = size.height;
  9337. width = Math.round(height * engine.getAspectRatio(camera));
  9338. }
  9339. //Assuming here that "size" parameter is a number
  9340. else if (!isNaN(size)) {
  9341. height = size;
  9342. width = size;
  9343. }
  9344. else {
  9345. Tools.Error("Invalid 'size' parameter !");
  9346. return;
  9347. }
  9348. if (!screenshotCanvas) {
  9349. screenshotCanvas = document.createElement('canvas');
  9350. }
  9351. screenshotCanvas.width = width;
  9352. screenshotCanvas.height = height;
  9353. var renderContext = screenshotCanvas.getContext("2d");
  9354. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9355. var newWidth = width;
  9356. var newHeight = newWidth / ratio;
  9357. if (newHeight > height) {
  9358. newHeight = height;
  9359. newWidth = newHeight * ratio;
  9360. }
  9361. var offsetX = Math.max(0, width - newWidth) / 2;
  9362. var offsetY = Math.max(0, height - newHeight) / 2;
  9363. var renderingCanvas = engine.getRenderingCanvas();
  9364. if (renderContext && renderingCanvas) {
  9365. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9366. }
  9367. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9368. };
  9369. /**
  9370. * Generates an image screenshot from the specified camera.
  9371. *
  9372. * @param engine The engine to use for rendering
  9373. * @param camera The camera to use for rendering
  9374. * @param size This parameter can be set to a single number or to an object with the
  9375. * following (optional) properties: precision, width, height. If a single number is passed,
  9376. * it will be used for both width and height. If an object is passed, the screenshot size
  9377. * will be derived from the parameters. The precision property is a multiplier allowing
  9378. * rendering at a higher or lower resolution.
  9379. * @param successCallback The callback receives a single parameter which contains the
  9380. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9381. * src parameter of an <img> to display it.
  9382. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9383. * Check your browser for supported MIME types.
  9384. * @param samples Texture samples (default: 1)
  9385. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9386. * @param fileName A name for for the downloaded file.
  9387. * @constructor
  9388. */
  9389. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9390. if (mimeType === void 0) { mimeType = "image/png"; }
  9391. if (samples === void 0) { samples = 1; }
  9392. if (antialiasing === void 0) { antialiasing = false; }
  9393. var width;
  9394. var height;
  9395. //If a precision value is specified
  9396. if (size.precision) {
  9397. width = Math.round(engine.getRenderWidth() * size.precision);
  9398. height = Math.round(width / engine.getAspectRatio(camera));
  9399. size = { width: width, height: height };
  9400. }
  9401. else if (size.width && size.height) {
  9402. width = size.width;
  9403. height = size.height;
  9404. }
  9405. //If passing only width, computing height to keep display canvas ratio.
  9406. else if (size.width && !size.height) {
  9407. width = size.width;
  9408. height = Math.round(width / engine.getAspectRatio(camera));
  9409. size = { width: width, height: height };
  9410. }
  9411. //If passing only height, computing width to keep display canvas ratio.
  9412. else if (size.height && !size.width) {
  9413. height = size.height;
  9414. width = Math.round(height * engine.getAspectRatio(camera));
  9415. size = { width: width, height: height };
  9416. }
  9417. //Assuming here that "size" parameter is a number
  9418. else if (!isNaN(size)) {
  9419. height = size;
  9420. width = size;
  9421. }
  9422. else {
  9423. Tools.Error("Invalid 'size' parameter !");
  9424. return;
  9425. }
  9426. var scene = camera.getScene();
  9427. var previousCamera = null;
  9428. if (scene.activeCamera !== camera) {
  9429. previousCamera = scene.activeCamera;
  9430. scene.activeCamera = camera;
  9431. }
  9432. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9433. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9434. texture.renderList = null;
  9435. texture.samples = samples;
  9436. if (antialiasing) {
  9437. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9438. }
  9439. texture.onAfterRenderObservable.add(function () {
  9440. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9441. });
  9442. scene.incrementRenderId();
  9443. scene.resetCachedMaterial();
  9444. texture.render(true);
  9445. texture.dispose();
  9446. if (previousCamera) {
  9447. scene.activeCamera = previousCamera;
  9448. }
  9449. camera.getProjectionMatrix(true); // Force cache refresh;
  9450. };
  9451. // XHR response validator for local file scenario
  9452. Tools.ValidateXHRData = function (xhr, dataType) {
  9453. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9454. if (dataType === void 0) { dataType = 7; }
  9455. try {
  9456. if (dataType & 1) {
  9457. if (xhr.responseText && xhr.responseText.length > 0) {
  9458. return true;
  9459. }
  9460. else if (dataType === 1) {
  9461. return false;
  9462. }
  9463. }
  9464. if (dataType & 2) {
  9465. // Check header width and height since there is no "TGA" magic number
  9466. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9467. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9468. return true;
  9469. }
  9470. else if (dataType === 2) {
  9471. return false;
  9472. }
  9473. }
  9474. if (dataType & 4) {
  9475. // Check for the "DDS" magic number
  9476. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9477. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9478. return true;
  9479. }
  9480. else {
  9481. return false;
  9482. }
  9483. }
  9484. }
  9485. catch (e) {
  9486. // Global protection
  9487. }
  9488. return false;
  9489. };
  9490. /**
  9491. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9492. * Be aware Math.random() could cause collisions, but:
  9493. * "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"
  9494. */
  9495. Tools.RandomId = function () {
  9496. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9497. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9498. return v.toString(16);
  9499. });
  9500. };
  9501. /**
  9502. * Test if the given uri is a base64 string.
  9503. * @param uri The uri to test
  9504. * @return True if the uri is a base64 string or false otherwise.
  9505. */
  9506. Tools.IsBase64 = function (uri) {
  9507. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9508. };
  9509. /**
  9510. * Decode the given base64 uri.
  9511. * @param uri The uri to decode
  9512. * @return The decoded base64 data.
  9513. */
  9514. Tools.DecodeBase64 = function (uri) {
  9515. var decodedString = atob(uri.split(",")[1]);
  9516. var bufferLength = decodedString.length;
  9517. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9518. for (var i = 0; i < bufferLength; i++) {
  9519. bufferView[i] = decodedString.charCodeAt(i);
  9520. }
  9521. return bufferView.buffer;
  9522. };
  9523. Object.defineProperty(Tools, "NoneLogLevel", {
  9524. get: function () {
  9525. return Tools._NoneLogLevel;
  9526. },
  9527. enumerable: true,
  9528. configurable: true
  9529. });
  9530. Object.defineProperty(Tools, "MessageLogLevel", {
  9531. get: function () {
  9532. return Tools._MessageLogLevel;
  9533. },
  9534. enumerable: true,
  9535. configurable: true
  9536. });
  9537. Object.defineProperty(Tools, "WarningLogLevel", {
  9538. get: function () {
  9539. return Tools._WarningLogLevel;
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. Object.defineProperty(Tools, "ErrorLogLevel", {
  9545. get: function () {
  9546. return Tools._ErrorLogLevel;
  9547. },
  9548. enumerable: true,
  9549. configurable: true
  9550. });
  9551. Object.defineProperty(Tools, "AllLogLevel", {
  9552. get: function () {
  9553. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9554. },
  9555. enumerable: true,
  9556. configurable: true
  9557. });
  9558. Tools._AddLogEntry = function (entry) {
  9559. Tools._LogCache = entry + Tools._LogCache;
  9560. if (Tools.OnNewCacheEntry) {
  9561. Tools.OnNewCacheEntry(entry);
  9562. }
  9563. };
  9564. Tools._FormatMessage = function (message) {
  9565. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9566. var date = new Date();
  9567. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9568. };
  9569. Tools._LogDisabled = function (message) {
  9570. // nothing to do
  9571. };
  9572. Tools._LogEnabled = function (message) {
  9573. var formattedMessage = Tools._FormatMessage(message);
  9574. console.log("BJS - " + formattedMessage);
  9575. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9576. Tools._AddLogEntry(entry);
  9577. };
  9578. Tools._WarnDisabled = function (message) {
  9579. // nothing to do
  9580. };
  9581. Tools._WarnEnabled = function (message) {
  9582. var formattedMessage = Tools._FormatMessage(message);
  9583. console.warn("BJS - " + formattedMessage);
  9584. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9585. Tools._AddLogEntry(entry);
  9586. };
  9587. Tools._ErrorDisabled = function (message) {
  9588. // nothing to do
  9589. };
  9590. Tools._ErrorEnabled = function (message) {
  9591. Tools.errorsCount++;
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.error("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Object.defineProperty(Tools, "LogCache", {
  9598. get: function () {
  9599. return Tools._LogCache;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Tools.ClearLogCache = function () {
  9605. Tools._LogCache = "";
  9606. Tools.errorsCount = 0;
  9607. };
  9608. Object.defineProperty(Tools, "LogLevels", {
  9609. set: function (level) {
  9610. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9611. Tools.Log = Tools._LogEnabled;
  9612. }
  9613. else {
  9614. Tools.Log = Tools._LogDisabled;
  9615. }
  9616. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9617. Tools.Warn = Tools._WarnEnabled;
  9618. }
  9619. else {
  9620. Tools.Warn = Tools._WarnDisabled;
  9621. }
  9622. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9623. Tools.Error = Tools._ErrorEnabled;
  9624. }
  9625. else {
  9626. Tools.Error = Tools._ErrorDisabled;
  9627. }
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. Tools.IsWindowObjectExist = function () {
  9633. return (typeof window) !== "undefined";
  9634. };
  9635. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9636. get: function () {
  9637. return Tools._PerformanceNoneLogLevel;
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9643. get: function () {
  9644. return Tools._PerformanceUserMarkLogLevel;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9650. get: function () {
  9651. return Tools._PerformanceConsoleLogLevel;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9657. set: function (level) {
  9658. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9659. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9660. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9661. return;
  9662. }
  9663. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9664. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9665. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9666. return;
  9667. }
  9668. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9669. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9675. };
  9676. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9677. };
  9678. Tools._StartUserMark = function (counterName, condition) {
  9679. if (condition === void 0) { condition = true; }
  9680. if (!Tools._performance) {
  9681. if (!Tools.IsWindowObjectExist()) {
  9682. return;
  9683. }
  9684. Tools._performance = window.performance;
  9685. }
  9686. if (!condition || !Tools._performance.mark) {
  9687. return;
  9688. }
  9689. Tools._performance.mark(counterName + "-Begin");
  9690. };
  9691. Tools._EndUserMark = function (counterName, condition) {
  9692. if (condition === void 0) { condition = true; }
  9693. if (!condition || !Tools._performance.mark) {
  9694. return;
  9695. }
  9696. Tools._performance.mark(counterName + "-End");
  9697. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9698. };
  9699. Tools._StartPerformanceConsole = function (counterName, condition) {
  9700. if (condition === void 0) { condition = true; }
  9701. if (!condition) {
  9702. return;
  9703. }
  9704. Tools._StartUserMark(counterName, condition);
  9705. if (console.time) {
  9706. console.time(counterName);
  9707. }
  9708. };
  9709. Tools._EndPerformanceConsole = function (counterName, condition) {
  9710. if (condition === void 0) { condition = true; }
  9711. if (!condition) {
  9712. return;
  9713. }
  9714. Tools._EndUserMark(counterName, condition);
  9715. if (console.time) {
  9716. console.timeEnd(counterName);
  9717. }
  9718. };
  9719. Object.defineProperty(Tools, "Now", {
  9720. get: function () {
  9721. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9722. return window.performance.now();
  9723. }
  9724. return Date.now();
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. /**
  9730. * This method will return the name of the class used to create the instance of the given object.
  9731. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9732. * @param object the object to get the class name from
  9733. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9734. */
  9735. Tools.GetClassName = function (object, isType) {
  9736. if (isType === void 0) { isType = false; }
  9737. var name = null;
  9738. if (!isType && object.getClassName) {
  9739. name = object.getClassName();
  9740. }
  9741. else {
  9742. if (object instanceof Object) {
  9743. var classObj = isType ? object : Object.getPrototypeOf(object);
  9744. name = classObj.constructor["__bjsclassName__"];
  9745. }
  9746. if (!name) {
  9747. name = typeof object;
  9748. }
  9749. }
  9750. return name;
  9751. };
  9752. Tools.First = function (array, predicate) {
  9753. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9754. var el = array_1[_i];
  9755. if (predicate(el)) {
  9756. return el;
  9757. }
  9758. }
  9759. return null;
  9760. };
  9761. /**
  9762. * This method will return the name of the full name of the class, including its owning module (if any).
  9763. * 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).
  9764. * @param object the object to get the class name from
  9765. * @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.
  9766. */
  9767. Tools.getFullClassName = function (object, isType) {
  9768. if (isType === void 0) { isType = false; }
  9769. var className = null;
  9770. var moduleName = null;
  9771. if (!isType && object.getClassName) {
  9772. className = object.getClassName();
  9773. }
  9774. else {
  9775. if (object instanceof Object) {
  9776. var classObj = isType ? object : Object.getPrototypeOf(object);
  9777. className = classObj.constructor["__bjsclassName__"];
  9778. moduleName = classObj.constructor["__bjsmoduleName__"];
  9779. }
  9780. if (!className) {
  9781. className = typeof object;
  9782. }
  9783. }
  9784. if (!className) {
  9785. return null;
  9786. }
  9787. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9788. };
  9789. /**
  9790. * 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.
  9791. * @param array
  9792. */
  9793. Tools.arrayOrStringFeeder = function (array) {
  9794. return function (index) {
  9795. if (index >= array.length) {
  9796. return null;
  9797. }
  9798. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9799. if (val && val.getHashCode) {
  9800. val = val.getHashCode();
  9801. }
  9802. if (typeof val === "string") {
  9803. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9804. }
  9805. return val;
  9806. };
  9807. };
  9808. /**
  9809. * Compute the hashCode of a stream of number
  9810. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9811. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9812. * @return the hash code computed
  9813. */
  9814. Tools.hashCodeFromStream = function (feeder) {
  9815. // Based from here: http://stackoverflow.com/a/7616484/802124
  9816. var hash = 0;
  9817. var index = 0;
  9818. var chr = feeder(index++);
  9819. while (chr != null) {
  9820. hash = ((hash << 5) - hash) + chr;
  9821. hash |= 0; // Convert to 32bit integer
  9822. chr = feeder(index++);
  9823. }
  9824. return hash;
  9825. };
  9826. /**
  9827. * Returns a promise that resolves after the given amount of time.
  9828. * @param delay Number of milliseconds to delay
  9829. * @returns Promise that resolves after the given amount of time
  9830. */
  9831. Tools.DelayAsync = function (delay) {
  9832. return new Promise(function (resolve) {
  9833. setTimeout(function () {
  9834. resolve();
  9835. }, delay);
  9836. });
  9837. };
  9838. Tools.BaseUrl = "";
  9839. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9840. /**
  9841. * Default behaviour for cors in the application.
  9842. * It can be a string if the expected behavior is identical in the entire app.
  9843. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9844. */
  9845. Tools.CorsBehavior = "anonymous";
  9846. Tools.UseFallbackTexture = true;
  9847. /**
  9848. * Use this object to register external classes like custom textures or material
  9849. * to allow the laoders to instantiate them
  9850. */
  9851. Tools.RegisteredExternalClasses = {};
  9852. // Used in case of a texture loading problem
  9853. 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";
  9854. Tools._tmpFloatArray = new Float32Array(1);
  9855. Tools.PreprocessUrl = function (url) {
  9856. return url;
  9857. };
  9858. // Logs
  9859. Tools._NoneLogLevel = 0;
  9860. Tools._MessageLogLevel = 1;
  9861. Tools._WarningLogLevel = 2;
  9862. Tools._ErrorLogLevel = 4;
  9863. Tools._LogCache = "";
  9864. Tools.errorsCount = 0;
  9865. Tools.Log = Tools._LogEnabled;
  9866. Tools.Warn = Tools._WarnEnabled;
  9867. Tools.Error = Tools._ErrorEnabled;
  9868. // Performances
  9869. Tools._PerformanceNoneLogLevel = 0;
  9870. Tools._PerformanceUserMarkLogLevel = 1;
  9871. Tools._PerformanceConsoleLogLevel = 2;
  9872. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9873. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9874. return Tools;
  9875. }());
  9876. BABYLON.Tools = Tools;
  9877. /**
  9878. * This class is used to track a performance counter which is number based.
  9879. * The user has access to many properties which give statistics of different nature
  9880. *
  9881. * The implementer can track two kinds of Performance Counter: time and count
  9882. * 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.
  9883. * 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.
  9884. */
  9885. var PerfCounter = /** @class */ (function () {
  9886. function PerfCounter() {
  9887. this._startMonitoringTime = 0;
  9888. this._min = 0;
  9889. this._max = 0;
  9890. this._average = 0;
  9891. this._lastSecAverage = 0;
  9892. this._current = 0;
  9893. this._totalValueCount = 0;
  9894. this._totalAccumulated = 0;
  9895. this._lastSecAccumulated = 0;
  9896. this._lastSecTime = 0;
  9897. this._lastSecValueCount = 0;
  9898. }
  9899. Object.defineProperty(PerfCounter.prototype, "min", {
  9900. /**
  9901. * Returns the smallest value ever
  9902. */
  9903. get: function () {
  9904. return this._min;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(PerfCounter.prototype, "max", {
  9910. /**
  9911. * Returns the biggest value ever
  9912. */
  9913. get: function () {
  9914. return this._max;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(PerfCounter.prototype, "average", {
  9920. /**
  9921. * Returns the average value since the performance counter is running
  9922. */
  9923. get: function () {
  9924. return this._average;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9930. /**
  9931. * Returns the average value of the last second the counter was monitored
  9932. */
  9933. get: function () {
  9934. return this._lastSecAverage;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(PerfCounter.prototype, "current", {
  9940. /**
  9941. * Returns the current value
  9942. */
  9943. get: function () {
  9944. return this._current;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(PerfCounter.prototype, "total", {
  9950. get: function () {
  9951. return this._totalAccumulated;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(PerfCounter.prototype, "count", {
  9957. get: function () {
  9958. return this._totalValueCount;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. /**
  9964. * Call this method to start monitoring a new frame.
  9965. * 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.
  9966. */
  9967. PerfCounter.prototype.fetchNewFrame = function () {
  9968. this._totalValueCount++;
  9969. this._current = 0;
  9970. this._lastSecValueCount++;
  9971. };
  9972. /**
  9973. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9974. * @param newCount the count value to add to the monitored count
  9975. * @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.
  9976. */
  9977. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9978. if (!PerfCounter.Enabled) {
  9979. return;
  9980. }
  9981. this._current += newCount;
  9982. if (fetchResult) {
  9983. this._fetchResult();
  9984. }
  9985. };
  9986. /**
  9987. * Start monitoring this performance counter
  9988. */
  9989. PerfCounter.prototype.beginMonitoring = function () {
  9990. if (!PerfCounter.Enabled) {
  9991. return;
  9992. }
  9993. this._startMonitoringTime = Tools.Now;
  9994. };
  9995. /**
  9996. * Compute the time lapsed since the previous beginMonitoring() call.
  9997. * @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
  9998. */
  9999. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10000. if (newFrame === void 0) { newFrame = true; }
  10001. if (!PerfCounter.Enabled) {
  10002. return;
  10003. }
  10004. if (newFrame) {
  10005. this.fetchNewFrame();
  10006. }
  10007. var currentTime = Tools.Now;
  10008. this._current = currentTime - this._startMonitoringTime;
  10009. if (newFrame) {
  10010. this._fetchResult();
  10011. }
  10012. };
  10013. PerfCounter.prototype._fetchResult = function () {
  10014. this._totalAccumulated += this._current;
  10015. this._lastSecAccumulated += this._current;
  10016. // Min/Max update
  10017. this._min = Math.min(this._min, this._current);
  10018. this._max = Math.max(this._max, this._current);
  10019. this._average = this._totalAccumulated / this._totalValueCount;
  10020. // Reset last sec?
  10021. var now = Tools.Now;
  10022. if ((now - this._lastSecTime) > 1000) {
  10023. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10024. this._lastSecTime = now;
  10025. this._lastSecAccumulated = 0;
  10026. this._lastSecValueCount = 0;
  10027. }
  10028. };
  10029. PerfCounter.Enabled = true;
  10030. return PerfCounter;
  10031. }());
  10032. BABYLON.PerfCounter = PerfCounter;
  10033. /**
  10034. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10035. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10036. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10037. * @param name The name of the class, case should be preserved
  10038. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10039. */
  10040. function className(name, module) {
  10041. return function (target) {
  10042. target["__bjsclassName__"] = name;
  10043. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10044. };
  10045. }
  10046. BABYLON.className = className;
  10047. /**
  10048. * An implementation of a loop for asynchronous functions.
  10049. */
  10050. var AsyncLoop = /** @class */ (function () {
  10051. /**
  10052. * Constroctor.
  10053. * @param iterations the number of iterations.
  10054. * @param _fn the function to run each iteration
  10055. * @param _successCallback the callback that will be called upon succesful execution
  10056. * @param offset starting offset.
  10057. */
  10058. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10059. if (offset === void 0) { offset = 0; }
  10060. this.iterations = iterations;
  10061. this._fn = _fn;
  10062. this._successCallback = _successCallback;
  10063. this.index = offset - 1;
  10064. this._done = false;
  10065. }
  10066. /**
  10067. * Execute the next iteration. Must be called after the last iteration was finished.
  10068. */
  10069. AsyncLoop.prototype.executeNext = function () {
  10070. if (!this._done) {
  10071. if (this.index + 1 < this.iterations) {
  10072. ++this.index;
  10073. this._fn(this);
  10074. }
  10075. else {
  10076. this.breakLoop();
  10077. }
  10078. }
  10079. };
  10080. /**
  10081. * Break the loop and run the success callback.
  10082. */
  10083. AsyncLoop.prototype.breakLoop = function () {
  10084. this._done = true;
  10085. this._successCallback();
  10086. };
  10087. /**
  10088. * Helper function
  10089. */
  10090. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10091. if (offset === void 0) { offset = 0; }
  10092. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10093. loop.executeNext();
  10094. return loop;
  10095. };
  10096. /**
  10097. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10098. * @param iterations total number of iterations
  10099. * @param syncedIterations number of synchronous iterations in each async iteration.
  10100. * @param fn the function to call each iteration.
  10101. * @param callback a success call back that will be called when iterating stops.
  10102. * @param breakFunction a break condition (optional)
  10103. * @param timeout timeout settings for the setTimeout function. default - 0.
  10104. * @constructor
  10105. */
  10106. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10107. if (timeout === void 0) { timeout = 0; }
  10108. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10109. if (breakFunction && breakFunction())
  10110. loop.breakLoop();
  10111. else {
  10112. setTimeout(function () {
  10113. for (var i = 0; i < syncedIterations; ++i) {
  10114. var iteration = (loop.index * syncedIterations) + i;
  10115. if (iteration >= iterations)
  10116. break;
  10117. fn(iteration);
  10118. if (breakFunction && breakFunction()) {
  10119. loop.breakLoop();
  10120. break;
  10121. }
  10122. }
  10123. loop.executeNext();
  10124. }, timeout);
  10125. }
  10126. }, callback);
  10127. };
  10128. return AsyncLoop;
  10129. }());
  10130. BABYLON.AsyncLoop = AsyncLoop;
  10131. })(BABYLON || (BABYLON = {}));
  10132. //# sourceMappingURL=babylon.tools.js.map
  10133. var BABYLON;
  10134. (function (BABYLON) {
  10135. var PromiseStates;
  10136. (function (PromiseStates) {
  10137. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10138. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10139. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10140. })(PromiseStates || (PromiseStates = {}));
  10141. var FulFillmentAgregator = /** @class */ (function () {
  10142. function FulFillmentAgregator() {
  10143. this.count = 0;
  10144. this.target = 0;
  10145. this.results = [];
  10146. }
  10147. return FulFillmentAgregator;
  10148. }());
  10149. var InternalPromise = /** @class */ (function () {
  10150. function InternalPromise(resolver) {
  10151. var _this = this;
  10152. this._state = PromiseStates.Pending;
  10153. this._children = new Array();
  10154. this._rejectWasConsumed = false;
  10155. if (!resolver) {
  10156. return;
  10157. }
  10158. try {
  10159. resolver(function (value) {
  10160. _this._resolve(value);
  10161. }, function (reason) {
  10162. _this._reject(reason);
  10163. });
  10164. }
  10165. catch (e) {
  10166. this._reject(e);
  10167. }
  10168. }
  10169. Object.defineProperty(InternalPromise.prototype, "_result", {
  10170. get: function () {
  10171. return this._resultValue;
  10172. },
  10173. set: function (value) {
  10174. this._resultValue = value;
  10175. if (this._parent && this._parent._result === undefined) {
  10176. this._parent._result = value;
  10177. }
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. InternalPromise.prototype.catch = function (onRejected) {
  10183. return this.then(undefined, onRejected);
  10184. };
  10185. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10186. var _this = this;
  10187. var newPromise = new InternalPromise();
  10188. newPromise._onFulfilled = onFulfilled;
  10189. newPromise._onRejected = onRejected;
  10190. // Composition
  10191. this._children.push(newPromise);
  10192. newPromise._parent = this;
  10193. if (this._state !== PromiseStates.Pending) {
  10194. BABYLON.Tools.SetImmediate(function () {
  10195. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10196. var returnedValue = newPromise._resolve(_this._result);
  10197. if (returnedValue !== undefined && returnedValue !== null) {
  10198. if (returnedValue._state !== undefined) {
  10199. var returnedPromise = returnedValue;
  10200. newPromise._children.push(returnedPromise);
  10201. returnedPromise._parent = newPromise;
  10202. newPromise = returnedPromise;
  10203. }
  10204. else {
  10205. newPromise._result = returnedValue;
  10206. }
  10207. }
  10208. }
  10209. else {
  10210. newPromise._reject(_this._reason);
  10211. }
  10212. });
  10213. }
  10214. return newPromise;
  10215. };
  10216. InternalPromise.prototype._moveChildren = function (children) {
  10217. var _this = this;
  10218. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10219. this._children.forEach(function (child) {
  10220. child._parent = _this;
  10221. });
  10222. if (this._state === PromiseStates.Fulfilled) {
  10223. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10224. var child = _b[_i];
  10225. child._resolve(this._result);
  10226. }
  10227. }
  10228. else if (this._state === PromiseStates.Rejected) {
  10229. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10230. var child = _d[_c];
  10231. child._reject(this._reason);
  10232. }
  10233. }
  10234. var _a;
  10235. };
  10236. InternalPromise.prototype._resolve = function (value) {
  10237. try {
  10238. this._state = PromiseStates.Fulfilled;
  10239. var returnedValue = null;
  10240. if (this._onFulfilled) {
  10241. returnedValue = this._onFulfilled(value);
  10242. }
  10243. if (returnedValue !== undefined && returnedValue !== null) {
  10244. if (returnedValue._state !== undefined) {
  10245. // Transmit children
  10246. var returnedPromise = returnedValue;
  10247. returnedPromise._parent = this;
  10248. returnedPromise._moveChildren(this._children);
  10249. value = returnedPromise._result;
  10250. }
  10251. else {
  10252. value = returnedValue;
  10253. }
  10254. }
  10255. this._result = value;
  10256. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10257. var child = _a[_i];
  10258. child._resolve(value);
  10259. }
  10260. this._children.length = 0;
  10261. delete this._onFulfilled;
  10262. delete this._onRejected;
  10263. }
  10264. catch (e) {
  10265. this._reject(e, true);
  10266. }
  10267. };
  10268. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10269. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10270. this._state = PromiseStates.Rejected;
  10271. this._reason = reason;
  10272. if (this._onRejected && !onLocalThrow) {
  10273. try {
  10274. this._onRejected(reason);
  10275. this._rejectWasConsumed = true;
  10276. }
  10277. catch (e) {
  10278. reason = e;
  10279. }
  10280. }
  10281. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10282. var child = _a[_i];
  10283. if (this._rejectWasConsumed) {
  10284. child._resolve(null);
  10285. }
  10286. else {
  10287. child._reject(reason);
  10288. }
  10289. }
  10290. this._children.length = 0;
  10291. delete this._onFulfilled;
  10292. delete this._onRejected;
  10293. };
  10294. InternalPromise.resolve = function (value) {
  10295. var newPromise = new InternalPromise();
  10296. newPromise._resolve(value);
  10297. return newPromise;
  10298. };
  10299. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10300. promise.then(function (value) {
  10301. agregator.results[index] = value;
  10302. agregator.count++;
  10303. if (agregator.count === agregator.target) {
  10304. agregator.rootPromise._resolve(agregator.results);
  10305. }
  10306. return null;
  10307. }, function (reason) {
  10308. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10309. agregator.rootPromise._reject(reason);
  10310. }
  10311. });
  10312. };
  10313. InternalPromise.all = function (promises) {
  10314. var newPromise = new InternalPromise();
  10315. var agregator = new FulFillmentAgregator();
  10316. agregator.target = promises.length;
  10317. agregator.rootPromise = newPromise;
  10318. if (promises.length) {
  10319. for (var index = 0; index < promises.length; index++) {
  10320. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10321. }
  10322. }
  10323. else {
  10324. newPromise._resolve([]);
  10325. }
  10326. return newPromise;
  10327. };
  10328. InternalPromise.race = function (promises) {
  10329. var newPromise = new InternalPromise();
  10330. if (promises.length) {
  10331. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10332. var promise = promises_1[_i];
  10333. promise.then(function (value) {
  10334. if (newPromise) {
  10335. newPromise._resolve(value);
  10336. newPromise = null;
  10337. }
  10338. return null;
  10339. }, function (reason) {
  10340. if (newPromise) {
  10341. newPromise._reject(reason);
  10342. newPromise = null;
  10343. }
  10344. });
  10345. }
  10346. }
  10347. return newPromise;
  10348. };
  10349. return InternalPromise;
  10350. }());
  10351. /**
  10352. * Helper class that provides a small promise polyfill
  10353. */
  10354. var PromisePolyfill = /** @class */ (function () {
  10355. function PromisePolyfill() {
  10356. }
  10357. /**
  10358. * Static function used to check if the polyfill is required
  10359. * If this is the case then the function will inject the polyfill to window.Promise
  10360. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10361. */
  10362. PromisePolyfill.Apply = function (force) {
  10363. if (force === void 0) { force = false; }
  10364. if (force || typeof Promise === 'undefined') {
  10365. var root = window;
  10366. root.Promise = InternalPromise;
  10367. }
  10368. };
  10369. return PromisePolyfill;
  10370. }());
  10371. BABYLON.PromisePolyfill = PromisePolyfill;
  10372. })(BABYLON || (BABYLON = {}));
  10373. //# sourceMappingURL=babylon.promise.js.map
  10374. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10375. var BABYLON;
  10376. (function (BABYLON) {
  10377. /**
  10378. * Helper class to push actions to a pool of workers.
  10379. */
  10380. var WorkerPool = /** @class */ (function () {
  10381. /**
  10382. * Constructor
  10383. * @param workers Array of workers to use for actions
  10384. */
  10385. function WorkerPool(workers) {
  10386. this._pendingActions = new Array();
  10387. this._workerInfos = workers.map(function (worker) { return ({
  10388. worker: worker,
  10389. active: false
  10390. }); });
  10391. }
  10392. /**
  10393. * Terminates all workers and clears any pending actions.
  10394. */
  10395. WorkerPool.prototype.dispose = function () {
  10396. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10397. var workerInfo = _a[_i];
  10398. workerInfo.worker.terminate();
  10399. }
  10400. delete this._workerInfos;
  10401. delete this._pendingActions;
  10402. };
  10403. /**
  10404. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10405. * pended until a worker has completed its action.
  10406. * @param action The action to perform. Call onComplete when the action is complete.
  10407. */
  10408. WorkerPool.prototype.push = function (action) {
  10409. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10410. var workerInfo = _a[_i];
  10411. if (!workerInfo.active) {
  10412. this._execute(workerInfo, action);
  10413. return;
  10414. }
  10415. }
  10416. this._pendingActions.push(action);
  10417. };
  10418. WorkerPool.prototype._execute = function (workerInfo, action) {
  10419. var _this = this;
  10420. workerInfo.active = true;
  10421. action(workerInfo.worker, function () {
  10422. workerInfo.active = false;
  10423. var nextAction = _this._pendingActions.shift();
  10424. if (nextAction) {
  10425. _this._execute(workerInfo, nextAction);
  10426. }
  10427. });
  10428. };
  10429. return WorkerPool;
  10430. }());
  10431. BABYLON.WorkerPool = WorkerPool;
  10432. })(BABYLON || (BABYLON = {}));
  10433. //# sourceMappingURL=babylon.workerPool.js.map
  10434. var BABYLON;
  10435. (function (BABYLON) {
  10436. /**
  10437. * @hidden
  10438. **/
  10439. var _AlphaState = /** @class */ (function () {
  10440. /**
  10441. * Initializes the state.
  10442. */
  10443. function _AlphaState() {
  10444. this._isAlphaBlendDirty = false;
  10445. this._isBlendFunctionParametersDirty = false;
  10446. this._isBlendEquationParametersDirty = false;
  10447. this._isBlendConstantsDirty = false;
  10448. this._alphaBlend = false;
  10449. this._blendFunctionParameters = new Array(4);
  10450. this._blendEquationParameters = new Array(2);
  10451. this._blendConstants = new Array(4);
  10452. this.reset();
  10453. }
  10454. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10455. get: function () {
  10456. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10457. },
  10458. enumerable: true,
  10459. configurable: true
  10460. });
  10461. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10462. get: function () {
  10463. return this._alphaBlend;
  10464. },
  10465. set: function (value) {
  10466. if (this._alphaBlend === value) {
  10467. return;
  10468. }
  10469. this._alphaBlend = value;
  10470. this._isAlphaBlendDirty = true;
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10476. if (this._blendConstants[0] === r &&
  10477. this._blendConstants[1] === g &&
  10478. this._blendConstants[2] === b &&
  10479. this._blendConstants[3] === a) {
  10480. return;
  10481. }
  10482. this._blendConstants[0] = r;
  10483. this._blendConstants[1] = g;
  10484. this._blendConstants[2] = b;
  10485. this._blendConstants[3] = a;
  10486. this._isBlendConstantsDirty = true;
  10487. };
  10488. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10489. if (this._blendFunctionParameters[0] === value0 &&
  10490. this._blendFunctionParameters[1] === value1 &&
  10491. this._blendFunctionParameters[2] === value2 &&
  10492. this._blendFunctionParameters[3] === value3) {
  10493. return;
  10494. }
  10495. this._blendFunctionParameters[0] = value0;
  10496. this._blendFunctionParameters[1] = value1;
  10497. this._blendFunctionParameters[2] = value2;
  10498. this._blendFunctionParameters[3] = value3;
  10499. this._isBlendFunctionParametersDirty = true;
  10500. };
  10501. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10502. if (this._blendEquationParameters[0] === rgb &&
  10503. this._blendEquationParameters[1] === alpha) {
  10504. return;
  10505. }
  10506. this._blendEquationParameters[0] = rgb;
  10507. this._blendEquationParameters[1] = alpha;
  10508. this._isBlendEquationParametersDirty = true;
  10509. };
  10510. _AlphaState.prototype.reset = function () {
  10511. this._alphaBlend = false;
  10512. this._blendFunctionParameters[0] = null;
  10513. this._blendFunctionParameters[1] = null;
  10514. this._blendFunctionParameters[2] = null;
  10515. this._blendFunctionParameters[3] = null;
  10516. this._blendEquationParameters[0] = null;
  10517. this._blendEquationParameters[1] = null;
  10518. this._blendConstants[0] = null;
  10519. this._blendConstants[1] = null;
  10520. this._blendConstants[2] = null;
  10521. this._blendConstants[3] = null;
  10522. this._isAlphaBlendDirty = true;
  10523. this._isBlendFunctionParametersDirty = false;
  10524. this._isBlendEquationParametersDirty = false;
  10525. this._isBlendConstantsDirty = false;
  10526. };
  10527. _AlphaState.prototype.apply = function (gl) {
  10528. if (!this.isDirty) {
  10529. return;
  10530. }
  10531. // Alpha blend
  10532. if (this._isAlphaBlendDirty) {
  10533. if (this._alphaBlend) {
  10534. gl.enable(gl.BLEND);
  10535. }
  10536. else {
  10537. gl.disable(gl.BLEND);
  10538. }
  10539. this._isAlphaBlendDirty = false;
  10540. }
  10541. // Alpha function
  10542. if (this._isBlendFunctionParametersDirty) {
  10543. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10544. this._isBlendFunctionParametersDirty = false;
  10545. }
  10546. // Alpha equation
  10547. if (this._isBlendEquationParametersDirty) {
  10548. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10549. this._isBlendEquationParametersDirty = false;
  10550. }
  10551. // Constants
  10552. if (this._isBlendConstantsDirty) {
  10553. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10554. this._isBlendConstantsDirty = false;
  10555. }
  10556. };
  10557. return _AlphaState;
  10558. }());
  10559. BABYLON._AlphaState = _AlphaState;
  10560. })(BABYLON || (BABYLON = {}));
  10561. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10562. var BABYLON;
  10563. (function (BABYLON) {
  10564. /**
  10565. * @hidden
  10566. **/
  10567. var _DepthCullingState = /** @class */ (function () {
  10568. /**
  10569. * Initializes the state.
  10570. */
  10571. function _DepthCullingState() {
  10572. this._isDepthTestDirty = false;
  10573. this._isDepthMaskDirty = false;
  10574. this._isDepthFuncDirty = false;
  10575. this._isCullFaceDirty = false;
  10576. this._isCullDirty = false;
  10577. this._isZOffsetDirty = false;
  10578. this._isFrontFaceDirty = false;
  10579. this.reset();
  10580. }
  10581. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10582. get: function () {
  10583. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10589. get: function () {
  10590. return this._zOffset;
  10591. },
  10592. set: function (value) {
  10593. if (this._zOffset === value) {
  10594. return;
  10595. }
  10596. this._zOffset = value;
  10597. this._isZOffsetDirty = true;
  10598. },
  10599. enumerable: true,
  10600. configurable: true
  10601. });
  10602. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10603. get: function () {
  10604. return this._cullFace;
  10605. },
  10606. set: function (value) {
  10607. if (this._cullFace === value) {
  10608. return;
  10609. }
  10610. this._cullFace = value;
  10611. this._isCullFaceDirty = true;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10617. get: function () {
  10618. return this._cull;
  10619. },
  10620. set: function (value) {
  10621. if (this._cull === value) {
  10622. return;
  10623. }
  10624. this._cull = value;
  10625. this._isCullDirty = true;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10631. get: function () {
  10632. return this._depthFunc;
  10633. },
  10634. set: function (value) {
  10635. if (this._depthFunc === value) {
  10636. return;
  10637. }
  10638. this._depthFunc = value;
  10639. this._isDepthFuncDirty = true;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10645. get: function () {
  10646. return this._depthMask;
  10647. },
  10648. set: function (value) {
  10649. if (this._depthMask === value) {
  10650. return;
  10651. }
  10652. this._depthMask = value;
  10653. this._isDepthMaskDirty = true;
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10659. get: function () {
  10660. return this._depthTest;
  10661. },
  10662. set: function (value) {
  10663. if (this._depthTest === value) {
  10664. return;
  10665. }
  10666. this._depthTest = value;
  10667. this._isDepthTestDirty = true;
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10673. get: function () {
  10674. return this._frontFace;
  10675. },
  10676. set: function (value) {
  10677. if (this._frontFace === value) {
  10678. return;
  10679. }
  10680. this._frontFace = value;
  10681. this._isFrontFaceDirty = true;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. _DepthCullingState.prototype.reset = function () {
  10687. this._depthMask = true;
  10688. this._depthTest = true;
  10689. this._depthFunc = null;
  10690. this._cullFace = null;
  10691. this._cull = null;
  10692. this._zOffset = 0;
  10693. this._frontFace = null;
  10694. this._isDepthTestDirty = true;
  10695. this._isDepthMaskDirty = true;
  10696. this._isDepthFuncDirty = false;
  10697. this._isCullFaceDirty = false;
  10698. this._isCullDirty = false;
  10699. this._isZOffsetDirty = false;
  10700. this._isFrontFaceDirty = false;
  10701. };
  10702. _DepthCullingState.prototype.apply = function (gl) {
  10703. if (!this.isDirty) {
  10704. return;
  10705. }
  10706. // Cull
  10707. if (this._isCullDirty) {
  10708. if (this.cull) {
  10709. gl.enable(gl.CULL_FACE);
  10710. }
  10711. else {
  10712. gl.disable(gl.CULL_FACE);
  10713. }
  10714. this._isCullDirty = false;
  10715. }
  10716. // Cull face
  10717. if (this._isCullFaceDirty) {
  10718. gl.cullFace(this.cullFace);
  10719. this._isCullFaceDirty = false;
  10720. }
  10721. // Depth mask
  10722. if (this._isDepthMaskDirty) {
  10723. gl.depthMask(this.depthMask);
  10724. this._isDepthMaskDirty = false;
  10725. }
  10726. // Depth test
  10727. if (this._isDepthTestDirty) {
  10728. if (this.depthTest) {
  10729. gl.enable(gl.DEPTH_TEST);
  10730. }
  10731. else {
  10732. gl.disable(gl.DEPTH_TEST);
  10733. }
  10734. this._isDepthTestDirty = false;
  10735. }
  10736. // Depth func
  10737. if (this._isDepthFuncDirty) {
  10738. gl.depthFunc(this.depthFunc);
  10739. this._isDepthFuncDirty = false;
  10740. }
  10741. // zOffset
  10742. if (this._isZOffsetDirty) {
  10743. if (this.zOffset) {
  10744. gl.enable(gl.POLYGON_OFFSET_FILL);
  10745. gl.polygonOffset(this.zOffset, 0);
  10746. }
  10747. else {
  10748. gl.disable(gl.POLYGON_OFFSET_FILL);
  10749. }
  10750. this._isZOffsetDirty = false;
  10751. }
  10752. // Front face
  10753. if (this._isFrontFaceDirty) {
  10754. gl.frontFace(this.frontFace);
  10755. this._isFrontFaceDirty = false;
  10756. }
  10757. };
  10758. return _DepthCullingState;
  10759. }());
  10760. BABYLON._DepthCullingState = _DepthCullingState;
  10761. })(BABYLON || (BABYLON = {}));
  10762. //# sourceMappingURL=babylon.depthCullingState.js.map
  10763. var BABYLON;
  10764. (function (BABYLON) {
  10765. /**
  10766. * @hidden
  10767. **/
  10768. var _StencilState = /** @class */ (function () {
  10769. function _StencilState() {
  10770. this._isStencilTestDirty = false;
  10771. this._isStencilMaskDirty = false;
  10772. this._isStencilFuncDirty = false;
  10773. this._isStencilOpDirty = false;
  10774. this.reset();
  10775. }
  10776. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10777. get: function () {
  10778. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10784. get: function () {
  10785. return this._stencilFunc;
  10786. },
  10787. set: function (value) {
  10788. if (this._stencilFunc === value) {
  10789. return;
  10790. }
  10791. this._stencilFunc = value;
  10792. this._isStencilFuncDirty = true;
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10798. get: function () {
  10799. return this._stencilFuncRef;
  10800. },
  10801. set: function (value) {
  10802. if (this._stencilFuncRef === value) {
  10803. return;
  10804. }
  10805. this._stencilFuncRef = value;
  10806. this._isStencilFuncDirty = true;
  10807. },
  10808. enumerable: true,
  10809. configurable: true
  10810. });
  10811. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10812. get: function () {
  10813. return this._stencilFuncMask;
  10814. },
  10815. set: function (value) {
  10816. if (this._stencilFuncMask === value) {
  10817. return;
  10818. }
  10819. this._stencilFuncMask = value;
  10820. this._isStencilFuncDirty = true;
  10821. },
  10822. enumerable: true,
  10823. configurable: true
  10824. });
  10825. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10826. get: function () {
  10827. return this._stencilOpStencilFail;
  10828. },
  10829. set: function (value) {
  10830. if (this._stencilOpStencilFail === value) {
  10831. return;
  10832. }
  10833. this._stencilOpStencilFail = value;
  10834. this._isStencilOpDirty = true;
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10840. get: function () {
  10841. return this._stencilOpDepthFail;
  10842. },
  10843. set: function (value) {
  10844. if (this._stencilOpDepthFail === value) {
  10845. return;
  10846. }
  10847. this._stencilOpDepthFail = value;
  10848. this._isStencilOpDirty = true;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10854. get: function () {
  10855. return this._stencilOpStencilDepthPass;
  10856. },
  10857. set: function (value) {
  10858. if (this._stencilOpStencilDepthPass === value) {
  10859. return;
  10860. }
  10861. this._stencilOpStencilDepthPass = value;
  10862. this._isStencilOpDirty = true;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10868. get: function () {
  10869. return this._stencilMask;
  10870. },
  10871. set: function (value) {
  10872. if (this._stencilMask === value) {
  10873. return;
  10874. }
  10875. this._stencilMask = value;
  10876. this._isStencilMaskDirty = true;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10882. get: function () {
  10883. return this._stencilTest;
  10884. },
  10885. set: function (value) {
  10886. if (this._stencilTest === value) {
  10887. return;
  10888. }
  10889. this._stencilTest = value;
  10890. this._isStencilTestDirty = true;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. _StencilState.prototype.reset = function () {
  10896. this._stencilTest = false;
  10897. this._stencilMask = 0xFF;
  10898. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10899. this._stencilFuncRef = 1;
  10900. this._stencilFuncMask = 0xFF;
  10901. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10902. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10903. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10904. this._isStencilTestDirty = true;
  10905. this._isStencilMaskDirty = true;
  10906. this._isStencilFuncDirty = true;
  10907. this._isStencilOpDirty = true;
  10908. };
  10909. _StencilState.prototype.apply = function (gl) {
  10910. if (!this.isDirty) {
  10911. return;
  10912. }
  10913. // Stencil test
  10914. if (this._isStencilTestDirty) {
  10915. if (this.stencilTest) {
  10916. gl.enable(gl.STENCIL_TEST);
  10917. }
  10918. else {
  10919. gl.disable(gl.STENCIL_TEST);
  10920. }
  10921. this._isStencilTestDirty = false;
  10922. }
  10923. // Stencil mask
  10924. if (this._isStencilMaskDirty) {
  10925. gl.stencilMask(this.stencilMask);
  10926. this._isStencilMaskDirty = false;
  10927. }
  10928. // Stencil func
  10929. if (this._isStencilFuncDirty) {
  10930. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10931. this._isStencilFuncDirty = false;
  10932. }
  10933. // Stencil op
  10934. if (this._isStencilOpDirty) {
  10935. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10936. this._isStencilOpDirty = false;
  10937. }
  10938. };
  10939. return _StencilState;
  10940. }());
  10941. BABYLON._StencilState = _StencilState;
  10942. })(BABYLON || (BABYLON = {}));
  10943. //# sourceMappingURL=babylon.stencilState.js.map
  10944. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10945. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10946. s = arguments[i];
  10947. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10948. t[p] = s[p];
  10949. }
  10950. return t;
  10951. };
  10952. var BABYLON;
  10953. (function (BABYLON) {
  10954. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10955. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10956. };
  10957. var compileRawShader = function (gl, source, type) {
  10958. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10959. gl.shaderSource(shader, source);
  10960. gl.compileShader(shader);
  10961. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10962. var log = gl.getShaderInfoLog(shader);
  10963. if (log) {
  10964. throw new Error(log);
  10965. }
  10966. }
  10967. if (!shader) {
  10968. throw new Error("Something went wrong while compile the shader.");
  10969. }
  10970. return shader;
  10971. };
  10972. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10973. var magFilter = gl.NEAREST;
  10974. var minFilter = gl.NEAREST;
  10975. switch (samplingMode) {
  10976. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10977. magFilter = gl.LINEAR;
  10978. if (generateMipMaps) {
  10979. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10980. }
  10981. else {
  10982. minFilter = gl.LINEAR;
  10983. }
  10984. break;
  10985. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10986. magFilter = gl.LINEAR;
  10987. if (generateMipMaps) {
  10988. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10989. }
  10990. else {
  10991. minFilter = gl.LINEAR;
  10992. }
  10993. break;
  10994. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10995. magFilter = gl.NEAREST;
  10996. if (generateMipMaps) {
  10997. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10998. }
  10999. else {
  11000. minFilter = gl.NEAREST;
  11001. }
  11002. break;
  11003. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11004. magFilter = gl.NEAREST;
  11005. if (generateMipMaps) {
  11006. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11007. }
  11008. else {
  11009. minFilter = gl.NEAREST;
  11010. }
  11011. break;
  11012. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11013. magFilter = gl.NEAREST;
  11014. if (generateMipMaps) {
  11015. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11016. }
  11017. else {
  11018. minFilter = gl.LINEAR;
  11019. }
  11020. break;
  11021. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11022. magFilter = gl.NEAREST;
  11023. if (generateMipMaps) {
  11024. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11025. }
  11026. else {
  11027. minFilter = gl.LINEAR;
  11028. }
  11029. break;
  11030. case BABYLON.Texture.NEAREST_LINEAR:
  11031. magFilter = gl.NEAREST;
  11032. minFilter = gl.LINEAR;
  11033. break;
  11034. case BABYLON.Texture.NEAREST_NEAREST:
  11035. magFilter = gl.NEAREST;
  11036. minFilter = gl.NEAREST;
  11037. break;
  11038. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11039. magFilter = gl.LINEAR;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11042. }
  11043. else {
  11044. minFilter = gl.NEAREST;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11048. magFilter = gl.LINEAR;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.NEAREST;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.LINEAR_LINEAR:
  11057. magFilter = gl.LINEAR;
  11058. minFilter = gl.LINEAR;
  11059. break;
  11060. case BABYLON.Texture.LINEAR_NEAREST:
  11061. magFilter = gl.LINEAR;
  11062. minFilter = gl.NEAREST;
  11063. break;
  11064. }
  11065. return {
  11066. min: minFilter,
  11067. mag: magFilter
  11068. };
  11069. };
  11070. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11071. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11072. var img;
  11073. var onload = function () {
  11074. loadedImages[index] = img;
  11075. loadedImages._internalCount++;
  11076. if (scene) {
  11077. scene._removePendingData(img);
  11078. }
  11079. if (loadedImages._internalCount === 6) {
  11080. onfinish(loadedImages);
  11081. }
  11082. };
  11083. var onerror = function (message, exception) {
  11084. if (scene) {
  11085. scene._removePendingData(img);
  11086. }
  11087. if (onErrorCallBack) {
  11088. onErrorCallBack(message, exception);
  11089. }
  11090. };
  11091. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11092. if (scene) {
  11093. scene._addPendingData(img);
  11094. }
  11095. };
  11096. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11097. if (onError === void 0) { onError = null; }
  11098. var loadedImages = [];
  11099. loadedImages._internalCount = 0;
  11100. for (var index = 0; index < 6; index++) {
  11101. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11102. }
  11103. };
  11104. var BufferPointer = /** @class */ (function () {
  11105. function BufferPointer() {
  11106. }
  11107. return BufferPointer;
  11108. }());
  11109. /**
  11110. * Interface for attribute information associated with buffer instanciation
  11111. */
  11112. var InstancingAttributeInfo = /** @class */ (function () {
  11113. function InstancingAttributeInfo() {
  11114. }
  11115. return InstancingAttributeInfo;
  11116. }());
  11117. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11118. /**
  11119. * Define options used to create a render target texture
  11120. */
  11121. var RenderTargetCreationOptions = /** @class */ (function () {
  11122. function RenderTargetCreationOptions() {
  11123. }
  11124. return RenderTargetCreationOptions;
  11125. }());
  11126. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11127. /**
  11128. * Define options used to create a depth texture
  11129. */
  11130. var DepthTextureCreationOptions = /** @class */ (function () {
  11131. function DepthTextureCreationOptions() {
  11132. }
  11133. return DepthTextureCreationOptions;
  11134. }());
  11135. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11136. /**
  11137. * Class used to describe the capabilities of the engine relatively to the current browser
  11138. */
  11139. var EngineCapabilities = /** @class */ (function () {
  11140. function EngineCapabilities() {
  11141. }
  11142. return EngineCapabilities;
  11143. }());
  11144. BABYLON.EngineCapabilities = EngineCapabilities;
  11145. /**
  11146. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11147. */
  11148. var Engine = /** @class */ (function () {
  11149. /**
  11150. * Creates a new engine
  11151. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11152. * @param antialias defines enable antialiasing (default: false)
  11153. * @param options defines further options to be sent to the getContext() function
  11154. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11155. */
  11156. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11157. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11158. var _this = this;
  11159. // Public members
  11160. /**
  11161. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11162. */
  11163. this.forcePOTTextures = false;
  11164. /**
  11165. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11166. */
  11167. this.isFullscreen = false;
  11168. /**
  11169. * Gets a boolean indicating if the pointer is currently locked
  11170. */
  11171. this.isPointerLock = false;
  11172. /**
  11173. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11174. */
  11175. this.cullBackFaces = true;
  11176. /**
  11177. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11178. */
  11179. this.renderEvenInBackground = true;
  11180. /**
  11181. * Gets or sets a boolean indicating that cache can be kept between frames
  11182. */
  11183. this.preventCacheWipeBetweenFrames = false;
  11184. /**
  11185. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11186. **/
  11187. this.enableOfflineSupport = false;
  11188. /**
  11189. * 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)
  11190. **/
  11191. this.disableManifestCheck = false;
  11192. /**
  11193. * Gets the list of created scenes
  11194. */
  11195. this.scenes = new Array();
  11196. /**
  11197. * Gets the list of created postprocesses
  11198. */
  11199. this.postProcesses = new Array();
  11200. // Observables
  11201. /**
  11202. * Observable event triggered each time the rendering canvas is resized
  11203. */
  11204. this.onResizeObservable = new BABYLON.Observable();
  11205. /**
  11206. * Observable event triggered each time the canvas loses focus
  11207. */
  11208. this.onCanvasBlurObservable = new BABYLON.Observable();
  11209. /**
  11210. * Observable event triggered each time the canvas gains focus
  11211. */
  11212. this.onCanvasFocusObservable = new BABYLON.Observable();
  11213. /**
  11214. * Observable event triggered each time the canvas receives pointerout event
  11215. */
  11216. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11217. /**
  11218. * Observable event triggered before each texture is initialized
  11219. */
  11220. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11221. //WebVR
  11222. this._vrDisplay = undefined;
  11223. this._vrSupported = false;
  11224. this._vrExclusivePointerMode = false;
  11225. // Uniform buffers list
  11226. /**
  11227. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11228. */
  11229. this.disableUniformBuffers = false;
  11230. /** @hidden */
  11231. this._uniformBuffers = new Array();
  11232. // Observables
  11233. /**
  11234. * Observable raised when the engine begins a new frame
  11235. */
  11236. this.onBeginFrameObservable = new BABYLON.Observable();
  11237. /**
  11238. * Observable raised when the engine ends the current frame
  11239. */
  11240. this.onEndFrameObservable = new BABYLON.Observable();
  11241. /**
  11242. * Observable raised when the engine is about to compile a shader
  11243. */
  11244. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11245. /**
  11246. * Observable raised when the engine has jsut compiled a shader
  11247. */
  11248. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11249. this._windowIsBackground = false;
  11250. this._webGLVersion = 1.0;
  11251. /** @hidden */
  11252. this._badOS = false;
  11253. /** @hidden */
  11254. this._badDesktopOS = false;
  11255. /**
  11256. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11257. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11258. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11259. */
  11260. this.disableTextureBindingOptimization = false;
  11261. /**
  11262. * Observable signaled when VR display mode changes
  11263. */
  11264. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11265. /**
  11266. * Observable signaled when VR request present is complete
  11267. */
  11268. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11269. /**
  11270. * Observable signaled when VR request present starts
  11271. */
  11272. this.onVRRequestPresentStart = new BABYLON.Observable();
  11273. this._colorWrite = true;
  11274. /** @hidden */
  11275. this._drawCalls = new BABYLON.PerfCounter();
  11276. /** @hidden */
  11277. this._textureCollisions = new BABYLON.PerfCounter();
  11278. this._renderingQueueLaunched = false;
  11279. this._activeRenderLoops = new Array();
  11280. // Deterministic lockstepMaxSteps
  11281. this._deterministicLockstep = false;
  11282. this._lockstepMaxSteps = 4;
  11283. // Lost context
  11284. /**
  11285. * Observable signaled when a context lost event is raised
  11286. */
  11287. this.onContextLostObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable signaled when a context restored event is raised
  11290. */
  11291. this.onContextRestoredObservable = new BABYLON.Observable();
  11292. this._contextWasLost = false;
  11293. this._doNotHandleContextLost = false;
  11294. // FPS
  11295. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11296. this._fps = 60;
  11297. this._deltaTime = 0;
  11298. /**
  11299. * Turn this value on if you want to pause FPS computation when in background
  11300. */
  11301. this.disablePerformanceMonitorInBackground = false;
  11302. // States
  11303. /** @hidden */
  11304. this._depthCullingState = new BABYLON._DepthCullingState();
  11305. /** @hidden */
  11306. this._stencilState = new BABYLON._StencilState();
  11307. /** @hidden */
  11308. this._alphaState = new BABYLON._AlphaState();
  11309. /** @hidden */
  11310. this._alphaMode = Engine.ALPHA_DISABLE;
  11311. // Cache
  11312. this._internalTexturesCache = new Array();
  11313. /** @hidden */
  11314. this._activeChannel = 0;
  11315. this._currentTextureChannel = -1;
  11316. /** @hidden */
  11317. this._boundTexturesCache = {};
  11318. this._compiledEffects = {};
  11319. this._vertexAttribArraysEnabled = [];
  11320. this._uintIndicesCurrentlySet = false;
  11321. this._currentBoundBuffer = new Array();
  11322. this._currentBufferPointers = new Array();
  11323. this._currentInstanceLocations = new Array();
  11324. this._currentInstanceBuffers = new Array();
  11325. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11326. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11327. this._vaoRecordInProgress = false;
  11328. this._mustWipeVertexAttributes = false;
  11329. this._nextFreeTextureSlots = new Array();
  11330. this._maxSimultaneousTextures = 0;
  11331. this._activeRequests = new Array();
  11332. // Hardware supported Compressed Textures
  11333. this._texturesSupported = new Array();
  11334. this._onVRFullScreenTriggered = function () {
  11335. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11336. //get the old size before we change
  11337. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11338. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11339. //get the width and height, change the render size
  11340. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11341. _this.setHardwareScalingLevel(1);
  11342. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11343. }
  11344. else {
  11345. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11346. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11347. }
  11348. };
  11349. this._boundUniforms = {};
  11350. // Register promises
  11351. BABYLON.PromisePolyfill.Apply();
  11352. var canvas = null;
  11353. Engine.Instances.push(this);
  11354. if (!canvasOrContext) {
  11355. return;
  11356. }
  11357. options = options || {};
  11358. if (canvasOrContext.getContext) {
  11359. canvas = canvasOrContext;
  11360. this._renderingCanvas = canvas;
  11361. if (antialias != null) {
  11362. options.antialias = antialias;
  11363. }
  11364. if (options.deterministicLockstep === undefined) {
  11365. options.deterministicLockstep = false;
  11366. }
  11367. if (options.lockstepMaxSteps === undefined) {
  11368. options.lockstepMaxSteps = 4;
  11369. }
  11370. if (options.preserveDrawingBuffer === undefined) {
  11371. options.preserveDrawingBuffer = false;
  11372. }
  11373. if (options.audioEngine === undefined) {
  11374. options.audioEngine = true;
  11375. }
  11376. if (options.stencil === undefined) {
  11377. options.stencil = true;
  11378. }
  11379. this._deterministicLockstep = options.deterministicLockstep;
  11380. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11381. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11382. // Exceptions
  11383. if (navigator && navigator.userAgent) {
  11384. var ua = navigator.userAgent;
  11385. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11386. var exception = _a[_i];
  11387. var key = exception.key;
  11388. var targets = exception.targets;
  11389. if (ua.indexOf(key) > -1) {
  11390. if (exception.capture && exception.captureConstraint) {
  11391. var capture = exception.capture;
  11392. var constraint = exception.captureConstraint;
  11393. var regex = new RegExp(capture);
  11394. var matches = regex.exec(ua);
  11395. if (matches && matches.length > 0) {
  11396. var capturedValue = parseInt(matches[matches.length - 1]);
  11397. if (capturedValue >= constraint) {
  11398. continue;
  11399. }
  11400. }
  11401. }
  11402. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11403. var target = targets_1[_b];
  11404. switch (target) {
  11405. case "uniformBuffer":
  11406. this.disableUniformBuffers = true;
  11407. break;
  11408. case "textureBindingOptimization":
  11409. this.disableTextureBindingOptimization = true;
  11410. break;
  11411. }
  11412. }
  11413. }
  11414. }
  11415. }
  11416. // GL
  11417. if (!options.disableWebGL2Support) {
  11418. try {
  11419. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11420. if (this._gl) {
  11421. this._webGLVersion = 2.0;
  11422. }
  11423. }
  11424. catch (e) {
  11425. // Do nothing
  11426. }
  11427. }
  11428. if (!this._gl) {
  11429. if (!canvas) {
  11430. throw new Error("The provided canvas is null or undefined.");
  11431. }
  11432. try {
  11433. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11434. }
  11435. catch (e) {
  11436. throw new Error("WebGL not supported");
  11437. }
  11438. }
  11439. if (!this._gl) {
  11440. throw new Error("WebGL not supported");
  11441. }
  11442. this._onCanvasFocus = function () {
  11443. _this.onCanvasFocusObservable.notifyObservers(_this);
  11444. };
  11445. this._onCanvasBlur = function () {
  11446. _this.onCanvasBlurObservable.notifyObservers(_this);
  11447. };
  11448. canvas.addEventListener("focus", this._onCanvasFocus);
  11449. canvas.addEventListener("blur", this._onCanvasBlur);
  11450. this._onBlur = function () {
  11451. if (_this.disablePerformanceMonitorInBackground) {
  11452. _this._performanceMonitor.disable();
  11453. }
  11454. _this._windowIsBackground = true;
  11455. };
  11456. this._onFocus = function () {
  11457. if (_this.disablePerformanceMonitorInBackground) {
  11458. _this._performanceMonitor.enable();
  11459. }
  11460. _this._windowIsBackground = false;
  11461. };
  11462. this._onCanvasPointerOut = function (ev) {
  11463. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11464. };
  11465. window.addEventListener("blur", this._onBlur);
  11466. window.addEventListener("focus", this._onFocus);
  11467. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11468. // Context lost
  11469. if (!this._doNotHandleContextLost) {
  11470. this._onContextLost = function (evt) {
  11471. evt.preventDefault();
  11472. _this._contextWasLost = true;
  11473. BABYLON.Tools.Warn("WebGL context lost.");
  11474. _this.onContextLostObservable.notifyObservers(_this);
  11475. };
  11476. this._onContextRestored = function (evt) {
  11477. // Adding a timeout to avoid race condition at browser level
  11478. setTimeout(function () {
  11479. // Rebuild gl context
  11480. _this._initGLContext();
  11481. // Rebuild effects
  11482. _this._rebuildEffects();
  11483. // Rebuild textures
  11484. _this._rebuildInternalTextures();
  11485. // Rebuild buffers
  11486. _this._rebuildBuffers();
  11487. // Cache
  11488. _this.wipeCaches(true);
  11489. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11490. _this.onContextRestoredObservable.notifyObservers(_this);
  11491. _this._contextWasLost = false;
  11492. }, 0);
  11493. };
  11494. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11495. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11496. }
  11497. }
  11498. else {
  11499. this._gl = canvasOrContext;
  11500. this._renderingCanvas = this._gl.canvas;
  11501. if (this._gl.renderbufferStorageMultisample) {
  11502. this._webGLVersion = 2.0;
  11503. }
  11504. options.stencil = this._gl.getContextAttributes().stencil;
  11505. }
  11506. // Viewport
  11507. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11508. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11509. this.resize();
  11510. this._isStencilEnable = options.stencil ? true : false;
  11511. this._initGLContext();
  11512. if (canvas) {
  11513. // Fullscreen
  11514. this._onFullscreenChange = function () {
  11515. if (document.fullscreen !== undefined) {
  11516. _this.isFullscreen = document.fullscreen;
  11517. }
  11518. else if (document.mozFullScreen !== undefined) {
  11519. _this.isFullscreen = document.mozFullScreen;
  11520. }
  11521. else if (document.webkitIsFullScreen !== undefined) {
  11522. _this.isFullscreen = document.webkitIsFullScreen;
  11523. }
  11524. else if (document.msIsFullScreen !== undefined) {
  11525. _this.isFullscreen = document.msIsFullScreen;
  11526. }
  11527. // Pointer lock
  11528. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11529. canvas.requestPointerLock = canvas.requestPointerLock ||
  11530. canvas.msRequestPointerLock ||
  11531. canvas.mozRequestPointerLock ||
  11532. canvas.webkitRequestPointerLock;
  11533. if (canvas.requestPointerLock) {
  11534. canvas.requestPointerLock();
  11535. }
  11536. }
  11537. };
  11538. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11539. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11540. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11541. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11542. // Pointer lock
  11543. this._onPointerLockChange = function () {
  11544. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11545. document.webkitPointerLockElement === canvas ||
  11546. document.msPointerLockElement === canvas ||
  11547. document.pointerLockElement === canvas);
  11548. };
  11549. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11550. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11551. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11552. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11553. this._onVRDisplayPointerRestricted = function () {
  11554. if (canvas) {
  11555. canvas.requestPointerLock();
  11556. }
  11557. };
  11558. this._onVRDisplayPointerUnrestricted = function () {
  11559. document.exitPointerLock();
  11560. };
  11561. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11562. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11563. }
  11564. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11565. Engine.audioEngine = new BABYLON.AudioEngine();
  11566. }
  11567. // Prepare buffer pointers
  11568. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11569. this._currentBufferPointers[i] = new BufferPointer();
  11570. }
  11571. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11572. // Load WebVR Devices
  11573. if (options.autoEnableWebVR) {
  11574. this.initWebVR();
  11575. }
  11576. // Detect if we are running on a faulty buggy OS.
  11577. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11578. // Detect if we are running on a faulty buggy desktop OS.
  11579. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11580. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11581. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11582. }
  11583. Object.defineProperty(Engine, "LastCreatedEngine", {
  11584. /**
  11585. * Gets the latest created engine
  11586. */
  11587. get: function () {
  11588. if (Engine.Instances.length === 0) {
  11589. return null;
  11590. }
  11591. return Engine.Instances[Engine.Instances.length - 1];
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine, "LastCreatedScene", {
  11597. /**
  11598. * Gets the latest created scene
  11599. */
  11600. get: function () {
  11601. var lastCreatedEngine = Engine.LastCreatedEngine;
  11602. if (!lastCreatedEngine) {
  11603. return null;
  11604. }
  11605. if (lastCreatedEngine.scenes.length === 0) {
  11606. return null;
  11607. }
  11608. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11609. },
  11610. enumerable: true,
  11611. configurable: true
  11612. });
  11613. /**
  11614. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11615. * @param flag defines which part of the materials must be marked as dirty
  11616. * @param predicate defines a predicate used to filter which materials should be affected
  11617. */
  11618. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11619. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11620. var engine = Engine.Instances[engineIndex];
  11621. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11622. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11623. }
  11624. }
  11625. };
  11626. Object.defineProperty(Engine, "NEVER", {
  11627. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11628. get: function () {
  11629. return Engine._NEVER;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "ALWAYS", {
  11635. /** 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 */
  11636. get: function () {
  11637. return Engine._ALWAYS;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "LESS", {
  11643. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11644. get: function () {
  11645. return Engine._LESS;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "EQUAL", {
  11651. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11652. get: function () {
  11653. return Engine._EQUAL;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "LEQUAL", {
  11659. /** 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 */
  11660. get: function () {
  11661. return Engine._LEQUAL;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "GREATER", {
  11667. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11668. get: function () {
  11669. return Engine._GREATER;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Engine, "GEQUAL", {
  11675. /** 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 */
  11676. get: function () {
  11677. return Engine._GEQUAL;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(Engine, "NOTEQUAL", {
  11683. /** 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 */
  11684. get: function () {
  11685. return Engine._NOTEQUAL;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "KEEP", {
  11691. /** Passed to stencilOperation to specify that stencil value must be kept */
  11692. get: function () {
  11693. return Engine._KEEP;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "REPLACE", {
  11699. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11700. get: function () {
  11701. return Engine._REPLACE;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "INCR", {
  11707. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11708. get: function () {
  11709. return Engine._INCR;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "DECR", {
  11715. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11716. get: function () {
  11717. return Engine._DECR;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "INVERT", {
  11723. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11724. get: function () {
  11725. return Engine._INVERT;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "INCR_WRAP", {
  11731. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11732. get: function () {
  11733. return Engine._INCR_WRAP;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "DECR_WRAP", {
  11739. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11740. get: function () {
  11741. return Engine._DECR_WRAP;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11747. // Alpha
  11748. /** Defines that alpha blending is disabled */
  11749. get: function () {
  11750. return Engine._ALPHA_DISABLE;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11756. /** Defines that alpha blending to SRC + DEST */
  11757. get: function () {
  11758. return Engine._ALPHA_ONEONE;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "ALPHA_ADD", {
  11764. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11765. get: function () {
  11766. return Engine._ALPHA_ADD;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11772. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11773. get: function () {
  11774. return Engine._ALPHA_COMBINE;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11780. /** Defines that alpha blending to DEST - SRC * DEST */
  11781. get: function () {
  11782. return Engine._ALPHA_SUBTRACT;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11788. /** Defines that alpha blending to SRC * DEST */
  11789. get: function () {
  11790. return Engine._ALPHA_MULTIPLY;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11796. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11797. get: function () {
  11798. return Engine._ALPHA_MAXIMIZED;
  11799. },
  11800. enumerable: true,
  11801. configurable: true
  11802. });
  11803. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11804. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11805. get: function () {
  11806. return Engine._ALPHA_PREMULTIPLIED;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11812. /**
  11813. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11814. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11815. */
  11816. get: function () {
  11817. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11818. },
  11819. enumerable: true,
  11820. configurable: true
  11821. });
  11822. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11823. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11824. get: function () {
  11825. return Engine._ALPHA_INTERPOLATE;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11831. /**
  11832. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11833. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11834. */
  11835. get: function () {
  11836. return Engine._ALPHA_SCREENMODE;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11842. // Delays
  11843. /** Defines that the ressource is not delayed*/
  11844. get: function () {
  11845. return Engine._DELAYLOADSTATE_NONE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11851. /** Defines that the ressource was successfully delay loaded */
  11852. get: function () {
  11853. return Engine._DELAYLOADSTATE_LOADED;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11859. /** Defines that the ressource is currently delay loading */
  11860. get: function () {
  11861. return Engine._DELAYLOADSTATE_LOADING;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11867. /** Defines that the ressource is delayed and has not started loading */
  11868. get: function () {
  11869. return Engine._DELAYLOADSTATE_NOTLOADED;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11875. /** ALPHA */
  11876. get: function () {
  11877. return Engine._TEXTUREFORMAT_ALPHA;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11883. /** LUMINANCE */
  11884. get: function () {
  11885. return Engine._TEXTUREFORMAT_LUMINANCE;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11891. /**
  11892. * R32F
  11893. */
  11894. get: function () {
  11895. return Engine._TEXTUREFORMAT_R32F;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11901. /**
  11902. * RG32F
  11903. */
  11904. get: function () {
  11905. return Engine._TEXTUREFORMAT_RG32F;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11911. /**
  11912. * RGB32F
  11913. */
  11914. get: function () {
  11915. return Engine._TEXTUREFORMAT_RGB32F;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11921. /**
  11922. * RGBA32F
  11923. */
  11924. get: function () {
  11925. return Engine._TEXTUREFORMAT_RGBA32F;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11931. /** LUMINANCE_ALPHA */
  11932. get: function () {
  11933. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11939. /** RGB */
  11940. get: function () {
  11941. return Engine._TEXTUREFORMAT_RGB;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11947. /** RGBA */
  11948. get: function () {
  11949. return Engine._TEXTUREFORMAT_RGBA;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11955. /** UNSIGNED_INT */
  11956. get: function () {
  11957. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11963. /** FLOAT */
  11964. get: function () {
  11965. return Engine._TEXTURETYPE_FLOAT;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11971. /** HALF_FLOAT */
  11972. get: function () {
  11973. return Engine._TEXTURETYPE_HALF_FLOAT;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11979. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11980. get: function () {
  11981. return Engine._SCALEMODE_FLOOR;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11987. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11988. get: function () {
  11989. return Engine._SCALEMODE_NEAREST;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11995. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11996. get: function () {
  11997. return Engine._SCALEMODE_CEILING;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine, "Version", {
  12003. /**
  12004. * Returns the current version of the framework
  12005. */
  12006. get: function () {
  12007. return "3.3.0-alpha.0";
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12013. /**
  12014. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12015. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12016. */
  12017. get: function () {
  12018. return this._vrExclusivePointerMode;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12024. /**
  12025. * Gets a boolean indicating that the engine supports uniform buffers
  12026. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12027. */
  12028. get: function () {
  12029. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12035. /**
  12036. * Gets a boolean indicating that only power of 2 textures are supported
  12037. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12038. */
  12039. get: function () {
  12040. return this._webGLVersion < 2 || this.forcePOTTextures;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12046. /**
  12047. * Gets the performance monitor attached to this engine
  12048. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12049. */
  12050. get: function () {
  12051. return this._performanceMonitor;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12057. /**
  12058. * Gets the list of texture formats supported
  12059. */
  12060. get: function () {
  12061. return this._texturesSupported;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12067. /**
  12068. * Gets the list of texture formats in use
  12069. */
  12070. get: function () {
  12071. return this._textureFormatInUse;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Engine.prototype, "currentViewport", {
  12077. /**
  12078. * Gets the current viewport
  12079. */
  12080. get: function () {
  12081. return this._cachedViewport;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12087. /**
  12088. * Gets the default empty texture
  12089. */
  12090. get: function () {
  12091. if (!this._emptyTexture) {
  12092. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12093. }
  12094. return this._emptyTexture;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12100. /**
  12101. * Gets the default empty 3D texture
  12102. */
  12103. get: function () {
  12104. if (!this._emptyTexture3D) {
  12105. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12106. }
  12107. return this._emptyTexture3D;
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12113. /**
  12114. * Gets the default empty cube texture
  12115. */
  12116. get: function () {
  12117. if (!this._emptyCubeTexture) {
  12118. var faceData = new Uint8Array(4);
  12119. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12120. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12121. }
  12122. return this._emptyCubeTexture;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Engine.prototype._rebuildInternalTextures = function () {
  12128. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12129. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12130. var internalTexture = currentState_1[_i];
  12131. internalTexture._rebuild();
  12132. }
  12133. };
  12134. Engine.prototype._rebuildEffects = function () {
  12135. for (var key in this._compiledEffects) {
  12136. var effect = this._compiledEffects[key];
  12137. effect._prepareEffect();
  12138. }
  12139. BABYLON.Effect.ResetCache();
  12140. };
  12141. Engine.prototype._rebuildBuffers = function () {
  12142. // Index / Vertex
  12143. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12144. var scene = _a[_i];
  12145. scene.resetCachedMaterial();
  12146. scene._rebuildGeometries();
  12147. scene._rebuildTextures();
  12148. }
  12149. // Uniforms
  12150. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12151. var uniformBuffer = _c[_b];
  12152. uniformBuffer._rebuild();
  12153. }
  12154. };
  12155. Engine.prototype._initGLContext = function () {
  12156. // Caps
  12157. this._caps = new EngineCapabilities();
  12158. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12159. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12160. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12161. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12162. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12163. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12164. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12165. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12166. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12167. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12168. // Infos
  12169. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12170. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12171. if (rendererInfo != null) {
  12172. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12173. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12174. }
  12175. if (!this._glVendor) {
  12176. this._glVendor = "Unknown vendor";
  12177. }
  12178. if (!this._glRenderer) {
  12179. this._glRenderer = "Unknown renderer";
  12180. }
  12181. // Constants
  12182. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12183. if (this._gl.RGBA16F !== 0x881A) {
  12184. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12185. }
  12186. if (this._gl.RGBA32F !== 0x8814) {
  12187. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12188. }
  12189. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12190. this._gl.DEPTH24_STENCIL8 = 35056;
  12191. }
  12192. // Extensions
  12193. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12194. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12195. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12196. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12197. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12198. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12199. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12200. 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');
  12201. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12202. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12203. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12204. this._caps.highPrecisionShaderSupported = true;
  12205. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12206. if (this._caps.timerQuery) {
  12207. if (this._webGLVersion === 1) {
  12208. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12209. }
  12210. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12211. }
  12212. // Checks if some of the format renders first to allow the use of webgl inspector.
  12213. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12214. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12215. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12216. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12217. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12218. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12219. if (this._webGLVersion > 1) {
  12220. this._gl.HALF_FLOAT_OES = 0x140B;
  12221. }
  12222. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12223. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12224. // Draw buffers
  12225. if (this._webGLVersion > 1) {
  12226. this._caps.drawBuffersExtension = true;
  12227. }
  12228. else {
  12229. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12230. if (drawBuffersExtension !== null) {
  12231. this._caps.drawBuffersExtension = true;
  12232. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12233. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12234. for (var i = 0; i < 16; i++) {
  12235. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12236. }
  12237. }
  12238. else {
  12239. this._caps.drawBuffersExtension = false;
  12240. }
  12241. }
  12242. // Depth Texture
  12243. if (this._webGLVersion > 1) {
  12244. this._caps.depthTextureExtension = true;
  12245. }
  12246. else {
  12247. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12248. if (depthTextureExtension != null) {
  12249. this._caps.depthTextureExtension = true;
  12250. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12251. }
  12252. }
  12253. // Vertex array object
  12254. if (this._webGLVersion > 1) {
  12255. this._caps.vertexArrayObject = true;
  12256. }
  12257. else {
  12258. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12259. if (vertexArrayObjectExtension != null) {
  12260. this._caps.vertexArrayObject = true;
  12261. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12262. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12263. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12264. }
  12265. else {
  12266. this._caps.vertexArrayObject = false;
  12267. }
  12268. }
  12269. // Instances count
  12270. if (this._webGLVersion > 1) {
  12271. this._caps.instancedArrays = true;
  12272. }
  12273. else {
  12274. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12275. if (instanceExtension != null) {
  12276. this._caps.instancedArrays = true;
  12277. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12278. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12279. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12280. }
  12281. else {
  12282. this._caps.instancedArrays = false;
  12283. }
  12284. }
  12285. // Intelligently add supported compressed formats in order to check for.
  12286. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12287. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12288. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12289. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12290. if (this._caps.astc)
  12291. this.texturesSupported.push('-astc.ktx');
  12292. if (this._caps.s3tc)
  12293. this.texturesSupported.push('-dxt.ktx');
  12294. if (this._caps.pvrtc)
  12295. this.texturesSupported.push('-pvrtc.ktx');
  12296. if (this._caps.etc2)
  12297. this.texturesSupported.push('-etc2.ktx');
  12298. if (this._caps.etc1)
  12299. this.texturesSupported.push('-etc1.ktx');
  12300. if (this._gl.getShaderPrecisionFormat) {
  12301. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12302. if (highp) {
  12303. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12304. }
  12305. }
  12306. // Depth buffer
  12307. this.setDepthBuffer(true);
  12308. this.setDepthFunctionToLessOrEqual();
  12309. this.setDepthWrite(true);
  12310. // Texture maps
  12311. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12312. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12313. this._nextFreeTextureSlots.push(slot);
  12314. }
  12315. };
  12316. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12317. /**
  12318. * Gets version of the current webGL context
  12319. */
  12320. get: function () {
  12321. return this._webGLVersion;
  12322. },
  12323. enumerable: true,
  12324. configurable: true
  12325. });
  12326. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12327. /**
  12328. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12329. */
  12330. get: function () {
  12331. return this._isStencilEnable;
  12332. },
  12333. enumerable: true,
  12334. configurable: true
  12335. });
  12336. Engine.prototype._prepareWorkingCanvas = function () {
  12337. if (this._workingCanvas) {
  12338. return;
  12339. }
  12340. this._workingCanvas = document.createElement("canvas");
  12341. var context = this._workingCanvas.getContext("2d");
  12342. if (context) {
  12343. this._workingContext = context;
  12344. }
  12345. };
  12346. /**
  12347. * Reset the texture cache to empty state
  12348. */
  12349. Engine.prototype.resetTextureCache = function () {
  12350. for (var key in this._boundTexturesCache) {
  12351. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12352. continue;
  12353. }
  12354. var boundTexture = this._boundTexturesCache[key];
  12355. if (boundTexture) {
  12356. this._removeDesignatedSlot(boundTexture);
  12357. }
  12358. this._boundTexturesCache[key] = null;
  12359. }
  12360. if (!this.disableTextureBindingOptimization) {
  12361. this._nextFreeTextureSlots = [];
  12362. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12363. this._nextFreeTextureSlots.push(slot);
  12364. }
  12365. }
  12366. this._currentTextureChannel = -1;
  12367. };
  12368. /**
  12369. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12370. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12371. * @returns true if engine is in deterministic lock step mode
  12372. */
  12373. Engine.prototype.isDeterministicLockStep = function () {
  12374. return this._deterministicLockstep;
  12375. };
  12376. /**
  12377. * Gets the max steps when engine is running in deterministic lock step
  12378. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12379. * @returns the max steps
  12380. */
  12381. Engine.prototype.getLockstepMaxSteps = function () {
  12382. return this._lockstepMaxSteps;
  12383. };
  12384. /**
  12385. * Gets an object containing information about the current webGL context
  12386. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12387. */
  12388. Engine.prototype.getGlInfo = function () {
  12389. return {
  12390. vendor: this._glVendor,
  12391. renderer: this._glRenderer,
  12392. version: this._glVersion
  12393. };
  12394. };
  12395. /**
  12396. * Gets current aspect ratio
  12397. * @param camera defines the camera to use to get the aspect ratio
  12398. * @param useScreen defines if screen size must be used (or the current render target if any)
  12399. * @returns a number defining the aspect ratio
  12400. */
  12401. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12402. if (useScreen === void 0) { useScreen = false; }
  12403. var viewport = camera.viewport;
  12404. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12405. };
  12406. /**
  12407. * Gets the current render width
  12408. * @param useScreen defines if screen size must be used (or the current render target if any)
  12409. * @returns a number defining the current render width
  12410. */
  12411. Engine.prototype.getRenderWidth = function (useScreen) {
  12412. if (useScreen === void 0) { useScreen = false; }
  12413. if (!useScreen && this._currentRenderTarget) {
  12414. return this._currentRenderTarget.width;
  12415. }
  12416. return this._gl.drawingBufferWidth;
  12417. };
  12418. /**
  12419. * Gets the current render height
  12420. * @param useScreen defines if screen size must be used (or the current render target if any)
  12421. * @returns a number defining the current render height
  12422. */
  12423. Engine.prototype.getRenderHeight = function (useScreen) {
  12424. if (useScreen === void 0) { useScreen = false; }
  12425. if (!useScreen && this._currentRenderTarget) {
  12426. return this._currentRenderTarget.height;
  12427. }
  12428. return this._gl.drawingBufferHeight;
  12429. };
  12430. /**
  12431. * Gets the HTML canvas attached with the current webGL context
  12432. * @returns a HTML canvas
  12433. */
  12434. Engine.prototype.getRenderingCanvas = function () {
  12435. return this._renderingCanvas;
  12436. };
  12437. /**
  12438. * Gets the client rect of the HTML canvas attached with the current webGL context
  12439. * @returns a client rectanglee
  12440. */
  12441. Engine.prototype.getRenderingCanvasClientRect = function () {
  12442. if (!this._renderingCanvas) {
  12443. return null;
  12444. }
  12445. return this._renderingCanvas.getBoundingClientRect();
  12446. };
  12447. /**
  12448. * Defines the hardware scaling level.
  12449. * By default the hardware scaling level is computed from the window device ratio.
  12450. * 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.
  12451. * @param level defines the level to use
  12452. */
  12453. Engine.prototype.setHardwareScalingLevel = function (level) {
  12454. this._hardwareScalingLevel = level;
  12455. this.resize();
  12456. };
  12457. /**
  12458. * Gets the current hardware scaling level.
  12459. * By default the hardware scaling level is computed from the window device ratio.
  12460. * 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.
  12461. * @returns a number indicating the current hardware scaling level
  12462. */
  12463. Engine.prototype.getHardwareScalingLevel = function () {
  12464. return this._hardwareScalingLevel;
  12465. };
  12466. /**
  12467. * Gets the list of loaded textures
  12468. * @returns an array containing all loaded textures
  12469. */
  12470. Engine.prototype.getLoadedTexturesCache = function () {
  12471. return this._internalTexturesCache;
  12472. };
  12473. /**
  12474. * Gets the object containing all engine capabilities
  12475. * @returns the EngineCapabilities object
  12476. */
  12477. Engine.prototype.getCaps = function () {
  12478. return this._caps;
  12479. };
  12480. Object.defineProperty(Engine.prototype, "drawCalls", {
  12481. /** @hidden */
  12482. get: function () {
  12483. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12484. return 0;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12490. /** @hidden */
  12491. get: function () {
  12492. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12493. return null;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. /**
  12499. * Gets the current depth function
  12500. * @returns a number defining the depth function
  12501. */
  12502. Engine.prototype.getDepthFunction = function () {
  12503. return this._depthCullingState.depthFunc;
  12504. };
  12505. /**
  12506. * Sets the current depth function
  12507. * @param depthFunc defines the function to use
  12508. */
  12509. Engine.prototype.setDepthFunction = function (depthFunc) {
  12510. this._depthCullingState.depthFunc = depthFunc;
  12511. };
  12512. /**
  12513. * Sets the current depth function to GREATER
  12514. */
  12515. Engine.prototype.setDepthFunctionToGreater = function () {
  12516. this._depthCullingState.depthFunc = this._gl.GREATER;
  12517. };
  12518. /**
  12519. * Sets the current depth function to GEQUAL
  12520. */
  12521. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12522. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12523. };
  12524. /**
  12525. * Sets the current depth function to LESS
  12526. */
  12527. Engine.prototype.setDepthFunctionToLess = function () {
  12528. this._depthCullingState.depthFunc = this._gl.LESS;
  12529. };
  12530. /**
  12531. * Sets the current depth function to LEQUAL
  12532. */
  12533. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12534. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12535. };
  12536. /**
  12537. * Gets a boolean indicating if stencil buffer is enabled
  12538. * @returns the current stencil buffer state
  12539. */
  12540. Engine.prototype.getStencilBuffer = function () {
  12541. return this._stencilState.stencilTest;
  12542. };
  12543. /**
  12544. * Enable or disable the stencil buffer
  12545. * @param enable defines if the stencil buffer must be enabled or disabled
  12546. */
  12547. Engine.prototype.setStencilBuffer = function (enable) {
  12548. this._stencilState.stencilTest = enable;
  12549. };
  12550. /**
  12551. * Gets the current stencil mask
  12552. * @returns a number defining the new stencil mask to use
  12553. */
  12554. Engine.prototype.getStencilMask = function () {
  12555. return this._stencilState.stencilMask;
  12556. };
  12557. /**
  12558. * Sets the current stencil mask
  12559. * @param mask defines the new stencil mask to use
  12560. */
  12561. Engine.prototype.setStencilMask = function (mask) {
  12562. this._stencilState.stencilMask = mask;
  12563. };
  12564. /**
  12565. * Gets the current stencil function
  12566. * @returns a number defining the stencil function to use
  12567. */
  12568. Engine.prototype.getStencilFunction = function () {
  12569. return this._stencilState.stencilFunc;
  12570. };
  12571. /**
  12572. * Gets the current stencil reference value
  12573. * @returns a number defining the stencil reference value to use
  12574. */
  12575. Engine.prototype.getStencilFunctionReference = function () {
  12576. return this._stencilState.stencilFuncRef;
  12577. };
  12578. /**
  12579. * Gets the current stencil mask
  12580. * @returns a number defining the stencil mask to use
  12581. */
  12582. Engine.prototype.getStencilFunctionMask = function () {
  12583. return this._stencilState.stencilFuncMask;
  12584. };
  12585. /**
  12586. * Sets the current stencil function
  12587. * @param stencilFunc defines the new stencil function to use
  12588. */
  12589. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12590. this._stencilState.stencilFunc = stencilFunc;
  12591. };
  12592. /**
  12593. * Sets the current stencil reference
  12594. * @param reference defines the new stencil reference to use
  12595. */
  12596. Engine.prototype.setStencilFunctionReference = function (reference) {
  12597. this._stencilState.stencilFuncRef = reference;
  12598. };
  12599. /**
  12600. * Sets the current stencil mask
  12601. * @param mask defines the new stencil mask to use
  12602. */
  12603. Engine.prototype.setStencilFunctionMask = function (mask) {
  12604. this._stencilState.stencilFuncMask = mask;
  12605. };
  12606. /**
  12607. * Gets the current stencil operation when stencil fails
  12608. * @returns a number defining stencil operation to use when stencil fails
  12609. */
  12610. Engine.prototype.getStencilOperationFail = function () {
  12611. return this._stencilState.stencilOpStencilFail;
  12612. };
  12613. /**
  12614. * Gets the current stencil operation when depth fails
  12615. * @returns a number defining stencil operation to use when depth fails
  12616. */
  12617. Engine.prototype.getStencilOperationDepthFail = function () {
  12618. return this._stencilState.stencilOpDepthFail;
  12619. };
  12620. /**
  12621. * Gets the current stencil operation when stencil passes
  12622. * @returns a number defining stencil operation to use when stencil passes
  12623. */
  12624. Engine.prototype.getStencilOperationPass = function () {
  12625. return this._stencilState.stencilOpStencilDepthPass;
  12626. };
  12627. /**
  12628. * Sets the stencil operation to use when stencil fails
  12629. * @param operation defines the stencil operation to use when stencil fails
  12630. */
  12631. Engine.prototype.setStencilOperationFail = function (operation) {
  12632. this._stencilState.stencilOpStencilFail = operation;
  12633. };
  12634. /**
  12635. * Sets the stencil operation to use when depth fails
  12636. * @param operation defines the stencil operation to use when depth fails
  12637. */
  12638. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12639. this._stencilState.stencilOpDepthFail = operation;
  12640. };
  12641. /**
  12642. * Sets the stencil operation to use when stencil passes
  12643. * @param operation defines the stencil operation to use when stencil passes
  12644. */
  12645. Engine.prototype.setStencilOperationPass = function (operation) {
  12646. this._stencilState.stencilOpStencilDepthPass = operation;
  12647. };
  12648. /**
  12649. * Sets a boolean indicating if the dithering state is enabled or disabled
  12650. * @param value defines the dithering state
  12651. */
  12652. Engine.prototype.setDitheringState = function (value) {
  12653. if (value) {
  12654. this._gl.enable(this._gl.DITHER);
  12655. }
  12656. else {
  12657. this._gl.disable(this._gl.DITHER);
  12658. }
  12659. };
  12660. /**
  12661. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12662. * @param value defines the rasterizer state
  12663. */
  12664. Engine.prototype.setRasterizerState = function (value) {
  12665. if (value) {
  12666. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12667. }
  12668. else {
  12669. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12670. }
  12671. };
  12672. /**
  12673. * stop executing a render loop function and remove it from the execution array
  12674. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12675. */
  12676. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12677. if (!renderFunction) {
  12678. this._activeRenderLoops = [];
  12679. return;
  12680. }
  12681. var index = this._activeRenderLoops.indexOf(renderFunction);
  12682. if (index >= 0) {
  12683. this._activeRenderLoops.splice(index, 1);
  12684. }
  12685. };
  12686. /** @hidden */
  12687. Engine.prototype._renderLoop = function () {
  12688. if (!this._contextWasLost) {
  12689. var shouldRender = true;
  12690. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12691. shouldRender = false;
  12692. }
  12693. if (shouldRender) {
  12694. // Start new frame
  12695. this.beginFrame();
  12696. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12697. var renderFunction = this._activeRenderLoops[index];
  12698. renderFunction();
  12699. }
  12700. // Present
  12701. this.endFrame();
  12702. }
  12703. }
  12704. if (this._activeRenderLoops.length > 0) {
  12705. // Register new frame
  12706. var requester = null;
  12707. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12708. requester = this._vrDisplay;
  12709. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12710. }
  12711. else {
  12712. this._renderingQueueLaunched = false;
  12713. }
  12714. };
  12715. /**
  12716. * Register and execute a render loop. The engine can have more than one render function
  12717. * @param renderFunction defines the function to continuously execute
  12718. */
  12719. Engine.prototype.runRenderLoop = function (renderFunction) {
  12720. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12721. return;
  12722. }
  12723. this._activeRenderLoops.push(renderFunction);
  12724. if (!this._renderingQueueLaunched) {
  12725. this._renderingQueueLaunched = true;
  12726. this._bindedRenderFunction = this._renderLoop.bind(this);
  12727. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12728. }
  12729. };
  12730. /**
  12731. * Toggle full screen mode
  12732. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12733. * @param options defines an option object to be sent to the requestFullscreen function
  12734. */
  12735. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12736. if (this.isFullscreen) {
  12737. BABYLON.Tools.ExitFullscreen();
  12738. }
  12739. else {
  12740. this._pointerLockRequested = requestPointerLock;
  12741. if (this._renderingCanvas) {
  12742. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12743. }
  12744. }
  12745. };
  12746. /**
  12747. * Clear the current render buffer or the current render target (if any is set up)
  12748. * @param color defines the color to use
  12749. * @param backBuffer defines if the back buffer must be cleared
  12750. * @param depth defines if the depth buffer must be cleared
  12751. * @param stencil defines if the stencil buffer must be cleared
  12752. */
  12753. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12754. if (stencil === void 0) { stencil = false; }
  12755. this.applyStates();
  12756. var mode = 0;
  12757. if (backBuffer && color) {
  12758. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12759. mode |= this._gl.COLOR_BUFFER_BIT;
  12760. }
  12761. if (depth) {
  12762. this._gl.clearDepth(1.0);
  12763. mode |= this._gl.DEPTH_BUFFER_BIT;
  12764. }
  12765. if (stencil) {
  12766. this._gl.clearStencil(0);
  12767. mode |= this._gl.STENCIL_BUFFER_BIT;
  12768. }
  12769. this._gl.clear(mode);
  12770. };
  12771. /**
  12772. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12773. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12774. * @param y defines the y-coordinate of the corner of the clear rectangle
  12775. * @param width defines the width of the clear rectangle
  12776. * @param height defines the height of the clear rectangle
  12777. * @param clearColor defines the clear color
  12778. */
  12779. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12780. var gl = this._gl;
  12781. // Save state
  12782. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12783. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12784. // Change state
  12785. gl.enable(gl.SCISSOR_TEST);
  12786. gl.scissor(x, y, width, height);
  12787. // Clear
  12788. this.clear(clearColor, true, true, true);
  12789. // Restore state
  12790. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12791. if (curScissor === true) {
  12792. gl.enable(gl.SCISSOR_TEST);
  12793. }
  12794. else {
  12795. gl.disable(gl.SCISSOR_TEST);
  12796. }
  12797. };
  12798. /**
  12799. * Set the WebGL's viewport
  12800. * @param viewport defines the viewport element to be used
  12801. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12802. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12803. */
  12804. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12805. var width = requiredWidth || this.getRenderWidth();
  12806. var height = requiredHeight || this.getRenderHeight();
  12807. var x = viewport.x || 0;
  12808. var y = viewport.y || 0;
  12809. this._cachedViewport = viewport;
  12810. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12811. };
  12812. /**
  12813. * Directly set the WebGL Viewport
  12814. * @param x defines the x coordinate of the viewport (in screen space)
  12815. * @param y defines the y coordinate of the viewport (in screen space)
  12816. * @param width defines the width of the viewport (in screen space)
  12817. * @param height defines the height of the viewport (in screen space)
  12818. * @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
  12819. */
  12820. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12821. var currentViewport = this._cachedViewport;
  12822. this._cachedViewport = null;
  12823. this._gl.viewport(x, y, width, height);
  12824. return currentViewport;
  12825. };
  12826. /**
  12827. * Begin a new frame
  12828. */
  12829. Engine.prototype.beginFrame = function () {
  12830. this.onBeginFrameObservable.notifyObservers(this);
  12831. this._measureFps();
  12832. };
  12833. /**
  12834. * Enf the current frame
  12835. */
  12836. Engine.prototype.endFrame = function () {
  12837. // Force a flush in case we are using a bad OS.
  12838. if (this._badOS) {
  12839. this.flushFramebuffer();
  12840. }
  12841. // Submit frame to the vr device, if enabled
  12842. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12843. // TODO: We should only submit the frame if we read frameData successfully.
  12844. this._vrDisplay.submitFrame();
  12845. }
  12846. this.onEndFrameObservable.notifyObservers(this);
  12847. };
  12848. /**
  12849. * Resize the view according to the canvas' size
  12850. */
  12851. Engine.prototype.resize = function () {
  12852. // We're not resizing the size of the canvas while in VR mode & presenting
  12853. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12854. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12855. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12856. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12857. }
  12858. };
  12859. /**
  12860. * Force a specific size of the canvas
  12861. * @param width defines the new canvas' width
  12862. * @param height defines the new canvas' height
  12863. */
  12864. Engine.prototype.setSize = function (width, height) {
  12865. if (!this._renderingCanvas) {
  12866. return;
  12867. }
  12868. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12869. return;
  12870. }
  12871. this._renderingCanvas.width = width;
  12872. this._renderingCanvas.height = height;
  12873. for (var index = 0; index < this.scenes.length; index++) {
  12874. var scene = this.scenes[index];
  12875. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12876. var cam = scene.cameras[camIndex];
  12877. cam._currentRenderId = 0;
  12878. }
  12879. }
  12880. if (this.onResizeObservable.hasObservers) {
  12881. this.onResizeObservable.notifyObservers(this);
  12882. }
  12883. };
  12884. // WebVR functions
  12885. /**
  12886. * Gets a boolean indicating if a webVR device was detected
  12887. * @returns true if a webVR device was detected
  12888. */
  12889. Engine.prototype.isVRDevicePresent = function () {
  12890. return !!this._vrDisplay;
  12891. };
  12892. /**
  12893. * Gets the current webVR device
  12894. * @returns the current webVR device (or null)
  12895. */
  12896. Engine.prototype.getVRDevice = function () {
  12897. return this._vrDisplay;
  12898. };
  12899. /**
  12900. * Initializes a webVR display and starts listening to display change events
  12901. * The onVRDisplayChangedObservable will be notified upon these changes
  12902. * @returns The onVRDisplayChangedObservable
  12903. */
  12904. Engine.prototype.initWebVR = function () {
  12905. this.initWebVRAsync();
  12906. return this.onVRDisplayChangedObservable;
  12907. };
  12908. /**
  12909. * Initializes a webVR display and starts listening to display change events
  12910. * The onVRDisplayChangedObservable will be notified upon these changes
  12911. * @returns A promise containing a VRDisplay and if vr is supported
  12912. */
  12913. Engine.prototype.initWebVRAsync = function () {
  12914. var _this = this;
  12915. var notifyObservers = function () {
  12916. var eventArgs = {
  12917. vrDisplay: _this._vrDisplay,
  12918. vrSupported: _this._vrSupported
  12919. };
  12920. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12921. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12922. };
  12923. if (!this._onVrDisplayConnect) {
  12924. this._onVrDisplayConnect = function (event) {
  12925. _this._vrDisplay = event.display;
  12926. notifyObservers();
  12927. };
  12928. this._onVrDisplayDisconnect = function () {
  12929. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12930. _this._vrDisplay = undefined;
  12931. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12932. notifyObservers();
  12933. };
  12934. this._onVrDisplayPresentChange = function () {
  12935. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12936. };
  12937. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12938. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12939. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12940. }
  12941. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12942. this._webVRInitPromise.then(notifyObservers);
  12943. return this._webVRInitPromise;
  12944. };
  12945. /**
  12946. * Call this function to switch to webVR mode
  12947. * Will do nothing if webVR is not supported or if there is no webVR device
  12948. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12949. */
  12950. Engine.prototype.enableVR = function () {
  12951. var _this = this;
  12952. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12953. var onResolved = function () {
  12954. _this.onVRRequestPresentComplete.notifyObservers(true);
  12955. _this._onVRFullScreenTriggered();
  12956. };
  12957. var onRejected = function () {
  12958. _this.onVRRequestPresentComplete.notifyObservers(false);
  12959. };
  12960. this.onVRRequestPresentStart.notifyObservers(this);
  12961. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12962. }
  12963. };
  12964. /**
  12965. * Call this function to leave webVR mode
  12966. * Will do nothing if webVR is not supported or if there is no webVR device
  12967. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12968. */
  12969. Engine.prototype.disableVR = function () {
  12970. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12971. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12972. }
  12973. };
  12974. Engine.prototype._getVRDisplaysAsync = function () {
  12975. var _this = this;
  12976. return new Promise(function (res, rej) {
  12977. if (navigator.getVRDisplays) {
  12978. navigator.getVRDisplays().then(function (devices) {
  12979. _this._vrSupported = true;
  12980. // note that devices may actually be an empty array. This is fine;
  12981. // we expect this._vrDisplay to be undefined in this case.
  12982. _this._vrDisplay = devices[0];
  12983. res({
  12984. vrDisplay: _this._vrDisplay,
  12985. vrSupported: _this._vrSupported
  12986. });
  12987. });
  12988. }
  12989. else {
  12990. _this._vrDisplay = undefined;
  12991. _this._vrSupported = false;
  12992. res({
  12993. vrDisplay: _this._vrDisplay,
  12994. vrSupported: _this._vrSupported
  12995. });
  12996. }
  12997. });
  12998. };
  12999. /**
  13000. * Binds the frame buffer to the specified texture.
  13001. * @param texture The texture to render to or null for the default canvas
  13002. * @param faceIndex The face of the texture to render to in case of cube texture
  13003. * @param requiredWidth The width of the target to render to
  13004. * @param requiredHeight The height of the target to render to
  13005. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13006. * @param depthStencilTexture The depth stencil texture to use to render
  13007. */
  13008. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13009. if (this._currentRenderTarget) {
  13010. this.unBindFramebuffer(this._currentRenderTarget);
  13011. }
  13012. this._currentRenderTarget = texture;
  13013. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13014. var gl = this._gl;
  13015. if (texture.isCube) {
  13016. if (faceIndex === undefined) {
  13017. faceIndex = 0;
  13018. }
  13019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13020. if (depthStencilTexture) {
  13021. if (depthStencilTexture._generateStencilBuffer) {
  13022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13023. }
  13024. else {
  13025. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13026. }
  13027. }
  13028. }
  13029. if (this._cachedViewport && !forceFullscreenViewport) {
  13030. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13031. }
  13032. else {
  13033. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13034. }
  13035. this.wipeCaches();
  13036. };
  13037. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13038. if (this._currentFramebuffer !== framebuffer) {
  13039. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13040. this._currentFramebuffer = framebuffer;
  13041. }
  13042. };
  13043. /**
  13044. * Unbind the current render target texture from the webGL context
  13045. * @param texture defines the render target texture to unbind
  13046. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13047. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13048. */
  13049. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13050. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13051. this._currentRenderTarget = null;
  13052. // If MSAA, we need to bitblt back to main texture
  13053. var gl = this._gl;
  13054. if (texture._MSAAFramebuffer) {
  13055. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13056. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13057. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13058. }
  13059. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13060. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13061. gl.generateMipmap(gl.TEXTURE_2D);
  13062. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13063. }
  13064. if (onBeforeUnbind) {
  13065. if (texture._MSAAFramebuffer) {
  13066. // Bind the correct framebuffer
  13067. this.bindUnboundFramebuffer(texture._framebuffer);
  13068. }
  13069. onBeforeUnbind();
  13070. }
  13071. this.bindUnboundFramebuffer(null);
  13072. };
  13073. /**
  13074. * Unbind a list of render target textures from the webGL context
  13075. * This is used only when drawBuffer extension or webGL2 are active
  13076. * @param textures defines the render target textures to unbind
  13077. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13078. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13079. */
  13080. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13081. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13082. this._currentRenderTarget = null;
  13083. // If MSAA, we need to bitblt back to main texture
  13084. var gl = this._gl;
  13085. if (textures[0]._MSAAFramebuffer) {
  13086. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13087. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13088. var attachments = textures[0]._attachments;
  13089. if (!attachments) {
  13090. attachments = new Array(textures.length);
  13091. textures[0]._attachments = attachments;
  13092. }
  13093. for (var i = 0; i < textures.length; i++) {
  13094. var texture = textures[i];
  13095. for (var j = 0; j < attachments.length; j++) {
  13096. attachments[j] = gl.NONE;
  13097. }
  13098. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13099. gl.readBuffer(attachments[i]);
  13100. gl.drawBuffers(attachments);
  13101. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13102. }
  13103. for (var i = 0; i < attachments.length; i++) {
  13104. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13105. }
  13106. gl.drawBuffers(attachments);
  13107. }
  13108. for (var i = 0; i < textures.length; i++) {
  13109. var texture = textures[i];
  13110. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13111. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13112. gl.generateMipmap(gl.TEXTURE_2D);
  13113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13114. }
  13115. }
  13116. if (onBeforeUnbind) {
  13117. if (textures[0]._MSAAFramebuffer) {
  13118. // Bind the correct framebuffer
  13119. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13120. }
  13121. onBeforeUnbind();
  13122. }
  13123. this.bindUnboundFramebuffer(null);
  13124. };
  13125. /**
  13126. * Force the mipmap generation for the given render target texture
  13127. * @param texture defines the render target texture to use
  13128. */
  13129. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13130. if (texture.generateMipMaps) {
  13131. var gl = this._gl;
  13132. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13133. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13134. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13135. }
  13136. };
  13137. /**
  13138. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13139. */
  13140. Engine.prototype.flushFramebuffer = function () {
  13141. this._gl.flush();
  13142. };
  13143. /**
  13144. * Unbind the current render target and bind the default framebuffer
  13145. */
  13146. Engine.prototype.restoreDefaultFramebuffer = function () {
  13147. if (this._currentRenderTarget) {
  13148. this.unBindFramebuffer(this._currentRenderTarget);
  13149. }
  13150. else {
  13151. this.bindUnboundFramebuffer(null);
  13152. }
  13153. if (this._cachedViewport) {
  13154. this.setViewport(this._cachedViewport);
  13155. }
  13156. this.wipeCaches();
  13157. };
  13158. // UBOs
  13159. /**
  13160. * Create an uniform buffer
  13161. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13162. * @param elements defines the content of the uniform buffer
  13163. * @returns the webGL uniform buffer
  13164. */
  13165. Engine.prototype.createUniformBuffer = function (elements) {
  13166. var ubo = this._gl.createBuffer();
  13167. if (!ubo) {
  13168. throw new Error("Unable to create uniform buffer");
  13169. }
  13170. this.bindUniformBuffer(ubo);
  13171. if (elements instanceof Float32Array) {
  13172. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13173. }
  13174. else {
  13175. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13176. }
  13177. this.bindUniformBuffer(null);
  13178. ubo.references = 1;
  13179. return ubo;
  13180. };
  13181. /**
  13182. * Create a dynamic uniform buffer
  13183. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13184. * @param elements defines the content of the uniform buffer
  13185. * @returns the webGL uniform buffer
  13186. */
  13187. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13188. var ubo = this._gl.createBuffer();
  13189. if (!ubo) {
  13190. throw new Error("Unable to create dynamic uniform buffer");
  13191. }
  13192. this.bindUniformBuffer(ubo);
  13193. if (elements instanceof Float32Array) {
  13194. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13195. }
  13196. else {
  13197. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13198. }
  13199. this.bindUniformBuffer(null);
  13200. ubo.references = 1;
  13201. return ubo;
  13202. };
  13203. /**
  13204. * Update an existing uniform buffer
  13205. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13206. * @param uniformBuffer defines the target uniform buffer
  13207. * @param elements defines the content to update
  13208. * @param offset defines the offset in the uniform buffer where update should start
  13209. * @param count defines the size of the data to update
  13210. */
  13211. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13212. this.bindUniformBuffer(uniformBuffer);
  13213. if (offset === undefined) {
  13214. offset = 0;
  13215. }
  13216. if (count === undefined) {
  13217. if (elements instanceof Float32Array) {
  13218. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13219. }
  13220. else {
  13221. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13222. }
  13223. }
  13224. else {
  13225. if (elements instanceof Float32Array) {
  13226. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13227. }
  13228. else {
  13229. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13230. }
  13231. }
  13232. this.bindUniformBuffer(null);
  13233. };
  13234. // VBOs
  13235. Engine.prototype._resetVertexBufferBinding = function () {
  13236. this.bindArrayBuffer(null);
  13237. this._cachedVertexBuffers = null;
  13238. };
  13239. /**
  13240. * Creates a vertex buffer
  13241. * @param data the data for the vertex buffer
  13242. * @returns the new WebGL static buffer
  13243. */
  13244. Engine.prototype.createVertexBuffer = function (data) {
  13245. var vbo = this._gl.createBuffer();
  13246. if (!vbo) {
  13247. throw new Error("Unable to create vertex buffer");
  13248. }
  13249. this.bindArrayBuffer(vbo);
  13250. if (data instanceof Array) {
  13251. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13252. }
  13253. else {
  13254. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13255. }
  13256. this._resetVertexBufferBinding();
  13257. vbo.references = 1;
  13258. return vbo;
  13259. };
  13260. /**
  13261. * Creates a dynamic vertex buffer
  13262. * @param data the data for the dynamic vertex buffer
  13263. * @returns the new WebGL dynamic buffer
  13264. */
  13265. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13266. var vbo = this._gl.createBuffer();
  13267. if (!vbo) {
  13268. throw new Error("Unable to create dynamic vertex buffer");
  13269. }
  13270. this.bindArrayBuffer(vbo);
  13271. if (data instanceof Array) {
  13272. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13273. }
  13274. else {
  13275. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13276. }
  13277. this._resetVertexBufferBinding();
  13278. vbo.references = 1;
  13279. return vbo;
  13280. };
  13281. /**
  13282. * Update a dynamic index buffer
  13283. * @param indexBuffer defines the target index buffer
  13284. * @param indices defines the data to update
  13285. * @param offset defines the offset in the target index buffer where update should start
  13286. */
  13287. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13288. if (offset === void 0) { offset = 0; }
  13289. // Force cache update
  13290. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13291. this.bindIndexBuffer(indexBuffer);
  13292. var arrayBuffer;
  13293. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13294. arrayBuffer = indices;
  13295. }
  13296. else {
  13297. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13298. }
  13299. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13300. this._resetIndexBufferBinding();
  13301. };
  13302. /**
  13303. * Updates a dynamic vertex buffer.
  13304. * @param vertexBuffer the vertex buffer to update
  13305. * @param data the data used to update the vertex buffer
  13306. * @param byteOffset the byte offset of the data
  13307. * @param byteLength the byte length of the data
  13308. */
  13309. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13310. this.bindArrayBuffer(vertexBuffer);
  13311. if (byteOffset === undefined) {
  13312. byteOffset = 0;
  13313. }
  13314. if (byteLength === undefined) {
  13315. if (data instanceof Array) {
  13316. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13317. }
  13318. else {
  13319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13320. }
  13321. }
  13322. else {
  13323. if (data instanceof Array) {
  13324. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13325. }
  13326. else {
  13327. if (data instanceof ArrayBuffer) {
  13328. data = new Uint8Array(data, byteOffset, byteLength);
  13329. }
  13330. else {
  13331. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13332. }
  13333. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13334. }
  13335. }
  13336. this._resetVertexBufferBinding();
  13337. };
  13338. Engine.prototype._resetIndexBufferBinding = function () {
  13339. this.bindIndexBuffer(null);
  13340. this._cachedIndexBuffer = null;
  13341. };
  13342. /**
  13343. * Creates a new index buffer
  13344. * @param indices defines the content of the index buffer
  13345. * @param updatable defines if the index buffer must be updatable
  13346. * @returns a new webGL buffer
  13347. */
  13348. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13349. var vbo = this._gl.createBuffer();
  13350. if (!vbo) {
  13351. throw new Error("Unable to create index buffer");
  13352. }
  13353. this.bindIndexBuffer(vbo);
  13354. // Check for 32 bits indices
  13355. var arrayBuffer;
  13356. var need32Bits = false;
  13357. if (indices instanceof Uint16Array) {
  13358. arrayBuffer = indices;
  13359. }
  13360. else {
  13361. //check 32 bit support
  13362. if (this._caps.uintIndices) {
  13363. if (indices instanceof Uint32Array) {
  13364. arrayBuffer = indices;
  13365. need32Bits = true;
  13366. }
  13367. else {
  13368. //number[] or Int32Array, check if 32 bit is necessary
  13369. for (var index = 0; index < indices.length; index++) {
  13370. if (indices[index] > 65535) {
  13371. need32Bits = true;
  13372. break;
  13373. }
  13374. }
  13375. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13376. }
  13377. }
  13378. else {
  13379. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13380. arrayBuffer = new Uint16Array(indices);
  13381. }
  13382. }
  13383. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13384. this._resetIndexBufferBinding();
  13385. vbo.references = 1;
  13386. vbo.is32Bits = need32Bits;
  13387. return vbo;
  13388. };
  13389. /**
  13390. * Bind a webGL buffer to the webGL context
  13391. * @param buffer defines the buffer to bind
  13392. */
  13393. Engine.prototype.bindArrayBuffer = function (buffer) {
  13394. if (!this._vaoRecordInProgress) {
  13395. this._unbindVertexArrayObject();
  13396. }
  13397. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13398. };
  13399. /**
  13400. * Bind an uniform buffer to the current webGL context
  13401. * @param buffer defines the buffer to bind
  13402. */
  13403. Engine.prototype.bindUniformBuffer = function (buffer) {
  13404. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13405. };
  13406. /**
  13407. * Bind a buffer to the current webGL context at a given location
  13408. * @param buffer defines the buffer to bind
  13409. * @param location defines the index where to bind the buffer
  13410. */
  13411. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13412. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13413. };
  13414. /**
  13415. * Bind a specific block at a given index in a specific shader program
  13416. * @param shaderProgram defines the shader program
  13417. * @param blockName defines the block name
  13418. * @param index defines the index where to bind the block
  13419. */
  13420. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13421. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13422. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13423. };
  13424. ;
  13425. Engine.prototype.bindIndexBuffer = function (buffer) {
  13426. if (!this._vaoRecordInProgress) {
  13427. this._unbindVertexArrayObject();
  13428. }
  13429. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13430. };
  13431. Engine.prototype.bindBuffer = function (buffer, target) {
  13432. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13433. this._gl.bindBuffer(target, buffer);
  13434. this._currentBoundBuffer[target] = buffer;
  13435. }
  13436. };
  13437. /**
  13438. * update the bound buffer with the given data
  13439. * @param data defines the data to update
  13440. */
  13441. Engine.prototype.updateArrayBuffer = function (data) {
  13442. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13443. };
  13444. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13445. var pointer = this._currentBufferPointers[indx];
  13446. var changed = false;
  13447. if (!pointer.active) {
  13448. changed = true;
  13449. pointer.active = true;
  13450. pointer.index = indx;
  13451. pointer.size = size;
  13452. pointer.type = type;
  13453. pointer.normalized = normalized;
  13454. pointer.stride = stride;
  13455. pointer.offset = offset;
  13456. pointer.buffer = buffer;
  13457. }
  13458. else {
  13459. if (pointer.buffer !== buffer) {
  13460. pointer.buffer = buffer;
  13461. changed = true;
  13462. }
  13463. if (pointer.size !== size) {
  13464. pointer.size = size;
  13465. changed = true;
  13466. }
  13467. if (pointer.type !== type) {
  13468. pointer.type = type;
  13469. changed = true;
  13470. }
  13471. if (pointer.normalized !== normalized) {
  13472. pointer.normalized = normalized;
  13473. changed = true;
  13474. }
  13475. if (pointer.stride !== stride) {
  13476. pointer.stride = stride;
  13477. changed = true;
  13478. }
  13479. if (pointer.offset !== offset) {
  13480. pointer.offset = offset;
  13481. changed = true;
  13482. }
  13483. }
  13484. if (changed || this._vaoRecordInProgress) {
  13485. this.bindArrayBuffer(buffer);
  13486. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13487. }
  13488. };
  13489. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13490. if (indexBuffer == null) {
  13491. return;
  13492. }
  13493. if (this._cachedIndexBuffer !== indexBuffer) {
  13494. this._cachedIndexBuffer = indexBuffer;
  13495. this.bindIndexBuffer(indexBuffer);
  13496. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13497. }
  13498. };
  13499. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13500. var attributes = effect.getAttributesNames();
  13501. if (!this._vaoRecordInProgress) {
  13502. this._unbindVertexArrayObject();
  13503. }
  13504. this.unbindAllAttributes();
  13505. for (var index = 0; index < attributes.length; index++) {
  13506. var order = effect.getAttributeLocation(index);
  13507. if (order >= 0) {
  13508. var vertexBuffer = vertexBuffers[attributes[index]];
  13509. if (!vertexBuffer) {
  13510. continue;
  13511. }
  13512. this._gl.enableVertexAttribArray(order);
  13513. if (!this._vaoRecordInProgress) {
  13514. this._vertexAttribArraysEnabled[order] = true;
  13515. }
  13516. var buffer = vertexBuffer.getBuffer();
  13517. if (buffer) {
  13518. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13519. if (vertexBuffer.getIsInstanced()) {
  13520. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13521. if (!this._vaoRecordInProgress) {
  13522. this._currentInstanceLocations.push(order);
  13523. this._currentInstanceBuffers.push(buffer);
  13524. }
  13525. }
  13526. }
  13527. }
  13528. }
  13529. };
  13530. /**
  13531. * Records a vertex array object
  13532. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13533. * @param vertexBuffers defines the list of vertex buffers to store
  13534. * @param indexBuffer defines the index buffer to store
  13535. * @param effect defines the effect to store
  13536. * @returns the new vertex array object
  13537. */
  13538. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13539. var vao = this._gl.createVertexArray();
  13540. this._vaoRecordInProgress = true;
  13541. this._gl.bindVertexArray(vao);
  13542. this._mustWipeVertexAttributes = true;
  13543. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13544. this.bindIndexBuffer(indexBuffer);
  13545. this._vaoRecordInProgress = false;
  13546. this._gl.bindVertexArray(null);
  13547. return vao;
  13548. };
  13549. /**
  13550. * Bind a specific vertex array object
  13551. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13552. * @param vertexArrayObject defines the vertex array object to bind
  13553. * @param indexBuffer defines the index buffer to bind
  13554. */
  13555. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13556. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13557. this._cachedVertexArrayObject = vertexArrayObject;
  13558. this._gl.bindVertexArray(vertexArrayObject);
  13559. this._cachedVertexBuffers = null;
  13560. this._cachedIndexBuffer = null;
  13561. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13562. this._mustWipeVertexAttributes = true;
  13563. }
  13564. };
  13565. /**
  13566. * Bind webGl buffers directly to the webGL context
  13567. * @param vertexBuffer defines the vertex buffer to bind
  13568. * @param indexBuffer defines the index buffer to bind
  13569. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13570. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13571. * @param effect defines the effect associated with the vertex buffer
  13572. */
  13573. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13574. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13575. this._cachedVertexBuffers = vertexBuffer;
  13576. this._cachedEffectForVertexBuffers = effect;
  13577. var attributesCount = effect.getAttributesCount();
  13578. this._unbindVertexArrayObject();
  13579. this.unbindAllAttributes();
  13580. var offset = 0;
  13581. for (var index = 0; index < attributesCount; index++) {
  13582. if (index < vertexDeclaration.length) {
  13583. var order = effect.getAttributeLocation(index);
  13584. if (order >= 0) {
  13585. this._gl.enableVertexAttribArray(order);
  13586. this._vertexAttribArraysEnabled[order] = true;
  13587. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13588. }
  13589. offset += vertexDeclaration[index] * 4;
  13590. }
  13591. }
  13592. }
  13593. this._bindIndexBufferWithCache(indexBuffer);
  13594. };
  13595. Engine.prototype._unbindVertexArrayObject = function () {
  13596. if (!this._cachedVertexArrayObject) {
  13597. return;
  13598. }
  13599. this._cachedVertexArrayObject = null;
  13600. this._gl.bindVertexArray(null);
  13601. };
  13602. /**
  13603. * Bind a list of vertex buffers to the webGL context
  13604. * @param vertexBuffers defines the list of vertex buffers to bind
  13605. * @param indexBuffer defines the index buffer to bind
  13606. * @param effect defines the effect associated with the vertex buffers
  13607. */
  13608. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13609. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13610. this._cachedVertexBuffers = vertexBuffers;
  13611. this._cachedEffectForVertexBuffers = effect;
  13612. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13613. }
  13614. this._bindIndexBufferWithCache(indexBuffer);
  13615. };
  13616. /**
  13617. * Unbind all instance attributes
  13618. */
  13619. Engine.prototype.unbindInstanceAttributes = function () {
  13620. var boundBuffer;
  13621. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13622. var instancesBuffer = this._currentInstanceBuffers[i];
  13623. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13624. boundBuffer = instancesBuffer;
  13625. this.bindArrayBuffer(instancesBuffer);
  13626. }
  13627. var offsetLocation = this._currentInstanceLocations[i];
  13628. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13629. }
  13630. this._currentInstanceBuffers.length = 0;
  13631. this._currentInstanceLocations.length = 0;
  13632. };
  13633. /**
  13634. * Release and free the memory of a vertex array object
  13635. * @param vao defines the vertex array object to delete
  13636. */
  13637. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13638. this._gl.deleteVertexArray(vao);
  13639. };
  13640. /** @hidden */
  13641. Engine.prototype._releaseBuffer = function (buffer) {
  13642. buffer.references--;
  13643. if (buffer.references === 0) {
  13644. this._gl.deleteBuffer(buffer);
  13645. return true;
  13646. }
  13647. return false;
  13648. };
  13649. /**
  13650. * Creates a webGL buffer to use with instanciation
  13651. * @param capacity defines the size of the buffer
  13652. * @returns the webGL buffer
  13653. */
  13654. Engine.prototype.createInstancesBuffer = function (capacity) {
  13655. var buffer = this._gl.createBuffer();
  13656. if (!buffer) {
  13657. throw new Error("Unable to create instance buffer");
  13658. }
  13659. buffer.capacity = capacity;
  13660. this.bindArrayBuffer(buffer);
  13661. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13662. return buffer;
  13663. };
  13664. /**
  13665. * Delete a webGL buffer used with instanciation
  13666. * @param buffer defines the webGL buffer to delete
  13667. */
  13668. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13669. this._gl.deleteBuffer(buffer);
  13670. };
  13671. /**
  13672. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13673. * @param instancesBuffer defines the webGL buffer to update and bind
  13674. * @param data defines the data to store in the buffer
  13675. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13676. */
  13677. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13678. this.bindArrayBuffer(instancesBuffer);
  13679. if (data) {
  13680. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13681. }
  13682. if (offsetLocations[0].index !== undefined) {
  13683. var stride = 0;
  13684. for (var i = 0; i < offsetLocations.length; i++) {
  13685. var ai = offsetLocations[i];
  13686. stride += ai.attributeSize * 4;
  13687. }
  13688. for (var i = 0; i < offsetLocations.length; i++) {
  13689. var ai = offsetLocations[i];
  13690. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13691. this._gl.enableVertexAttribArray(ai.index);
  13692. this._vertexAttribArraysEnabled[ai.index] = true;
  13693. }
  13694. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13695. this._gl.vertexAttribDivisor(ai.index, 1);
  13696. this._currentInstanceLocations.push(ai.index);
  13697. this._currentInstanceBuffers.push(instancesBuffer);
  13698. }
  13699. }
  13700. else {
  13701. for (var index = 0; index < 4; index++) {
  13702. var offsetLocation = offsetLocations[index];
  13703. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13704. this._gl.enableVertexAttribArray(offsetLocation);
  13705. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13706. }
  13707. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13708. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13709. this._currentInstanceLocations.push(offsetLocation);
  13710. this._currentInstanceBuffers.push(instancesBuffer);
  13711. }
  13712. }
  13713. };
  13714. /**
  13715. * Apply all cached states (depth, culling, stencil and alpha)
  13716. */
  13717. Engine.prototype.applyStates = function () {
  13718. this._depthCullingState.apply(this._gl);
  13719. this._stencilState.apply(this._gl);
  13720. this._alphaState.apply(this._gl);
  13721. };
  13722. /**
  13723. * Send a draw order
  13724. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13725. * @param indexStart defines the starting index
  13726. * @param indexCount defines the number of index to draw
  13727. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13728. */
  13729. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13730. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13731. };
  13732. /**
  13733. * Draw a list of points
  13734. * @param verticesStart defines the index of first vertex to draw
  13735. * @param verticesCount defines the count of vertices to draw
  13736. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13737. */
  13738. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13739. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13740. };
  13741. /**
  13742. * Draw a list of unindexed primitives
  13743. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13744. * @param verticesStart defines the index of first vertex to draw
  13745. * @param verticesCount defines the count of vertices to draw
  13746. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13747. */
  13748. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13749. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13750. };
  13751. /**
  13752. * Draw a list of indexed primitives
  13753. * @param fillMode defines the primitive to use
  13754. * @param indexStart defines the starting index
  13755. * @param indexCount defines the number of index to draw
  13756. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13757. */
  13758. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13759. // Apply states
  13760. this.applyStates();
  13761. this._drawCalls.addCount(1, false);
  13762. // Render
  13763. var drawMode = this._drawMode(fillMode);
  13764. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13765. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13766. if (instancesCount) {
  13767. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13768. }
  13769. else {
  13770. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13771. }
  13772. };
  13773. /**
  13774. * Draw a list of unindexed primitives
  13775. * @param fillMode defines the primitive to use
  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.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13781. // Apply states
  13782. this.applyStates();
  13783. this._drawCalls.addCount(1, false);
  13784. var drawMode = this._drawMode(fillMode);
  13785. if (instancesCount) {
  13786. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13787. }
  13788. else {
  13789. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13790. }
  13791. };
  13792. Engine.prototype._drawMode = function (fillMode) {
  13793. switch (fillMode) {
  13794. // Triangle views
  13795. case BABYLON.Material.TriangleFillMode:
  13796. return this._gl.TRIANGLES;
  13797. case BABYLON.Material.PointFillMode:
  13798. return this._gl.POINTS;
  13799. case BABYLON.Material.WireFrameFillMode:
  13800. return this._gl.LINES;
  13801. // Draw modes
  13802. case BABYLON.Material.PointListDrawMode:
  13803. return this._gl.POINTS;
  13804. case BABYLON.Material.LineListDrawMode:
  13805. return this._gl.LINES;
  13806. case BABYLON.Material.LineLoopDrawMode:
  13807. return this._gl.LINE_LOOP;
  13808. case BABYLON.Material.LineStripDrawMode:
  13809. return this._gl.LINE_STRIP;
  13810. case BABYLON.Material.TriangleStripDrawMode:
  13811. return this._gl.TRIANGLE_STRIP;
  13812. case BABYLON.Material.TriangleFanDrawMode:
  13813. return this._gl.TRIANGLE_FAN;
  13814. default:
  13815. return this._gl.TRIANGLES;
  13816. }
  13817. };
  13818. // Shaders
  13819. /** @hidden */
  13820. Engine.prototype._releaseEffect = function (effect) {
  13821. if (this._compiledEffects[effect._key]) {
  13822. delete this._compiledEffects[effect._key];
  13823. this._deleteProgram(effect.getProgram());
  13824. }
  13825. };
  13826. /** @hidden */
  13827. Engine.prototype._deleteProgram = function (program) {
  13828. if (program) {
  13829. program.__SPECTOR_rebuildProgram = null;
  13830. if (program.transformFeedback) {
  13831. this.deleteTransformFeedback(program.transformFeedback);
  13832. program.transformFeedback = null;
  13833. }
  13834. this._gl.deleteProgram(program);
  13835. }
  13836. };
  13837. /**
  13838. * Create a new effect (used to store vertex/fragment shaders)
  13839. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13840. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13841. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13842. * @param samplers defines an array of string used to represent textures
  13843. * @param defines defines the string containing the defines to use to compile the shaders
  13844. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13845. * @param onCompiled defines a function to call when the effect creation is successful
  13846. * @param onError defines a function to call when the effect creation has failed
  13847. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13848. * @returns the new Effect
  13849. */
  13850. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13851. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13852. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13853. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13854. if (this._compiledEffects[name]) {
  13855. var compiledEffect = this._compiledEffects[name];
  13856. if (onCompiled && compiledEffect.isReady()) {
  13857. onCompiled(compiledEffect);
  13858. }
  13859. return compiledEffect;
  13860. }
  13861. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13862. effect._key = name;
  13863. this._compiledEffects[name] = effect;
  13864. return effect;
  13865. };
  13866. /**
  13867. * Create an effect to use with particle systems
  13868. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13869. * @param uniformsNames defines a list of attribute names
  13870. * @param samplers defines an array of string used to represent textures
  13871. * @param defines defines the string containing the defines to use to compile the shaders
  13872. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13873. * @param onCompiled defines a function to call when the effect creation is successful
  13874. * @param onError defines a function to call when the effect creation has failed
  13875. * @returns the new Effect
  13876. */
  13877. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13878. if (uniformsNames === void 0) { uniformsNames = []; }
  13879. if (samplers === void 0) { samplers = []; }
  13880. if (defines === void 0) { defines = ""; }
  13881. return this.createEffect({
  13882. vertex: "particles",
  13883. fragmentElement: fragmentName
  13884. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13885. };
  13886. /**
  13887. * Directly creates a webGL program
  13888. * @param vertexCode defines the vertex shader code to use
  13889. * @param fragmentCode defines the fragment shader code to use
  13890. * @param context defines the webGL context to use (if not set, the current one will be used)
  13891. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13892. * @returns the new webGL program
  13893. */
  13894. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13895. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13896. context = context || this._gl;
  13897. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13898. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13899. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13900. };
  13901. /**
  13902. * Creates a webGL program
  13903. * @param vertexCode defines the vertex shader code to use
  13904. * @param fragmentCode defines the fragment shader code to use
  13905. * @param defines defines the string containing the defines to use to compile the shaders
  13906. * @param context defines the webGL context to use (if not set, the current one will be used)
  13907. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13908. * @returns the new webGL program
  13909. */
  13910. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13911. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13912. context = context || this._gl;
  13913. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13914. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13915. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13916. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13917. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13918. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13919. return program;
  13920. };
  13921. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13922. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13923. var shaderProgram = context.createProgram();
  13924. if (!shaderProgram) {
  13925. throw new Error("Unable to create program");
  13926. }
  13927. context.attachShader(shaderProgram, vertexShader);
  13928. context.attachShader(shaderProgram, fragmentShader);
  13929. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13930. var transformFeedback = this.createTransformFeedback();
  13931. this.bindTransformFeedback(transformFeedback);
  13932. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13933. shaderProgram.transformFeedback = transformFeedback;
  13934. }
  13935. context.linkProgram(shaderProgram);
  13936. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13937. this.bindTransformFeedback(null);
  13938. }
  13939. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13940. if (!linked) {
  13941. context.validateProgram(shaderProgram);
  13942. var error = context.getProgramInfoLog(shaderProgram);
  13943. if (error) {
  13944. throw new Error(error);
  13945. }
  13946. }
  13947. context.deleteShader(vertexShader);
  13948. context.deleteShader(fragmentShader);
  13949. return shaderProgram;
  13950. };
  13951. /**
  13952. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13953. * @param shaderProgram defines the webGL program to use
  13954. * @param uniformsNames defines the list of uniform names
  13955. * @returns an array of webGL uniform locations
  13956. */
  13957. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13958. var results = new Array();
  13959. for (var index = 0; index < uniformsNames.length; index++) {
  13960. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13961. }
  13962. return results;
  13963. };
  13964. /**
  13965. * Gets the lsit of active attributes for a given webGL program
  13966. * @param shaderProgram defines the webGL program to use
  13967. * @param attributesNames defines the list of attribute names to get
  13968. * @returns an array of indices indicating the offset of each attribute
  13969. */
  13970. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13971. var results = [];
  13972. for (var index = 0; index < attributesNames.length; index++) {
  13973. try {
  13974. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13975. }
  13976. catch (e) {
  13977. results.push(-1);
  13978. }
  13979. }
  13980. return results;
  13981. };
  13982. /**
  13983. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13984. * @param effect defines the effect to activate
  13985. */
  13986. Engine.prototype.enableEffect = function (effect) {
  13987. if (!effect) {
  13988. return;
  13989. }
  13990. // Use program
  13991. this.bindSamplers(effect);
  13992. this._currentEffect = effect;
  13993. if (effect.onBind) {
  13994. effect.onBind(effect);
  13995. }
  13996. effect.onBindObservable.notifyObservers(effect);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of int32
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of int32 to store
  14002. */
  14003. Engine.prototype.setIntArray = function (uniform, array) {
  14004. if (!uniform)
  14005. return;
  14006. this._gl.uniform1iv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of int32 (stored as vec2)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of int32 to store
  14012. */
  14013. Engine.prototype.setIntArray2 = function (uniform, array) {
  14014. if (!uniform || array.length % 2 !== 0)
  14015. return;
  14016. this._gl.uniform2iv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of int32 (stored as vec3)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param array defines the array of int32 to store
  14022. */
  14023. Engine.prototype.setIntArray3 = function (uniform, array) {
  14024. if (!uniform || array.length % 3 !== 0)
  14025. return;
  14026. this._gl.uniform3iv(uniform, array);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to an array of int32 (stored as vec4)
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param array defines the array of int32 to store
  14032. */
  14033. Engine.prototype.setIntArray4 = function (uniform, array) {
  14034. if (!uniform || array.length % 4 !== 0)
  14035. return;
  14036. this._gl.uniform4iv(uniform, array);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to an array of float32
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param array defines the array of float32 to store
  14042. */
  14043. Engine.prototype.setFloatArray = function (uniform, array) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniform1fv(uniform, array);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to an array of float32 (stored as vec2)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param array defines the array of float32 to store
  14052. */
  14053. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14054. if (!uniform || array.length % 2 !== 0)
  14055. return;
  14056. this._gl.uniform2fv(uniform, array);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to an array of float32 (stored as vec3)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param array defines the array of float32 to store
  14062. */
  14063. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14064. if (!uniform || array.length % 3 !== 0)
  14065. return;
  14066. this._gl.uniform3fv(uniform, array);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to an array of float32 (stored as vec4)
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param array defines the array of float32 to store
  14072. */
  14073. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14074. if (!uniform || array.length % 4 !== 0)
  14075. return;
  14076. this._gl.uniform4fv(uniform, array);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to an array of number
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param array defines the array of number to store
  14082. */
  14083. Engine.prototype.setArray = function (uniform, array) {
  14084. if (!uniform)
  14085. return;
  14086. this._gl.uniform1fv(uniform, array);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to an array of number (stored as vec2)
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param array defines the array of number to store
  14092. */
  14093. Engine.prototype.setArray2 = function (uniform, array) {
  14094. if (!uniform || array.length % 2 !== 0)
  14095. return;
  14096. this._gl.uniform2fv(uniform, array);
  14097. };
  14098. /**
  14099. * Set the value of an uniform to an array of number (stored as vec3)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param array defines the array of number to store
  14102. */
  14103. Engine.prototype.setArray3 = function (uniform, array) {
  14104. if (!uniform || array.length % 3 !== 0)
  14105. return;
  14106. this._gl.uniform3fv(uniform, array);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to an array of number (stored as vec4)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param array defines the array of number to store
  14112. */
  14113. Engine.prototype.setArray4 = function (uniform, array) {
  14114. if (!uniform || array.length % 4 !== 0)
  14115. return;
  14116. this._gl.uniform4fv(uniform, array);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to an array of float32 (stored as matrices)
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param matrices defines the array of float32 to store
  14122. */
  14123. Engine.prototype.setMatrices = function (uniform, matrices) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a matrix
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param matrix defines the matrix to store
  14132. */
  14133. Engine.prototype.setMatrix = function (uniform, matrix) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a matrix (3x3)
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14142. */
  14143. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14144. if (!uniform)
  14145. return;
  14146. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to a matrix (2x2)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14152. */
  14153. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14154. if (!uniform)
  14155. return;
  14156. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to a number (int)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param value defines the int number to store
  14162. */
  14163. Engine.prototype.setInt = function (uniform, value) {
  14164. if (!uniform)
  14165. return;
  14166. this._gl.uniform1i(uniform, value);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to a number (float)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param value defines the float number to store
  14172. */
  14173. Engine.prototype.setFloat = function (uniform, value) {
  14174. if (!uniform)
  14175. return;
  14176. this._gl.uniform1f(uniform, value);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to a vec2
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param x defines the 1st component of the value
  14182. * @param y defines the 2nd component of the value
  14183. */
  14184. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform2f(uniform, x, y);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a vec3
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param x defines the 1st component of the value
  14193. * @param y defines the 2nd component of the value
  14194. * @param z defines the 3rd component of the value
  14195. */
  14196. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14197. if (!uniform)
  14198. return;
  14199. this._gl.uniform3f(uniform, x, y, z);
  14200. };
  14201. /**
  14202. * Set the value of an uniform to a boolean
  14203. * @param uniform defines the webGL uniform location where to store the value
  14204. * @param bool defines the boolean to store
  14205. */
  14206. Engine.prototype.setBool = function (uniform, bool) {
  14207. if (!uniform)
  14208. return;
  14209. this._gl.uniform1i(uniform, bool);
  14210. };
  14211. /**
  14212. * Set the value of an uniform to a vec4
  14213. * @param uniform defines the webGL uniform location where to store the value
  14214. * @param x defines the 1st component of the value
  14215. * @param y defines the 2nd component of the value
  14216. * @param z defines the 3rd component of the value
  14217. * @param w defines the 4th component of the value
  14218. */
  14219. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14220. if (!uniform)
  14221. return;
  14222. this._gl.uniform4f(uniform, x, y, z, w);
  14223. };
  14224. /**
  14225. * Set the value of an uniform to a Color3
  14226. * @param uniform defines the webGL uniform location where to store the value
  14227. * @param color3 defines the color to store
  14228. */
  14229. Engine.prototype.setColor3 = function (uniform, color3) {
  14230. if (!uniform)
  14231. return;
  14232. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14233. };
  14234. /**
  14235. * Set the value of an uniform to a Color3 and an alpha value
  14236. * @param uniform defines the webGL uniform location where to store the value
  14237. * @param color3 defines the color to store
  14238. * @param alpha defines the alpha component to store
  14239. */
  14240. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14241. if (!uniform)
  14242. return;
  14243. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14244. };
  14245. /**
  14246. * Sets a Color4 on a uniform variable
  14247. * @param uniform defines the uniform location
  14248. * @param color4 defines the value to be set
  14249. */
  14250. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14251. if (!uniform)
  14252. return;
  14253. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14254. };
  14255. // States
  14256. /**
  14257. * Set various states to the webGL context
  14258. * @param culling defines backface culling state
  14259. * @param zOffset defines the value to apply to zOffset (0 by default)
  14260. * @param force defines if states must be applied even if cache is up to date
  14261. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14262. */
  14263. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14264. if (zOffset === void 0) { zOffset = 0; }
  14265. if (reverseSide === void 0) { reverseSide = false; }
  14266. // Culling
  14267. if (this._depthCullingState.cull !== culling || force) {
  14268. this._depthCullingState.cull = culling;
  14269. }
  14270. // Cull face
  14271. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14272. if (this._depthCullingState.cullFace !== cullFace || force) {
  14273. this._depthCullingState.cullFace = cullFace;
  14274. }
  14275. // Z offset
  14276. this.setZOffset(zOffset);
  14277. // Front face
  14278. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14279. if (this._depthCullingState.frontFace !== frontFace || force) {
  14280. this._depthCullingState.frontFace = frontFace;
  14281. }
  14282. };
  14283. /**
  14284. * Set the z offset to apply to current rendering
  14285. * @param value defines the offset to apply
  14286. */
  14287. Engine.prototype.setZOffset = function (value) {
  14288. this._depthCullingState.zOffset = value;
  14289. };
  14290. /**
  14291. * Gets the current value of the zOffset
  14292. * @returns the current zOffset state
  14293. */
  14294. Engine.prototype.getZOffset = function () {
  14295. return this._depthCullingState.zOffset;
  14296. };
  14297. /**
  14298. * Enable or disable depth buffering
  14299. * @param enable defines the state to set
  14300. */
  14301. Engine.prototype.setDepthBuffer = function (enable) {
  14302. this._depthCullingState.depthTest = enable;
  14303. };
  14304. /**
  14305. * Gets a boolean indicating if depth writing is enabled
  14306. * @returns the current depth writing state
  14307. */
  14308. Engine.prototype.getDepthWrite = function () {
  14309. return this._depthCullingState.depthMask;
  14310. };
  14311. /**
  14312. * Enable or disable depth writing
  14313. * @param enable defines the state to set
  14314. */
  14315. Engine.prototype.setDepthWrite = function (enable) {
  14316. this._depthCullingState.depthMask = enable;
  14317. };
  14318. /**
  14319. * Enable or disable color writing
  14320. * @param enable defines the state to set
  14321. */
  14322. Engine.prototype.setColorWrite = function (enable) {
  14323. this._gl.colorMask(enable, enable, enable, enable);
  14324. this._colorWrite = enable;
  14325. };
  14326. /**
  14327. * Gets a boolean indicating if color writing is enabled
  14328. * @returns the current color writing state
  14329. */
  14330. Engine.prototype.getColorWrite = function () {
  14331. return this._colorWrite;
  14332. };
  14333. /**
  14334. * Sets alpha constants used by some alpha blending modes
  14335. * @param r defines the red component
  14336. * @param g defines the green component
  14337. * @param b defines the blue component
  14338. * @param a defines the alpha component
  14339. */
  14340. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14341. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14342. };
  14343. /**
  14344. * Sets the current alpha mode
  14345. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14346. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14347. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14348. */
  14349. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14350. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14351. if (this._alphaMode === mode) {
  14352. return;
  14353. }
  14354. switch (mode) {
  14355. case Engine.ALPHA_DISABLE:
  14356. this._alphaState.alphaBlend = false;
  14357. break;
  14358. case Engine.ALPHA_PREMULTIPLIED:
  14359. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14360. this._alphaState.alphaBlend = true;
  14361. break;
  14362. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14363. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14364. this._alphaState.alphaBlend = true;
  14365. break;
  14366. case Engine.ALPHA_COMBINE:
  14367. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14368. this._alphaState.alphaBlend = true;
  14369. break;
  14370. case Engine.ALPHA_ONEONE:
  14371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14372. this._alphaState.alphaBlend = true;
  14373. break;
  14374. case Engine.ALPHA_ADD:
  14375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14376. this._alphaState.alphaBlend = true;
  14377. break;
  14378. case Engine.ALPHA_SUBTRACT:
  14379. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14380. this._alphaState.alphaBlend = true;
  14381. break;
  14382. case Engine.ALPHA_MULTIPLY:
  14383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14384. this._alphaState.alphaBlend = true;
  14385. break;
  14386. case Engine.ALPHA_MAXIMIZED:
  14387. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14388. this._alphaState.alphaBlend = true;
  14389. break;
  14390. case Engine.ALPHA_INTERPOLATE:
  14391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14392. this._alphaState.alphaBlend = true;
  14393. break;
  14394. case Engine.ALPHA_SCREENMODE:
  14395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14396. this._alphaState.alphaBlend = true;
  14397. break;
  14398. }
  14399. if (!noDepthWriteChange) {
  14400. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14401. }
  14402. this._alphaMode = mode;
  14403. };
  14404. /**
  14405. * Gets the current alpha mode
  14406. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14407. * @returns the current alpha mode
  14408. */
  14409. Engine.prototype.getAlphaMode = function () {
  14410. return this._alphaMode;
  14411. };
  14412. // Textures
  14413. /**
  14414. * Force the entire cache to be cleared
  14415. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14416. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14417. */
  14418. Engine.prototype.wipeCaches = function (bruteForce) {
  14419. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14420. return;
  14421. }
  14422. this._currentEffect = null;
  14423. if (bruteForce) {
  14424. this.resetTextureCache();
  14425. this._currentProgram = null;
  14426. this._stencilState.reset();
  14427. this._depthCullingState.reset();
  14428. this.setDepthFunctionToLessOrEqual();
  14429. this._alphaState.reset();
  14430. }
  14431. this._resetVertexBufferBinding();
  14432. this._cachedIndexBuffer = null;
  14433. this._cachedEffectForVertexBuffers = null;
  14434. this._unbindVertexArrayObject();
  14435. this.bindIndexBuffer(null);
  14436. };
  14437. /**
  14438. * Set the compressed texture format to use, based on the formats you have, and the formats
  14439. * supported by the hardware / browser.
  14440. *
  14441. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14442. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14443. * to API arguments needed to compressed textures. This puts the burden on the container
  14444. * generator to house the arcane code for determining these for current & future formats.
  14445. *
  14446. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14447. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14448. *
  14449. * Note: The result of this call is not taken into account when a texture is base64.
  14450. *
  14451. * @param formatsAvailable defines the list of those format families you have created
  14452. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14453. *
  14454. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14455. * @returns The extension selected.
  14456. */
  14457. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14458. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14459. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14460. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14461. return this._textureFormatInUse = this._texturesSupported[i];
  14462. }
  14463. }
  14464. }
  14465. // actively set format to nothing, to allow this to be called more than once
  14466. // and possibly fail the 2nd time
  14467. this._textureFormatInUse = null;
  14468. return null;
  14469. };
  14470. /** @hidden */
  14471. Engine.prototype._createTexture = function () {
  14472. var texture = this._gl.createTexture();
  14473. if (!texture) {
  14474. throw new Error("Unable to create texture");
  14475. }
  14476. return texture;
  14477. };
  14478. /**
  14479. * Usually called from BABYLON.Texture.ts.
  14480. * Passed information to create a WebGLTexture
  14481. * @param urlArg defines a value which contains one of the following:
  14482. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14483. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14484. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14485. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14486. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14487. * @param scene needed for loading to the correct scene
  14488. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14489. * @param onLoad optional callback to be called upon successful completion
  14490. * @param onError optional callback to be called upon failure
  14491. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14492. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14493. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14494. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14495. */
  14496. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14497. var _this = this;
  14498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14499. if (onLoad === void 0) { onLoad = null; }
  14500. if (onError === void 0) { onError = null; }
  14501. if (buffer === void 0) { buffer = null; }
  14502. if (fallback === void 0) { fallback = null; }
  14503. if (format === void 0) { format = null; }
  14504. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14505. var fromData = url.substr(0, 5) === "data:";
  14506. var fromBlob = url.substr(0, 5) === "blob:";
  14507. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14508. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14509. // establish the file extension, if possible
  14510. var lastDot = url.lastIndexOf('.');
  14511. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14512. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14513. var isTGA = (extension.indexOf(".tga") === 0);
  14514. // determine if a ktx file should be substituted
  14515. var isKTX = false;
  14516. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14517. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14518. isKTX = true;
  14519. }
  14520. if (scene) {
  14521. scene._addPendingData(texture);
  14522. }
  14523. texture.url = url;
  14524. texture.generateMipMaps = !noMipmap;
  14525. texture.samplingMode = samplingMode;
  14526. texture.invertY = invertY;
  14527. if (!this._doNotHandleContextLost) {
  14528. // Keep a link to the buffer only if we plan to handle context lost
  14529. texture._buffer = buffer;
  14530. }
  14531. var onLoadObserver = null;
  14532. if (onLoad && !fallback) {
  14533. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14534. }
  14535. if (!fallback)
  14536. this._internalTexturesCache.push(texture);
  14537. var onerror = function (message, exception) {
  14538. if (scene) {
  14539. scene._removePendingData(texture);
  14540. }
  14541. if (onLoadObserver) {
  14542. texture.onLoadedObservable.remove(onLoadObserver);
  14543. }
  14544. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14545. if (isKTX) {
  14546. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14547. }
  14548. else if (BABYLON.Tools.UseFallbackTexture) {
  14549. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14550. }
  14551. if (onError) {
  14552. onError(message || "Unknown error", exception);
  14553. }
  14554. };
  14555. var callback = null;
  14556. // processing for non-image formats
  14557. if (isKTX || isTGA || isDDS) {
  14558. if (isKTX) {
  14559. callback = function (data) {
  14560. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14561. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14562. ktx.uploadLevels(_this._gl, !noMipmap);
  14563. return false;
  14564. }, samplingMode);
  14565. };
  14566. }
  14567. else if (isTGA) {
  14568. callback = function (arrayBuffer) {
  14569. var data = new Uint8Array(arrayBuffer);
  14570. var header = BABYLON.TGATools.GetTGAHeader(data);
  14571. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14572. BABYLON.TGATools.UploadContent(_this._gl, data);
  14573. return false;
  14574. }, samplingMode);
  14575. };
  14576. }
  14577. else if (isDDS) {
  14578. callback = function (data) {
  14579. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14580. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14581. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14582. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14583. return false;
  14584. }, samplingMode);
  14585. };
  14586. }
  14587. if (!buffer) {
  14588. this._loadFile(url, function (data) {
  14589. if (callback) {
  14590. callback(data);
  14591. }
  14592. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14593. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14594. });
  14595. }
  14596. else {
  14597. if (callback) {
  14598. callback(buffer);
  14599. }
  14600. }
  14601. // image format processing
  14602. }
  14603. else {
  14604. var onload = function (img) {
  14605. if (fromBlob && !_this._doNotHandleContextLost) {
  14606. // We need to store the image if we need to rebuild the texture
  14607. // in case of a webgl context lost
  14608. texture._buffer = img;
  14609. }
  14610. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14611. var gl = _this._gl;
  14612. var isPot = (img.width === potWidth && img.height === potHeight);
  14613. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14614. if (isPot) {
  14615. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14616. return false;
  14617. }
  14618. // Using shaders to rescale because canvas.drawImage is lossy
  14619. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14620. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14621. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14626. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14627. _this._releaseTexture(source);
  14628. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14629. continuationCallback();
  14630. });
  14631. return true;
  14632. }, samplingMode);
  14633. };
  14634. if (!fromData || isBase64)
  14635. if (buffer instanceof HTMLImageElement) {
  14636. onload(buffer);
  14637. }
  14638. else {
  14639. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14640. }
  14641. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14642. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14643. else
  14644. onload(buffer);
  14645. }
  14646. return texture;
  14647. };
  14648. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14649. var _this = this;
  14650. var rtt = this.createRenderTargetTexture({
  14651. width: destination.width,
  14652. height: destination.height,
  14653. }, {
  14654. generateMipMaps: false,
  14655. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14656. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14657. generateDepthBuffer: false,
  14658. generateStencilBuffer: false
  14659. });
  14660. if (!this._rescalePostProcess) {
  14661. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14662. }
  14663. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14664. _this._rescalePostProcess.onApply = function (effect) {
  14665. effect._bindTexture("textureSampler", source);
  14666. };
  14667. var hostingScene = scene;
  14668. if (!hostingScene) {
  14669. hostingScene = _this.scenes[_this.scenes.length - 1];
  14670. }
  14671. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14672. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14673. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14674. _this.unBindFramebuffer(rtt);
  14675. _this._releaseTexture(rtt);
  14676. if (onComplete) {
  14677. onComplete();
  14678. }
  14679. });
  14680. };
  14681. /**
  14682. * Update a raw texture
  14683. * @param texture defines the texture to update
  14684. * @param data defines the data to store in the texture
  14685. * @param format defines the format of the data
  14686. * @param invertY defines if data must be stored with Y axis inverted
  14687. * @param compression defines the compression used (null by default)
  14688. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14689. */
  14690. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14691. if (compression === void 0) { compression = null; }
  14692. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14693. if (!texture) {
  14694. return;
  14695. }
  14696. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14697. var internalFormat = this._getInternalFormat(format);
  14698. var textureType = this._getWebGLTextureType(type);
  14699. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14700. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14701. if (!this._doNotHandleContextLost) {
  14702. texture._bufferView = data;
  14703. texture.format = format;
  14704. texture.type = type;
  14705. texture.invertY = invertY;
  14706. texture._compression = compression;
  14707. }
  14708. if (texture.width % 4 !== 0) {
  14709. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14710. }
  14711. if (compression && data) {
  14712. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14713. }
  14714. else {
  14715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14716. }
  14717. if (texture.generateMipMaps) {
  14718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14719. }
  14720. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14721. // this.resetTextureCache();
  14722. texture.isReady = true;
  14723. };
  14724. /**
  14725. * Creates a raw texture
  14726. * @param data defines the data to store in the texture
  14727. * @param width defines the width of the texture
  14728. * @param height defines the height of the texture
  14729. * @param format defines the format of the data
  14730. * @param generateMipMaps defines if the engine should generate the mip levels
  14731. * @param invertY defines if data must be stored with Y axis inverted
  14732. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14733. * @param compression defines the compression used (null by default)
  14734. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14735. * @returns the raw texture inside an InternalTexture
  14736. */
  14737. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14738. if (compression === void 0) { compression = null; }
  14739. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14741. texture.baseWidth = width;
  14742. texture.baseHeight = height;
  14743. texture.width = width;
  14744. texture.height = height;
  14745. texture.format = format;
  14746. texture.generateMipMaps = generateMipMaps;
  14747. texture.samplingMode = samplingMode;
  14748. texture.invertY = invertY;
  14749. texture._compression = compression;
  14750. texture.type = type;
  14751. if (!this._doNotHandleContextLost) {
  14752. texture._bufferView = data;
  14753. }
  14754. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14755. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14756. // Filters
  14757. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14758. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14760. if (generateMipMaps) {
  14761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14762. }
  14763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14764. this._internalTexturesCache.push(texture);
  14765. return texture;
  14766. };
  14767. /**
  14768. * Creates a dynamic texture
  14769. * @param width defines the width of the texture
  14770. * @param height defines the height of the texture
  14771. * @param generateMipMaps defines if the engine should generate the mip levels
  14772. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14773. * @returns the dynamic texture inside an InternalTexture
  14774. */
  14775. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14776. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14777. texture.baseWidth = width;
  14778. texture.baseHeight = height;
  14779. if (generateMipMaps) {
  14780. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14781. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14782. }
  14783. // this.resetTextureCache();
  14784. texture.width = width;
  14785. texture.height = height;
  14786. texture.isReady = false;
  14787. texture.generateMipMaps = generateMipMaps;
  14788. texture.samplingMode = samplingMode;
  14789. this.updateTextureSamplingMode(samplingMode, texture);
  14790. this._internalTexturesCache.push(texture);
  14791. return texture;
  14792. };
  14793. /**
  14794. * Update the sampling mode of a given texture
  14795. * @param samplingMode defines the required sampling mode
  14796. * @param texture defines the texture to update
  14797. */
  14798. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14799. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14800. if (texture.isCube) {
  14801. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14802. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14803. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14804. }
  14805. else if (texture.is3D) {
  14806. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14807. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14808. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14809. }
  14810. else {
  14811. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14812. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14814. }
  14815. texture.samplingMode = samplingMode;
  14816. };
  14817. /**
  14818. * Update the content of a dynamic texture
  14819. * @param texture defines the texture to update
  14820. * @param canvas defines the canvas containing the source
  14821. * @param invertY defines if data must be stored with Y axis inverted
  14822. * @param premulAlpha defines if alpha is stored as premultiplied
  14823. * @param format defines the format of the data
  14824. */
  14825. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14826. if (premulAlpha === void 0) { premulAlpha = false; }
  14827. if (!texture) {
  14828. return;
  14829. }
  14830. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14831. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14832. if (premulAlpha) {
  14833. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14834. }
  14835. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14836. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14837. if (texture.generateMipMaps) {
  14838. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14839. }
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14841. if (premulAlpha) {
  14842. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14843. }
  14844. texture.isReady = true;
  14845. };
  14846. /**
  14847. * Update a video texture
  14848. * @param texture defines the texture to update
  14849. * @param video defines the video element to use
  14850. * @param invertY defines if data must be stored with Y axis inverted
  14851. */
  14852. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14853. if (!texture || texture._isDisabled) {
  14854. return;
  14855. }
  14856. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14857. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14858. try {
  14859. // Testing video texture support
  14860. if (this._videoTextureSupported === undefined) {
  14861. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14862. if (this._gl.getError() !== 0) {
  14863. this._videoTextureSupported = false;
  14864. }
  14865. else {
  14866. this._videoTextureSupported = true;
  14867. }
  14868. }
  14869. // Copy video through the current working canvas if video texture is not supported
  14870. if (!this._videoTextureSupported) {
  14871. if (!texture._workingCanvas) {
  14872. texture._workingCanvas = document.createElement("canvas");
  14873. var context = texture._workingCanvas.getContext("2d");
  14874. if (!context) {
  14875. throw new Error("Unable to get 2d context");
  14876. }
  14877. texture._workingContext = context;
  14878. texture._workingCanvas.width = texture.width;
  14879. texture._workingCanvas.height = texture.height;
  14880. }
  14881. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14882. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14883. }
  14884. else {
  14885. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14886. }
  14887. if (texture.generateMipMaps) {
  14888. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14889. }
  14890. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14891. // this.resetTextureCache();
  14892. texture.isReady = true;
  14893. }
  14894. catch (ex) {
  14895. // Something unexpected
  14896. // Let's disable the texture
  14897. texture._isDisabled = true;
  14898. }
  14899. };
  14900. /**
  14901. * Updates a depth texture Comparison Mode and Function.
  14902. * If the comparison Function is equal to 0, the mode will be set to none.
  14903. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14904. * @param texture The texture to set the comparison function for
  14905. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14906. */
  14907. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14908. if (this.webGLVersion === 1) {
  14909. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14910. return;
  14911. }
  14912. var gl = this._gl;
  14913. if (texture.isCube) {
  14914. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14915. if (comparisonFunction === 0) {
  14916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14918. }
  14919. else {
  14920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14922. }
  14923. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14924. }
  14925. else {
  14926. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14927. if (comparisonFunction === 0) {
  14928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14930. }
  14931. else {
  14932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14934. }
  14935. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14936. }
  14937. texture._comparisonFunction = comparisonFunction;
  14938. };
  14939. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14940. var width = size.width || size;
  14941. var height = size.height || size;
  14942. internalTexture.baseWidth = width;
  14943. internalTexture.baseHeight = height;
  14944. internalTexture.width = width;
  14945. internalTexture.height = height;
  14946. internalTexture.isReady = true;
  14947. internalTexture.samples = 1;
  14948. internalTexture.generateMipMaps = false;
  14949. internalTexture._generateDepthBuffer = true;
  14950. internalTexture._generateStencilBuffer = generateStencil;
  14951. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14952. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14953. internalTexture._comparisonFunction = comparisonFunction;
  14954. var gl = this._gl;
  14955. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14956. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14957. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14958. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14959. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14960. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14961. if (comparisonFunction === 0) {
  14962. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14963. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14964. }
  14965. else {
  14966. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14967. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14968. }
  14969. };
  14970. /**
  14971. * Creates a depth stencil texture.
  14972. * This is only available in WebGL 2 or with the depth texture extension available.
  14973. * @param size The size of face edge in the texture.
  14974. * @param options The options defining the texture.
  14975. * @returns The texture
  14976. */
  14977. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14978. if (options.isCube) {
  14979. var width = size.width || size;
  14980. return this._createDepthStencilCubeTexture(width, options);
  14981. }
  14982. else {
  14983. return this._createDepthStencilTexture(size, options);
  14984. }
  14985. };
  14986. /**
  14987. * Creates a depth stencil texture.
  14988. * This is only available in WebGL 2 or with the depth texture extension available.
  14989. * @param size The size of face edge in the texture.
  14990. * @param options The options defining the texture.
  14991. * @returns The texture
  14992. */
  14993. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14994. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14995. if (!this._caps.depthTextureExtension) {
  14996. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14997. return internalTexture;
  14998. }
  14999. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15000. var gl = this._gl;
  15001. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15002. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15003. if (this.webGLVersion > 1) {
  15004. if (internalOptions.generateStencil) {
  15005. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15006. }
  15007. else {
  15008. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15009. }
  15010. }
  15011. else {
  15012. if (internalOptions.generateStencil) {
  15013. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15014. }
  15015. else {
  15016. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15017. }
  15018. }
  15019. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15020. return internalTexture;
  15021. };
  15022. /**
  15023. * Creates a depth stencil cube texture.
  15024. * This is only available in WebGL 2.
  15025. * @param size The size of face edge in the cube texture.
  15026. * @param options The options defining the cube texture.
  15027. * @returns The cube texture
  15028. */
  15029. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15030. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15031. internalTexture.isCube = true;
  15032. if (this.webGLVersion === 1) {
  15033. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15034. return internalTexture;
  15035. }
  15036. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15037. var gl = this._gl;
  15038. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15039. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15040. // Create the depth/stencil buffer
  15041. for (var face = 0; face < 6; face++) {
  15042. if (internalOptions.generateStencil) {
  15043. 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);
  15044. }
  15045. else {
  15046. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15047. }
  15048. }
  15049. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15050. return internalTexture;
  15051. };
  15052. /**
  15053. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15054. * @param renderTarget The render target to set the frame buffer for
  15055. */
  15056. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15057. // Create the framebuffer
  15058. var internalTexture = renderTarget.getInternalTexture();
  15059. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15060. return;
  15061. }
  15062. var gl = this._gl;
  15063. var depthStencilTexture = renderTarget.depthStencilTexture;
  15064. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15065. if (depthStencilTexture.isCube) {
  15066. if (depthStencilTexture._generateStencilBuffer) {
  15067. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15068. }
  15069. else {
  15070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15071. }
  15072. }
  15073. else {
  15074. if (depthStencilTexture._generateStencilBuffer) {
  15075. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15076. }
  15077. else {
  15078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15079. }
  15080. }
  15081. this.bindUnboundFramebuffer(null);
  15082. };
  15083. /**
  15084. * Creates a new render target texture
  15085. * @param size defines the size of the texture
  15086. * @param options defines the options used to create the texture
  15087. * @returns a new render target texture stored in an InternalTexture
  15088. */
  15089. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15090. var fullOptions = new RenderTargetCreationOptions();
  15091. if (options !== undefined && typeof options === "object") {
  15092. fullOptions.generateMipMaps = options.generateMipMaps;
  15093. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15094. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15095. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15096. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15097. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15098. }
  15099. else {
  15100. fullOptions.generateMipMaps = options;
  15101. fullOptions.generateDepthBuffer = true;
  15102. fullOptions.generateStencilBuffer = false;
  15103. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15104. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15105. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15106. }
  15107. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15108. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15109. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15110. }
  15111. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15112. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15113. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15114. }
  15115. var gl = this._gl;
  15116. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15117. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15118. var width = size.width || size;
  15119. var height = size.height || size;
  15120. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15121. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15122. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15123. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15124. }
  15125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15129. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15130. // Create the framebuffer
  15131. var framebuffer = gl.createFramebuffer();
  15132. this.bindUnboundFramebuffer(framebuffer);
  15133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15134. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15135. if (fullOptions.generateMipMaps) {
  15136. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15137. }
  15138. // Unbind
  15139. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15140. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15141. this.bindUnboundFramebuffer(null);
  15142. texture._framebuffer = framebuffer;
  15143. texture.baseWidth = width;
  15144. texture.baseHeight = height;
  15145. texture.width = width;
  15146. texture.height = height;
  15147. texture.isReady = true;
  15148. texture.samples = 1;
  15149. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15150. texture.samplingMode = fullOptions.samplingMode;
  15151. texture.type = fullOptions.type;
  15152. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15153. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15154. // this.resetTextureCache();
  15155. this._internalTexturesCache.push(texture);
  15156. return texture;
  15157. };
  15158. /**
  15159. * Create a multi render target texture
  15160. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15161. * @param size defines the size of the texture
  15162. * @param options defines the creation options
  15163. * @returns the cube texture as an InternalTexture
  15164. */
  15165. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15166. var generateMipMaps = false;
  15167. var generateDepthBuffer = true;
  15168. var generateStencilBuffer = false;
  15169. var generateDepthTexture = false;
  15170. var textureCount = 1;
  15171. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15172. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15173. var types = new Array();
  15174. var samplingModes = new Array();
  15175. if (options !== undefined) {
  15176. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15177. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15178. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15179. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15180. textureCount = options.textureCount || 1;
  15181. if (options.types) {
  15182. types = options.types;
  15183. }
  15184. if (options.samplingModes) {
  15185. samplingModes = options.samplingModes;
  15186. }
  15187. }
  15188. var gl = this._gl;
  15189. // Create the framebuffer
  15190. var framebuffer = gl.createFramebuffer();
  15191. this.bindUnboundFramebuffer(framebuffer);
  15192. var width = size.width || size;
  15193. var height = size.height || size;
  15194. var textures = [];
  15195. var attachments = [];
  15196. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15197. for (var i = 0; i < textureCount; i++) {
  15198. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15199. var type = types[i] || defaultType;
  15200. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15201. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15202. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15203. }
  15204. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15205. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15206. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15207. }
  15208. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15209. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15210. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15211. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15212. }
  15213. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15214. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15215. textures.push(texture);
  15216. attachments.push(attachment);
  15217. gl.activeTexture(gl["TEXTURE" + i]);
  15218. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15222. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15223. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15224. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15225. if (generateMipMaps) {
  15226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15227. }
  15228. // Unbind
  15229. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15230. texture._framebuffer = framebuffer;
  15231. texture._depthStencilBuffer = depthStencilBuffer;
  15232. texture.baseWidth = width;
  15233. texture.baseHeight = height;
  15234. texture.width = width;
  15235. texture.height = height;
  15236. texture.isReady = true;
  15237. texture.samples = 1;
  15238. texture.generateMipMaps = generateMipMaps;
  15239. texture.samplingMode = samplingMode;
  15240. texture.type = type;
  15241. texture._generateDepthBuffer = generateDepthBuffer;
  15242. texture._generateStencilBuffer = generateStencilBuffer;
  15243. texture._attachments = attachments;
  15244. this._internalTexturesCache.push(texture);
  15245. }
  15246. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15247. // Depth texture
  15248. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15249. gl.activeTexture(gl.TEXTURE0);
  15250. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15255. 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);
  15256. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15257. depthTexture._framebuffer = framebuffer;
  15258. depthTexture.baseWidth = width;
  15259. depthTexture.baseHeight = height;
  15260. depthTexture.width = width;
  15261. depthTexture.height = height;
  15262. depthTexture.isReady = true;
  15263. depthTexture.samples = 1;
  15264. depthTexture.generateMipMaps = generateMipMaps;
  15265. depthTexture.samplingMode = gl.NEAREST;
  15266. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15267. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15268. textures.push(depthTexture);
  15269. this._internalTexturesCache.push(depthTexture);
  15270. }
  15271. gl.drawBuffers(attachments);
  15272. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15273. this.bindUnboundFramebuffer(null);
  15274. this.resetTextureCache();
  15275. return textures;
  15276. };
  15277. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15278. if (samples === void 0) { samples = 1; }
  15279. var depthStencilBuffer = null;
  15280. var gl = this._gl;
  15281. // Create the depth/stencil buffer
  15282. if (generateStencilBuffer) {
  15283. depthStencilBuffer = gl.createRenderbuffer();
  15284. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15285. if (samples > 1) {
  15286. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15287. }
  15288. else {
  15289. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15290. }
  15291. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15292. }
  15293. else if (generateDepthBuffer) {
  15294. depthStencilBuffer = gl.createRenderbuffer();
  15295. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15296. if (samples > 1) {
  15297. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15298. }
  15299. else {
  15300. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15301. }
  15302. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15303. }
  15304. return depthStencilBuffer;
  15305. };
  15306. /**
  15307. * Updates the sample count of a render target texture
  15308. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15309. * @param texture defines the texture to update
  15310. * @param samples defines the sample count to set
  15311. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15312. */
  15313. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15314. if (this.webGLVersion < 2 || !texture) {
  15315. return 1;
  15316. }
  15317. if (texture.samples === samples) {
  15318. return samples;
  15319. }
  15320. var gl = this._gl;
  15321. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15322. // Dispose previous render buffers
  15323. if (texture._depthStencilBuffer) {
  15324. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15325. texture._depthStencilBuffer = null;
  15326. }
  15327. if (texture._MSAAFramebuffer) {
  15328. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15329. texture._MSAAFramebuffer = null;
  15330. }
  15331. if (texture._MSAARenderBuffer) {
  15332. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15333. texture._MSAARenderBuffer = null;
  15334. }
  15335. if (samples > 1) {
  15336. var framebuffer = gl.createFramebuffer();
  15337. if (!framebuffer) {
  15338. throw new Error("Unable to create multi sampled framebuffer");
  15339. }
  15340. texture._MSAAFramebuffer = framebuffer;
  15341. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15342. var colorRenderbuffer = gl.createRenderbuffer();
  15343. if (!colorRenderbuffer) {
  15344. throw new Error("Unable to create multi sampled framebuffer");
  15345. }
  15346. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15347. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15348. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15349. texture._MSAARenderBuffer = colorRenderbuffer;
  15350. }
  15351. else {
  15352. this.bindUnboundFramebuffer(texture._framebuffer);
  15353. }
  15354. texture.samples = samples;
  15355. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15356. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15357. this.bindUnboundFramebuffer(null);
  15358. return samples;
  15359. };
  15360. /**
  15361. * Update the sample count for a given multiple render target texture
  15362. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15363. * @param textures defines the textures to update
  15364. * @param samples defines the sample count to set
  15365. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15366. */
  15367. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15368. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15369. return 1;
  15370. }
  15371. if (textures[0].samples === samples) {
  15372. return samples;
  15373. }
  15374. var gl = this._gl;
  15375. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15376. // Dispose previous render buffers
  15377. if (textures[0]._depthStencilBuffer) {
  15378. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15379. textures[0]._depthStencilBuffer = null;
  15380. }
  15381. if (textures[0]._MSAAFramebuffer) {
  15382. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15383. textures[0]._MSAAFramebuffer = null;
  15384. }
  15385. for (var i = 0; i < textures.length; i++) {
  15386. if (textures[i]._MSAARenderBuffer) {
  15387. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15388. textures[i]._MSAARenderBuffer = null;
  15389. }
  15390. }
  15391. if (samples > 1) {
  15392. var framebuffer = gl.createFramebuffer();
  15393. if (!framebuffer) {
  15394. throw new Error("Unable to create multi sampled framebuffer");
  15395. }
  15396. this.bindUnboundFramebuffer(framebuffer);
  15397. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15398. var attachments = [];
  15399. for (var i = 0; i < textures.length; i++) {
  15400. var texture = textures[i];
  15401. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15402. var colorRenderbuffer = gl.createRenderbuffer();
  15403. if (!colorRenderbuffer) {
  15404. throw new Error("Unable to create multi sampled framebuffer");
  15405. }
  15406. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15407. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15408. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15409. texture._MSAAFramebuffer = framebuffer;
  15410. texture._MSAARenderBuffer = colorRenderbuffer;
  15411. texture.samples = samples;
  15412. texture._depthStencilBuffer = depthStencilBuffer;
  15413. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15414. attachments.push(attachment);
  15415. }
  15416. gl.drawBuffers(attachments);
  15417. }
  15418. else {
  15419. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15420. }
  15421. this.bindUnboundFramebuffer(null);
  15422. return samples;
  15423. };
  15424. /** @hidden */
  15425. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15426. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15427. };
  15428. /** @hidden */
  15429. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15430. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15431. };
  15432. /**
  15433. * Creates a new render target cube texture
  15434. * @param size defines the size of the texture
  15435. * @param options defines the options used to create the texture
  15436. * @returns a new render target cube texture stored in an InternalTexture
  15437. */
  15438. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15439. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15440. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15441. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15442. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15443. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15444. }
  15445. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15446. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15447. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15448. }
  15449. var gl = this._gl;
  15450. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15451. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15452. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15453. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15454. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15455. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15456. }
  15457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15461. for (var face = 0; face < 6; face++) {
  15462. 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);
  15463. }
  15464. // Create the framebuffer
  15465. var framebuffer = gl.createFramebuffer();
  15466. this.bindUnboundFramebuffer(framebuffer);
  15467. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15468. // MipMaps
  15469. if (fullOptions.generateMipMaps) {
  15470. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15471. }
  15472. // Unbind
  15473. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15474. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15475. this.bindUnboundFramebuffer(null);
  15476. texture._framebuffer = framebuffer;
  15477. texture.width = size;
  15478. texture.height = size;
  15479. texture.isReady = true;
  15480. texture.isCube = true;
  15481. texture.samples = 1;
  15482. texture.generateMipMaps = fullOptions.generateMipMaps;
  15483. texture.samplingMode = fullOptions.samplingMode;
  15484. texture.type = fullOptions.type;
  15485. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15486. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15487. this._internalTexturesCache.push(texture);
  15488. return texture;
  15489. };
  15490. /**
  15491. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15492. * @param rootUrl defines the url where the file to load is located
  15493. * @param scene defines the current scene
  15494. * @param scale defines scale to apply to the mip map selection
  15495. * @param offset defines offset to apply to the mip map selection
  15496. * @param onLoad defines an optional callback raised when the texture is loaded
  15497. * @param onError defines an optional callback raised if there is an issue to load the texture
  15498. * @param format defines the format of the data
  15499. * @param forcedExtension defines the extension to use to pick the right loader
  15500. * @returns the cube texture as an InternalTexture
  15501. */
  15502. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15503. var _this = this;
  15504. if (onLoad === void 0) { onLoad = null; }
  15505. if (onError === void 0) { onError = null; }
  15506. if (forcedExtension === void 0) { forcedExtension = null; }
  15507. var callback = function (loadData) {
  15508. if (!loadData) {
  15509. if (onLoad) {
  15510. onLoad(null);
  15511. }
  15512. return;
  15513. }
  15514. var texture = loadData.texture;
  15515. if (loadData.info.sphericalPolynomial) {
  15516. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15517. }
  15518. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15519. texture._lodGenerationScale = scale;
  15520. texture._lodGenerationOffset = offset;
  15521. if (_this._caps.textureLOD) {
  15522. // Do not add extra process if texture lod is supported.
  15523. if (onLoad) {
  15524. onLoad(texture);
  15525. }
  15526. return;
  15527. }
  15528. var mipSlices = 3;
  15529. var gl = _this._gl;
  15530. var width = loadData.width;
  15531. if (!width) {
  15532. return;
  15533. }
  15534. var textures = [];
  15535. for (var i = 0; i < mipSlices; i++) {
  15536. //compute LOD from even spacing in smoothness (matching shader calculation)
  15537. var smoothness = i / (mipSlices - 1);
  15538. var roughness = 1 - smoothness;
  15539. var minLODIndex = offset; // roughness = 0
  15540. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15541. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15542. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15543. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15544. glTextureFromLod.isCube = true;
  15545. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15550. if (loadData.isDDS) {
  15551. var info = loadData.info;
  15552. var data = loadData.data;
  15553. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15554. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15555. }
  15556. else {
  15557. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15558. }
  15559. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15560. // Wrap in a base texture for easy binding.
  15561. var lodTexture = new BABYLON.BaseTexture(scene);
  15562. lodTexture.isCube = true;
  15563. lodTexture._texture = glTextureFromLod;
  15564. glTextureFromLod.isReady = true;
  15565. textures.push(lodTexture);
  15566. }
  15567. texture._lodTextureHigh = textures[2];
  15568. texture._lodTextureMid = textures[1];
  15569. texture._lodTextureLow = textures[0];
  15570. if (onLoad) {
  15571. onLoad(texture);
  15572. }
  15573. };
  15574. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15575. };
  15576. /**
  15577. * Creates a cube texture
  15578. * @param rootUrl defines the url where the files to load is located
  15579. * @param scene defines the current scene
  15580. * @param files defines the list of files to load (1 per face)
  15581. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15582. * @param onLoad defines an optional callback raised when the texture is loaded
  15583. * @param onError defines an optional callback raised if there is an issue to load the texture
  15584. * @param format defines the format of the data
  15585. * @param forcedExtension defines the extension to use to pick the right loader
  15586. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15587. * @returns the cube texture as an InternalTexture
  15588. */
  15589. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15590. var _this = this;
  15591. if (onLoad === void 0) { onLoad = null; }
  15592. if (onError === void 0) { onError = null; }
  15593. if (forcedExtension === void 0) { forcedExtension = null; }
  15594. if (createPolynomials === void 0) { createPolynomials = false; }
  15595. var gl = this._gl;
  15596. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15597. texture.isCube = true;
  15598. texture.url = rootUrl;
  15599. texture.generateMipMaps = !noMipmap;
  15600. if (!this._doNotHandleContextLost) {
  15601. texture._extension = forcedExtension;
  15602. texture._files = files;
  15603. }
  15604. var isKTX = false;
  15605. var isDDS = false;
  15606. var lastDot = rootUrl.lastIndexOf('.');
  15607. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15608. if (this._textureFormatInUse) {
  15609. extension = this._textureFormatInUse;
  15610. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15611. isKTX = true;
  15612. }
  15613. else {
  15614. isDDS = (extension === ".dds");
  15615. }
  15616. var onerror = function (request, exception) {
  15617. if (onError && request) {
  15618. onError(request.status + " " + request.statusText, exception);
  15619. }
  15620. };
  15621. if (isKTX) {
  15622. this._loadFile(rootUrl, function (data) {
  15623. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15624. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15626. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15627. ktx.uploadLevels(_this._gl, !noMipmap);
  15628. _this.setCubeMapTextureParams(gl, loadMipmap);
  15629. texture.width = ktx.pixelWidth;
  15630. texture.height = ktx.pixelHeight;
  15631. texture.isReady = true;
  15632. }, undefined, undefined, true, onerror);
  15633. }
  15634. else if (isDDS) {
  15635. if (files && files.length === 6) {
  15636. this._cascadeLoadFiles(scene, function (imgs) {
  15637. var info;
  15638. var loadMipmap = false;
  15639. var width = 0;
  15640. for (var index = 0; index < imgs.length; index++) {
  15641. var data = imgs[index];
  15642. info = BABYLON.DDSTools.GetDDSInfo(data);
  15643. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15644. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15645. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15646. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15647. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15648. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15649. }
  15650. texture.width = info.width;
  15651. texture.height = info.height;
  15652. texture.type = info.textureType;
  15653. width = info.width;
  15654. }
  15655. _this.setCubeMapTextureParams(gl, loadMipmap);
  15656. texture.isReady = true;
  15657. if (onLoad) {
  15658. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15659. }
  15660. }, files, onError);
  15661. }
  15662. else {
  15663. this._loadFile(rootUrl, function (data) {
  15664. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15665. if (createPolynomials) {
  15666. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15667. }
  15668. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15669. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15670. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15671. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15672. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15673. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15674. }
  15675. _this.setCubeMapTextureParams(gl, loadMipmap);
  15676. texture.width = info.width;
  15677. texture.height = info.height;
  15678. texture.isReady = true;
  15679. texture.type = info.textureType;
  15680. if (onLoad) {
  15681. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15682. }
  15683. }, undefined, undefined, true, onerror);
  15684. }
  15685. }
  15686. else {
  15687. if (!files) {
  15688. throw new Error("Cannot load cubemap because files were not defined");
  15689. }
  15690. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15691. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15692. var height = width;
  15693. _this._prepareWorkingCanvas();
  15694. if (!_this._workingCanvas || !_this._workingContext) {
  15695. return;
  15696. }
  15697. _this._workingCanvas.width = width;
  15698. _this._workingCanvas.height = height;
  15699. var faces = [
  15700. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15701. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15702. ];
  15703. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15704. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15705. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15706. for (var index = 0; index < faces.length; index++) {
  15707. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15708. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15709. }
  15710. if (!noMipmap) {
  15711. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15712. }
  15713. _this.setCubeMapTextureParams(gl, !noMipmap);
  15714. texture.width = width;
  15715. texture.height = height;
  15716. texture.isReady = true;
  15717. if (format) {
  15718. texture.format = format;
  15719. }
  15720. texture.onLoadedObservable.notifyObservers(texture);
  15721. texture.onLoadedObservable.clear();
  15722. if (onLoad) {
  15723. onLoad();
  15724. }
  15725. }, files, onError);
  15726. }
  15727. this._internalTexturesCache.push(texture);
  15728. return texture;
  15729. };
  15730. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15735. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15736. // this.resetTextureCache();
  15737. };
  15738. /**
  15739. * Update a raw cube texture
  15740. * @param texture defines the texture to udpdate
  15741. * @param data defines the data to store
  15742. * @param format defines the data format
  15743. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15744. * @param invertY defines if data must be stored with Y axis inverted
  15745. * @param compression defines the compression used (null by default)
  15746. * @param level defines which level of the texture to update
  15747. */
  15748. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15749. if (compression === void 0) { compression = null; }
  15750. if (level === void 0) { level = 0; }
  15751. texture._bufferViewArray = data;
  15752. texture.format = format;
  15753. texture.type = type;
  15754. texture.invertY = invertY;
  15755. texture._compression = compression;
  15756. var gl = this._gl;
  15757. var textureType = this._getWebGLTextureType(type);
  15758. var internalFormat = this._getInternalFormat(format);
  15759. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15760. var needConversion = false;
  15761. if (internalFormat === gl.RGB) {
  15762. internalFormat = gl.RGBA;
  15763. needConversion = true;
  15764. }
  15765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15766. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15767. if (texture.width % 4 !== 0) {
  15768. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15769. }
  15770. // Data are known to be in +X +Y +Z -X -Y -Z
  15771. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15772. var faceData = data[faceIndex];
  15773. if (compression) {
  15774. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15775. }
  15776. else {
  15777. if (needConversion) {
  15778. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15779. }
  15780. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15781. }
  15782. }
  15783. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15784. if (isPot && texture.generateMipMaps && level === 0) {
  15785. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15786. }
  15787. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15788. // this.resetTextureCache();
  15789. texture.isReady = true;
  15790. };
  15791. /**
  15792. * Creates a new raw cube texture
  15793. * @param data defines the array of data to use to create each face
  15794. * @param size defines the size of the textures
  15795. * @param format defines the format of the data
  15796. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15797. * @param generateMipMaps defines if the engine should generate the mip levels
  15798. * @param invertY defines if data must be stored with Y axis inverted
  15799. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15800. * @param compression defines the compression used (null by default)
  15801. * @returns the cube texture as an InternalTexture
  15802. */
  15803. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15804. if (compression === void 0) { compression = null; }
  15805. var gl = this._gl;
  15806. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15807. texture.isCube = true;
  15808. texture.generateMipMaps = generateMipMaps;
  15809. texture.format = format;
  15810. texture.type = type;
  15811. if (!this._doNotHandleContextLost) {
  15812. texture._bufferViewArray = data;
  15813. }
  15814. var textureType = this._getWebGLTextureType(type);
  15815. var internalFormat = this._getInternalFormat(format);
  15816. if (internalFormat === gl.RGB) {
  15817. internalFormat = gl.RGBA;
  15818. }
  15819. var width = size;
  15820. var height = width;
  15821. texture.width = width;
  15822. texture.height = height;
  15823. // Double check on POT to generate Mips.
  15824. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15825. if (!isPot) {
  15826. generateMipMaps = false;
  15827. }
  15828. // Upload data if needed. The texture won't be ready until then.
  15829. if (data) {
  15830. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15831. }
  15832. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15833. // Filters
  15834. if (data && generateMipMaps) {
  15835. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15836. }
  15837. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15840. }
  15841. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15844. }
  15845. else {
  15846. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15849. }
  15850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15852. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15853. return texture;
  15854. };
  15855. /**
  15856. * Creates a new raw cube texture from a specified url
  15857. * @param url defines the url where the data is located
  15858. * @param scene defines the current scene
  15859. * @param size defines the size of the textures
  15860. * @param format defines the format of the data
  15861. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15862. * @param noMipmap defines if the engine should avoid generating the mip levels
  15863. * @param callback defines a callback used to extract texture data from loaded data
  15864. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15865. * @param onLoad defines a callback called when texture is loaded
  15866. * @param onError defines a callback called if there is an error
  15867. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15868. * @param invertY defines if data must be stored with Y axis inverted
  15869. * @returns the cube texture as an InternalTexture
  15870. */
  15871. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15872. var _this = this;
  15873. if (onLoad === void 0) { onLoad = null; }
  15874. if (onError === void 0) { onError = null; }
  15875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15876. if (invertY === void 0) { invertY = false; }
  15877. var gl = this._gl;
  15878. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15879. scene._addPendingData(texture);
  15880. texture.url = url;
  15881. this._internalTexturesCache.push(texture);
  15882. var onerror = function (request, exception) {
  15883. scene._removePendingData(texture);
  15884. if (onError && request) {
  15885. onError(request.status + " " + request.statusText, exception);
  15886. }
  15887. };
  15888. var internalCallback = function (data) {
  15889. var width = texture.width;
  15890. var faceDataArrays = callback(data);
  15891. if (!faceDataArrays) {
  15892. return;
  15893. }
  15894. if (mipmapGenerator) {
  15895. var textureType = _this._getWebGLTextureType(type);
  15896. var internalFormat = _this._getInternalFormat(format);
  15897. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15898. var needConversion = false;
  15899. if (internalFormat === gl.RGB) {
  15900. internalFormat = gl.RGBA;
  15901. needConversion = true;
  15902. }
  15903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15904. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15905. var mipData = mipmapGenerator(faceDataArrays);
  15906. for (var level = 0; level < mipData.length; level++) {
  15907. var mipSize = width >> level;
  15908. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15909. var mipFaceData = mipData[level][faceIndex];
  15910. if (needConversion) {
  15911. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15912. }
  15913. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15914. }
  15915. }
  15916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15917. }
  15918. else {
  15919. texture.generateMipMaps = !noMipmap;
  15920. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15921. }
  15922. texture.isReady = true;
  15923. // this.resetTextureCache();
  15924. scene._removePendingData(texture);
  15925. if (onLoad) {
  15926. onLoad();
  15927. }
  15928. };
  15929. this._loadFile(url, function (data) {
  15930. internalCallback(data);
  15931. }, undefined, scene.database, true, onerror);
  15932. return texture;
  15933. };
  15934. ;
  15935. /**
  15936. * Update a raw 3D texture
  15937. * @param texture defines the texture to update
  15938. * @param data defines the data to store
  15939. * @param format defines the data format
  15940. * @param invertY defines if data must be stored with Y axis inverted
  15941. * @param compression defines the used compression (can be null)
  15942. */
  15943. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15944. if (compression === void 0) { compression = null; }
  15945. var internalFormat = this._getInternalFormat(format);
  15946. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15947. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15948. if (!this._doNotHandleContextLost) {
  15949. texture._bufferView = data;
  15950. texture.format = format;
  15951. texture.invertY = invertY;
  15952. texture._compression = compression;
  15953. }
  15954. if (texture.width % 4 !== 0) {
  15955. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15956. }
  15957. if (compression && data) {
  15958. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15959. }
  15960. else {
  15961. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15962. }
  15963. if (texture.generateMipMaps) {
  15964. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15965. }
  15966. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15967. // this.resetTextureCache();
  15968. texture.isReady = true;
  15969. };
  15970. /**
  15971. * Creates a new raw 3D texture
  15972. * @param data defines the data used to create the texture
  15973. * @param width defines the width of the texture
  15974. * @param height defines the height of the texture
  15975. * @param depth defines the depth of the texture
  15976. * @param format defines the format of the texture
  15977. * @param generateMipMaps defines if the engine must generate mip levels
  15978. * @param invertY defines if data must be stored with Y axis inverted
  15979. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15980. * @param compression defines the compressed used (can be null)
  15981. * @returns a new raw 3D texture (stored in an InternalTexture)
  15982. */
  15983. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15984. if (compression === void 0) { compression = null; }
  15985. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15986. texture.baseWidth = width;
  15987. texture.baseHeight = height;
  15988. texture.baseDepth = depth;
  15989. texture.width = width;
  15990. texture.height = height;
  15991. texture.depth = depth;
  15992. texture.format = format;
  15993. texture.generateMipMaps = generateMipMaps;
  15994. texture.samplingMode = samplingMode;
  15995. texture.is3D = true;
  15996. if (!this._doNotHandleContextLost) {
  15997. texture._bufferView = data;
  15998. }
  15999. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16000. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16001. // Filters
  16002. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16003. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16004. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16005. if (generateMipMaps) {
  16006. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16007. }
  16008. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16009. this._internalTexturesCache.push(texture);
  16010. return texture;
  16011. };
  16012. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16013. var gl = this._gl;
  16014. if (!gl) {
  16015. return;
  16016. }
  16017. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16020. if (!noMipmap && !isCompressed) {
  16021. gl.generateMipmap(gl.TEXTURE_2D);
  16022. }
  16023. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16024. // this.resetTextureCache();
  16025. if (scene) {
  16026. scene._removePendingData(texture);
  16027. }
  16028. texture.onLoadedObservable.notifyObservers(texture);
  16029. texture.onLoadedObservable.clear();
  16030. };
  16031. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16032. var _this = this;
  16033. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16034. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16035. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16036. var gl = this._gl;
  16037. if (!gl) {
  16038. return;
  16039. }
  16040. if (!texture._webGLTexture) {
  16041. // this.resetTextureCache();
  16042. if (scene) {
  16043. scene._removePendingData(texture);
  16044. }
  16045. return;
  16046. }
  16047. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16048. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16049. texture.baseWidth = width;
  16050. texture.baseHeight = height;
  16051. texture.width = potWidth;
  16052. texture.height = potHeight;
  16053. texture.isReady = true;
  16054. if (processFunction(potWidth, potHeight, function () {
  16055. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16056. })) {
  16057. // Returning as texture needs extra async steps
  16058. return;
  16059. }
  16060. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16061. };
  16062. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16063. // Create new RGBA data container.
  16064. var rgbaData;
  16065. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16066. rgbaData = new Float32Array(width * height * 4);
  16067. }
  16068. else {
  16069. rgbaData = new Uint32Array(width * height * 4);
  16070. }
  16071. // Convert each pixel.
  16072. for (var x = 0; x < width; x++) {
  16073. for (var y = 0; y < height; y++) {
  16074. var index = (y * width + x) * 3;
  16075. var newIndex = (y * width + x) * 4;
  16076. // Map Old Value to new value.
  16077. rgbaData[newIndex + 0] = rgbData[index + 0];
  16078. rgbaData[newIndex + 1] = rgbData[index + 1];
  16079. rgbaData[newIndex + 2] = rgbData[index + 2];
  16080. // Add fully opaque alpha channel.
  16081. rgbaData[newIndex + 3] = 1;
  16082. }
  16083. }
  16084. return rgbaData;
  16085. };
  16086. /** @hidden */
  16087. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16088. var gl = this._gl;
  16089. if (texture._framebuffer) {
  16090. gl.deleteFramebuffer(texture._framebuffer);
  16091. texture._framebuffer = null;
  16092. }
  16093. if (texture._depthStencilBuffer) {
  16094. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16095. texture._depthStencilBuffer = null;
  16096. }
  16097. if (texture._MSAAFramebuffer) {
  16098. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16099. texture._MSAAFramebuffer = null;
  16100. }
  16101. if (texture._MSAARenderBuffer) {
  16102. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16103. texture._MSAARenderBuffer = null;
  16104. }
  16105. };
  16106. /** @hidden */
  16107. Engine.prototype._releaseTexture = function (texture) {
  16108. var gl = this._gl;
  16109. this._releaseFramebufferObjects(texture);
  16110. gl.deleteTexture(texture._webGLTexture);
  16111. // Unbind channels
  16112. this.unbindAllTextures();
  16113. var index = this._internalTexturesCache.indexOf(texture);
  16114. if (index !== -1) {
  16115. this._internalTexturesCache.splice(index, 1);
  16116. }
  16117. // Integrated fixed lod samplers.
  16118. if (texture._lodTextureHigh) {
  16119. texture._lodTextureHigh.dispose();
  16120. }
  16121. if (texture._lodTextureMid) {
  16122. texture._lodTextureMid.dispose();
  16123. }
  16124. if (texture._lodTextureLow) {
  16125. texture._lodTextureLow.dispose();
  16126. }
  16127. // Set output texture of post process to null if the texture has been released/disposed
  16128. this.scenes.forEach(function (scene) {
  16129. scene.postProcesses.forEach(function (postProcess) {
  16130. if (postProcess._outputTexture == texture) {
  16131. postProcess._outputTexture = null;
  16132. }
  16133. });
  16134. scene.cameras.forEach(function (camera) {
  16135. camera._postProcesses.forEach(function (postProcess) {
  16136. if (postProcess) {
  16137. if (postProcess._outputTexture == texture) {
  16138. postProcess._outputTexture = null;
  16139. }
  16140. }
  16141. });
  16142. });
  16143. });
  16144. };
  16145. Engine.prototype.setProgram = function (program) {
  16146. if (this._currentProgram !== program) {
  16147. this._gl.useProgram(program);
  16148. this._currentProgram = program;
  16149. }
  16150. };
  16151. /**
  16152. * Binds an effect to the webGL context
  16153. * @param effect defines the effect to bind
  16154. */
  16155. Engine.prototype.bindSamplers = function (effect) {
  16156. this.setProgram(effect.getProgram());
  16157. var samplers = effect.getSamplers();
  16158. for (var index = 0; index < samplers.length; index++) {
  16159. var uniform = effect.getUniform(samplers[index]);
  16160. if (uniform) {
  16161. this._boundUniforms[index] = uniform;
  16162. }
  16163. }
  16164. this._currentEffect = null;
  16165. };
  16166. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16167. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16168. return;
  16169. }
  16170. // Remove
  16171. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16172. // Bind last to it
  16173. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16174. // Bind to dummy
  16175. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16176. };
  16177. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16178. if (!internalTexture) {
  16179. return -1;
  16180. }
  16181. internalTexture._initialSlot = channel;
  16182. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16183. if (channel !== internalTexture._designatedSlot) {
  16184. this._textureCollisions.addCount(1, false);
  16185. }
  16186. }
  16187. else {
  16188. if (channel !== internalTexture._designatedSlot) {
  16189. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16190. return internalTexture._designatedSlot;
  16191. }
  16192. else {
  16193. // No slot for this texture, let's pick a new one (if we find a free slot)
  16194. if (this._nextFreeTextureSlots.length) {
  16195. return this._nextFreeTextureSlots[0];
  16196. }
  16197. // We need to recycle the oldest bound texture, sorry.
  16198. this._textureCollisions.addCount(1, false);
  16199. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16200. }
  16201. }
  16202. }
  16203. return channel;
  16204. };
  16205. Engine.prototype._linkTrackers = function (previous, next) {
  16206. previous.next = next;
  16207. next.previous = previous;
  16208. };
  16209. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16210. var currentSlot = internalTexture._designatedSlot;
  16211. if (currentSlot === -1) {
  16212. return -1;
  16213. }
  16214. internalTexture._designatedSlot = -1;
  16215. if (this.disableTextureBindingOptimization) {
  16216. return -1;
  16217. }
  16218. // Remove from bound list
  16219. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16220. // Free the slot
  16221. this._boundTexturesCache[currentSlot] = null;
  16222. this._nextFreeTextureSlots.push(currentSlot);
  16223. return currentSlot;
  16224. };
  16225. Engine.prototype._activateCurrentTexture = function () {
  16226. if (this._currentTextureChannel !== this._activeChannel) {
  16227. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16228. this._currentTextureChannel = this._activeChannel;
  16229. }
  16230. };
  16231. /** @hidden */
  16232. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16233. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16234. if (force === void 0) { force = false; }
  16235. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16236. this._activeChannel = texture._designatedSlot;
  16237. }
  16238. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16239. var isTextureForRendering = texture && texture._initialSlot > -1;
  16240. if (currentTextureBound !== texture || force) {
  16241. if (currentTextureBound) {
  16242. this._removeDesignatedSlot(currentTextureBound);
  16243. }
  16244. this._activateCurrentTexture();
  16245. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16246. this._boundTexturesCache[this._activeChannel] = texture;
  16247. if (texture) {
  16248. if (!this.disableTextureBindingOptimization) {
  16249. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16250. if (slotIndex > -1) {
  16251. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16252. }
  16253. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16254. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16255. }
  16256. texture._designatedSlot = this._activeChannel;
  16257. }
  16258. }
  16259. else if (forTextureDataUpdate) {
  16260. this._activateCurrentTexture();
  16261. }
  16262. if (isTextureForRendering && !forTextureDataUpdate) {
  16263. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16264. }
  16265. };
  16266. /** @hidden */
  16267. Engine.prototype._bindTexture = function (channel, texture) {
  16268. if (channel < 0) {
  16269. return;
  16270. }
  16271. if (texture) {
  16272. channel = this._getCorrectTextureChannel(channel, texture);
  16273. }
  16274. this._activeChannel = channel;
  16275. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16276. };
  16277. /**
  16278. * Sets a texture to the webGL context from a postprocess
  16279. * @param channel defines the channel to use
  16280. * @param postProcess defines the source postprocess
  16281. */
  16282. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16283. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16284. };
  16285. /**
  16286. * Binds the output of the passed in post process to the texture channel specified
  16287. * @param channel The channel the texture should be bound to
  16288. * @param postProcess The post process which's output should be bound
  16289. */
  16290. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16291. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16292. };
  16293. /**
  16294. * Unbind all textures from the webGL context
  16295. */
  16296. Engine.prototype.unbindAllTextures = function () {
  16297. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16298. this._activeChannel = channel;
  16299. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16300. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16301. if (this.webGLVersion > 1) {
  16302. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16303. }
  16304. }
  16305. };
  16306. /**
  16307. * Sets a texture to the according uniform.
  16308. * @param channel The texture channel
  16309. * @param uniform The uniform to set
  16310. * @param texture The texture to apply
  16311. */
  16312. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16313. if (channel < 0) {
  16314. return;
  16315. }
  16316. if (uniform) {
  16317. this._boundUniforms[channel] = uniform;
  16318. }
  16319. this._setTexture(channel, texture);
  16320. };
  16321. /**
  16322. * Sets a depth stencil texture from a render target to the according uniform.
  16323. * @param channel The texture channel
  16324. * @param uniform The uniform to set
  16325. * @param texture The render target texture containing the depth stencil texture to apply
  16326. */
  16327. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16328. if (channel < 0) {
  16329. return;
  16330. }
  16331. if (uniform) {
  16332. this._boundUniforms[channel] = uniform;
  16333. }
  16334. if (!texture || !texture.depthStencilTexture) {
  16335. this._setTexture(channel, null);
  16336. }
  16337. else {
  16338. this._setTexture(channel, texture, false, true);
  16339. }
  16340. };
  16341. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16342. var uniform = this._boundUniforms[sourceSlot];
  16343. if (uniform._currentState === destination) {
  16344. return;
  16345. }
  16346. this._gl.uniform1i(uniform, destination);
  16347. uniform._currentState = destination;
  16348. };
  16349. Engine.prototype._getTextureWrapMode = function (mode) {
  16350. switch (mode) {
  16351. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16352. return this._gl.REPEAT;
  16353. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16354. return this._gl.CLAMP_TO_EDGE;
  16355. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16356. return this._gl.MIRRORED_REPEAT;
  16357. }
  16358. return this._gl.REPEAT;
  16359. };
  16360. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16361. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16362. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16363. // Not ready?
  16364. if (!texture) {
  16365. if (this._boundTexturesCache[channel] != null) {
  16366. this._activeChannel = channel;
  16367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16368. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16369. if (this.webGLVersion > 1) {
  16370. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16371. }
  16372. }
  16373. return false;
  16374. }
  16375. // Video
  16376. if (texture.video) {
  16377. this._activeChannel = channel;
  16378. texture.update();
  16379. }
  16380. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16381. texture.delayLoad();
  16382. return false;
  16383. }
  16384. var internalTexture;
  16385. if (depthStencilTexture) {
  16386. internalTexture = texture.depthStencilTexture;
  16387. }
  16388. else if (texture.isReady()) {
  16389. internalTexture = texture.getInternalTexture();
  16390. }
  16391. else if (texture.isCube) {
  16392. internalTexture = this.emptyCubeTexture;
  16393. }
  16394. else if (texture.is3D) {
  16395. internalTexture = this.emptyTexture3D;
  16396. }
  16397. else {
  16398. internalTexture = this.emptyTexture;
  16399. }
  16400. if (!isPartOfTextureArray) {
  16401. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16402. }
  16403. var needToBind = true;
  16404. if (this._boundTexturesCache[channel] === internalTexture) {
  16405. this._moveBoundTextureOnTop(internalTexture);
  16406. if (!isPartOfTextureArray) {
  16407. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16408. }
  16409. needToBind = false;
  16410. }
  16411. this._activeChannel = channel;
  16412. if (internalTexture && internalTexture.is3D) {
  16413. if (needToBind) {
  16414. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16417. internalTexture._cachedWrapU = texture.wrapU;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16419. }
  16420. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16421. internalTexture._cachedWrapV = texture.wrapV;
  16422. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16423. }
  16424. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16425. internalTexture._cachedWrapR = texture.wrapR;
  16426. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16427. }
  16428. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16429. }
  16430. else if (internalTexture && internalTexture.isCube) {
  16431. if (needToBind) {
  16432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16433. }
  16434. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16435. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16436. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16437. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16439. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16440. }
  16441. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16442. }
  16443. else {
  16444. if (needToBind) {
  16445. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16446. }
  16447. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16448. internalTexture._cachedWrapU = texture.wrapU;
  16449. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16450. }
  16451. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16452. internalTexture._cachedWrapV = texture.wrapV;
  16453. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16454. }
  16455. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16456. }
  16457. return true;
  16458. };
  16459. /**
  16460. * Sets an array of texture to the webGL context
  16461. * @param channel defines the channel where the texture array must be set
  16462. * @param uniform defines the associated uniform location
  16463. * @param textures defines the array of textures to bind
  16464. */
  16465. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16466. if (channel < 0 || !uniform) {
  16467. return;
  16468. }
  16469. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16470. this._textureUnits = new Int32Array(textures.length);
  16471. }
  16472. for (var i = 0; i < textures.length; i++) {
  16473. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16474. }
  16475. this._gl.uniform1iv(uniform, this._textureUnits);
  16476. for (var index = 0; index < textures.length; index++) {
  16477. this._setTexture(this._textureUnits[index], textures[index], true);
  16478. }
  16479. };
  16480. /** @hidden */
  16481. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16482. var internalTexture = texture.getInternalTexture();
  16483. if (!internalTexture) {
  16484. return;
  16485. }
  16486. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16487. var value = texture.anisotropicFilteringLevel;
  16488. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16489. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16490. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16491. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16492. }
  16493. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16494. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16495. internalTexture._cachedAnisotropicFilteringLevel = value;
  16496. }
  16497. };
  16498. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16499. this._bindTextureDirectly(target, texture, true, true);
  16500. this._gl.texParameterf(target, parameter, value);
  16501. };
  16502. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16503. if (texture) {
  16504. this._bindTextureDirectly(target, texture, true, true);
  16505. }
  16506. this._gl.texParameteri(target, parameter, value);
  16507. };
  16508. /**
  16509. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16510. * @param x defines the x coordinate of the rectangle where pixels must be read
  16511. * @param y defines the y coordinate of the rectangle where pixels must be read
  16512. * @param width defines the width of the rectangle where pixels must be read
  16513. * @param height defines the height of the rectangle where pixels must be read
  16514. * @returns a Uint8Array containing RGBA colors
  16515. */
  16516. Engine.prototype.readPixels = function (x, y, width, height) {
  16517. var data = new Uint8Array(height * width * 4);
  16518. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16519. return data;
  16520. };
  16521. /**
  16522. * Add an externaly attached data from its key.
  16523. * This method call will fail and return false, if such key already exists.
  16524. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16525. * @param key the unique key that identifies the data
  16526. * @param data the data object to associate to the key for this Engine instance
  16527. * @return true if no such key were already present and the data was added successfully, false otherwise
  16528. */
  16529. Engine.prototype.addExternalData = function (key, data) {
  16530. if (!this._externalData) {
  16531. this._externalData = new BABYLON.StringDictionary();
  16532. }
  16533. return this._externalData.add(key, data);
  16534. };
  16535. /**
  16536. * Get an externaly attached data from its key
  16537. * @param key the unique key that identifies the data
  16538. * @return the associated data, if present (can be null), or undefined if not present
  16539. */
  16540. Engine.prototype.getExternalData = function (key) {
  16541. if (!this._externalData) {
  16542. this._externalData = new BABYLON.StringDictionary();
  16543. }
  16544. return this._externalData.get(key);
  16545. };
  16546. /**
  16547. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16548. * @param key the unique key that identifies the data
  16549. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16550. * @return the associated data, can be null if the factory returned null.
  16551. */
  16552. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16553. if (!this._externalData) {
  16554. this._externalData = new BABYLON.StringDictionary();
  16555. }
  16556. return this._externalData.getOrAddWithFactory(key, factory);
  16557. };
  16558. /**
  16559. * Remove an externaly attached data from the Engine instance
  16560. * @param key the unique key that identifies the data
  16561. * @return true if the data was successfully removed, false if it doesn't exist
  16562. */
  16563. Engine.prototype.removeExternalData = function (key) {
  16564. if (!this._externalData) {
  16565. this._externalData = new BABYLON.StringDictionary();
  16566. }
  16567. return this._externalData.remove(key);
  16568. };
  16569. /**
  16570. * Unbind all vertex attributes from the webGL context
  16571. */
  16572. Engine.prototype.unbindAllAttributes = function () {
  16573. if (this._mustWipeVertexAttributes) {
  16574. this._mustWipeVertexAttributes = false;
  16575. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16576. this._gl.disableVertexAttribArray(i);
  16577. this._vertexAttribArraysEnabled[i] = false;
  16578. this._currentBufferPointers[i].active = false;
  16579. }
  16580. return;
  16581. }
  16582. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16583. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16584. continue;
  16585. }
  16586. this._gl.disableVertexAttribArray(i);
  16587. this._vertexAttribArraysEnabled[i] = false;
  16588. this._currentBufferPointers[i].active = false;
  16589. }
  16590. };
  16591. /**
  16592. * 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
  16593. */
  16594. Engine.prototype.releaseEffects = function () {
  16595. for (var name in this._compiledEffects) {
  16596. this._deleteProgram(this._compiledEffects[name]._program);
  16597. }
  16598. this._compiledEffects = {};
  16599. };
  16600. /**
  16601. * Dispose and release all associated resources
  16602. */
  16603. Engine.prototype.dispose = function () {
  16604. this.hideLoadingUI();
  16605. this.stopRenderLoop();
  16606. // Release postProcesses
  16607. while (this.postProcesses.length) {
  16608. this.postProcesses[0].dispose();
  16609. }
  16610. // Empty texture
  16611. if (this._emptyTexture) {
  16612. this._releaseTexture(this._emptyTexture);
  16613. this._emptyTexture = null;
  16614. }
  16615. if (this._emptyCubeTexture) {
  16616. this._releaseTexture(this._emptyCubeTexture);
  16617. this._emptyCubeTexture = null;
  16618. }
  16619. // Rescale PP
  16620. if (this._rescalePostProcess) {
  16621. this._rescalePostProcess.dispose();
  16622. }
  16623. // Release scenes
  16624. while (this.scenes.length) {
  16625. this.scenes[0].dispose();
  16626. }
  16627. // Release audio engine
  16628. if (Engine.audioEngine) {
  16629. Engine.audioEngine.dispose();
  16630. }
  16631. // Release effects
  16632. this.releaseEffects();
  16633. // Unbind
  16634. this.unbindAllAttributes();
  16635. this._boundUniforms = [];
  16636. if (this._dummyFramebuffer) {
  16637. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16638. }
  16639. //WebVR
  16640. this.disableVR();
  16641. // Events
  16642. if (BABYLON.Tools.IsWindowObjectExist()) {
  16643. window.removeEventListener("blur", this._onBlur);
  16644. window.removeEventListener("focus", this._onFocus);
  16645. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16646. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16647. if (this._renderingCanvas) {
  16648. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16649. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16650. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16651. if (!this._doNotHandleContextLost) {
  16652. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16653. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16654. }
  16655. }
  16656. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16657. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16658. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16659. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16660. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16661. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16662. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16663. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16664. if (this._onVrDisplayConnect) {
  16665. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16666. if (this._onVrDisplayDisconnect) {
  16667. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16668. }
  16669. if (this._onVrDisplayPresentChange) {
  16670. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16671. }
  16672. this._onVrDisplayConnect = null;
  16673. this._onVrDisplayDisconnect = null;
  16674. }
  16675. }
  16676. // Remove from Instances
  16677. var index = Engine.Instances.indexOf(this);
  16678. if (index >= 0) {
  16679. Engine.Instances.splice(index, 1);
  16680. }
  16681. this._workingCanvas = null;
  16682. this._workingContext = null;
  16683. this._currentBufferPointers = [];
  16684. this._renderingCanvas = null;
  16685. this._currentProgram = null;
  16686. this._bindedRenderFunction = null;
  16687. this.onResizeObservable.clear();
  16688. this.onCanvasBlurObservable.clear();
  16689. this.onCanvasFocusObservable.clear();
  16690. this.onCanvasPointerOutObservable.clear();
  16691. this.onBeginFrameObservable.clear();
  16692. this.onEndFrameObservable.clear();
  16693. BABYLON.Effect.ResetCache();
  16694. // Abort active requests
  16695. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16696. var request = _a[_i];
  16697. request.abort();
  16698. }
  16699. };
  16700. // Loading screen
  16701. /**
  16702. * Display the loading screen
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. Engine.prototype.displayLoadingUI = function () {
  16706. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16707. return;
  16708. }
  16709. var loadingScreen = this.loadingScreen;
  16710. if (loadingScreen) {
  16711. loadingScreen.displayLoadingUI();
  16712. }
  16713. };
  16714. /**
  16715. * Hide the loading screen
  16716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16717. */
  16718. Engine.prototype.hideLoadingUI = function () {
  16719. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16720. return;
  16721. }
  16722. var loadingScreen = this.loadingScreen;
  16723. if (loadingScreen) {
  16724. loadingScreen.hideLoadingUI();
  16725. }
  16726. };
  16727. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16728. /**
  16729. * Gets the current loading screen object
  16730. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16731. */
  16732. get: function () {
  16733. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16734. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16735. return this._loadingScreen;
  16736. },
  16737. /**
  16738. * Sets the current loading screen object
  16739. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16740. */
  16741. set: function (loadingScreen) {
  16742. this._loadingScreen = loadingScreen;
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16748. /**
  16749. * Sets the current loading screen text
  16750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16751. */
  16752. set: function (text) {
  16753. this.loadingScreen.loadingUIText = text;
  16754. },
  16755. enumerable: true,
  16756. configurable: true
  16757. });
  16758. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16759. /**
  16760. * Sets the current loading screen background color
  16761. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16762. */
  16763. set: function (color) {
  16764. this.loadingScreen.loadingUIBackgroundColor = color;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. /**
  16770. * Attach a new callback raised when context lost event is fired
  16771. * @param callback defines the callback to call
  16772. */
  16773. Engine.prototype.attachContextLostEvent = function (callback) {
  16774. if (this._renderingCanvas) {
  16775. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16776. }
  16777. };
  16778. /**
  16779. * Attach a new callback raised when context restored event is fired
  16780. * @param callback defines the callback to call
  16781. */
  16782. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16783. if (this._renderingCanvas) {
  16784. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16785. }
  16786. };
  16787. /**
  16788. * Gets the source code of the vertex shader associated with a specific webGL program
  16789. * @param program defines the program to use
  16790. * @returns a string containing the source code of the vertex shader associated with the program
  16791. */
  16792. Engine.prototype.getVertexShaderSource = function (program) {
  16793. var shaders = this._gl.getAttachedShaders(program);
  16794. if (!shaders) {
  16795. return null;
  16796. }
  16797. return this._gl.getShaderSource(shaders[0]);
  16798. };
  16799. /**
  16800. * Gets the source code of the fragment shader associated with a specific webGL program
  16801. * @param program defines the program to use
  16802. * @returns a string containing the source code of the fragment shader associated with the program
  16803. */
  16804. Engine.prototype.getFragmentShaderSource = function (program) {
  16805. var shaders = this._gl.getAttachedShaders(program);
  16806. if (!shaders) {
  16807. return null;
  16808. }
  16809. return this._gl.getShaderSource(shaders[1]);
  16810. };
  16811. /**
  16812. * Get the current error code of the webGL context
  16813. * @returns the error code
  16814. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16815. */
  16816. Engine.prototype.getError = function () {
  16817. return this._gl.getError();
  16818. };
  16819. // FPS
  16820. /**
  16821. * Gets the current framerate
  16822. * @returns a number representing the framerate
  16823. */
  16824. Engine.prototype.getFps = function () {
  16825. return this._fps;
  16826. };
  16827. /**
  16828. * Gets the time spent between current and previous frame
  16829. * @returns a number representing the delta time in ms
  16830. */
  16831. Engine.prototype.getDeltaTime = function () {
  16832. return this._deltaTime;
  16833. };
  16834. Engine.prototype._measureFps = function () {
  16835. this._performanceMonitor.sampleFrame();
  16836. this._fps = this._performanceMonitor.averageFPS;
  16837. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16838. };
  16839. /** @hidden */
  16840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16841. if (faceIndex === void 0) { faceIndex = -1; }
  16842. var gl = this._gl;
  16843. if (!this._dummyFramebuffer) {
  16844. var dummy = gl.createFramebuffer();
  16845. if (!dummy) {
  16846. throw new Error("Unable to create dummy framebuffer");
  16847. }
  16848. this._dummyFramebuffer = dummy;
  16849. }
  16850. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16851. if (faceIndex > -1) {
  16852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16853. }
  16854. else {
  16855. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16856. }
  16857. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16858. var buffer;
  16859. switch (readType) {
  16860. case gl.UNSIGNED_BYTE:
  16861. buffer = new Uint8Array(4 * width * height);
  16862. readType = gl.UNSIGNED_BYTE;
  16863. break;
  16864. default:
  16865. buffer = new Float32Array(4 * width * height);
  16866. readType = gl.FLOAT;
  16867. break;
  16868. }
  16869. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16871. return buffer;
  16872. };
  16873. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16874. if (this._webGLVersion > 1) {
  16875. return this._caps.colorBufferFloat;
  16876. }
  16877. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16878. };
  16879. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16880. if (this._webGLVersion > 1) {
  16881. return this._caps.colorBufferFloat;
  16882. }
  16883. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16884. };
  16885. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16886. Engine.prototype._canRenderToFramebuffer = function (type) {
  16887. var gl = this._gl;
  16888. //clear existing errors
  16889. while (gl.getError() !== gl.NO_ERROR) { }
  16890. var successful = true;
  16891. var texture = gl.createTexture();
  16892. gl.bindTexture(gl.TEXTURE_2D, texture);
  16893. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16896. var fb = gl.createFramebuffer();
  16897. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16899. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16900. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16901. successful = successful && (gl.getError() === gl.NO_ERROR);
  16902. //try render by clearing frame buffer's color buffer
  16903. if (successful) {
  16904. gl.clear(gl.COLOR_BUFFER_BIT);
  16905. successful = successful && (gl.getError() === gl.NO_ERROR);
  16906. }
  16907. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16908. if (successful) {
  16909. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16911. var readFormat = gl.RGBA;
  16912. var readType = gl.UNSIGNED_BYTE;
  16913. var buffer = new Uint8Array(4);
  16914. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16915. successful = successful && (gl.getError() === gl.NO_ERROR);
  16916. }
  16917. //clean up
  16918. gl.deleteTexture(texture);
  16919. gl.deleteFramebuffer(fb);
  16920. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16921. //clear accumulated errors
  16922. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16923. return successful;
  16924. };
  16925. /** @hidden */
  16926. Engine.prototype._getWebGLTextureType = function (type) {
  16927. if (type === Engine.TEXTURETYPE_FLOAT) {
  16928. return this._gl.FLOAT;
  16929. }
  16930. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16931. // Add Half Float Constant.
  16932. return this._gl.HALF_FLOAT_OES;
  16933. }
  16934. return this._gl.UNSIGNED_BYTE;
  16935. };
  16936. ;
  16937. Engine.prototype._getInternalFormat = function (format) {
  16938. var internalFormat = this._gl.RGBA;
  16939. switch (format) {
  16940. case Engine.TEXTUREFORMAT_ALPHA:
  16941. internalFormat = this._gl.ALPHA;
  16942. break;
  16943. case Engine.TEXTUREFORMAT_LUMINANCE:
  16944. internalFormat = this._gl.LUMINANCE;
  16945. break;
  16946. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16947. internalFormat = this._gl.LUMINANCE_ALPHA;
  16948. break;
  16949. case Engine.TEXTUREFORMAT_RGB:
  16950. case Engine.TEXTUREFORMAT_RGB32F:
  16951. internalFormat = this._gl.RGB;
  16952. break;
  16953. case Engine.TEXTUREFORMAT_RGBA:
  16954. case Engine.TEXTUREFORMAT_RGBA32F:
  16955. internalFormat = this._gl.RGBA;
  16956. break;
  16957. case Engine.TEXTUREFORMAT_R32F:
  16958. internalFormat = this._gl.RED;
  16959. break;
  16960. case Engine.TEXTUREFORMAT_RG32F:
  16961. internalFormat = this._gl.RG;
  16962. break;
  16963. }
  16964. return internalFormat;
  16965. };
  16966. /** @hidden */
  16967. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16968. if (this._webGLVersion === 1) {
  16969. if (format) {
  16970. switch (format) {
  16971. case Engine.TEXTUREFORMAT_LUMINANCE:
  16972. return this._gl.LUMINANCE;
  16973. }
  16974. }
  16975. return this._gl.RGBA;
  16976. }
  16977. if (type === Engine.TEXTURETYPE_FLOAT) {
  16978. if (format) {
  16979. switch (format) {
  16980. case Engine.TEXTUREFORMAT_R32F:
  16981. return this._gl.R32F;
  16982. case Engine.TEXTUREFORMAT_RG32F:
  16983. return this._gl.RG32F;
  16984. case Engine.TEXTUREFORMAT_RGB32F:
  16985. return this._gl.RGB32F;
  16986. }
  16987. }
  16988. return this._gl.RGBA32F;
  16989. }
  16990. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16991. return this._gl.RGBA16F;
  16992. }
  16993. if (format) {
  16994. switch (format) {
  16995. case Engine.TEXTUREFORMAT_LUMINANCE:
  16996. return this._gl.LUMINANCE;
  16997. case Engine.TEXTUREFORMAT_RGB:
  16998. return this._gl.RGB;
  16999. }
  17000. }
  17001. return this._gl.RGBA;
  17002. };
  17003. ;
  17004. /** @hidden */
  17005. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17006. if (type === Engine.TEXTURETYPE_FLOAT) {
  17007. return this._gl.RGBA32F;
  17008. }
  17009. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17010. return this._gl.RGBA16F;
  17011. }
  17012. return this._gl.RGBA8;
  17013. };
  17014. ;
  17015. /**
  17016. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17017. * @return the new query
  17018. */
  17019. Engine.prototype.createQuery = function () {
  17020. return this._gl.createQuery();
  17021. };
  17022. /**
  17023. * Delete and release a webGL query
  17024. * @param query defines the query to delete
  17025. * @return the current engine
  17026. */
  17027. Engine.prototype.deleteQuery = function (query) {
  17028. this._gl.deleteQuery(query);
  17029. return this;
  17030. };
  17031. /**
  17032. * Check if a given query has resolved and got its value
  17033. * @param query defines the query to check
  17034. * @returns true if the query got its value
  17035. */
  17036. Engine.prototype.isQueryResultAvailable = function (query) {
  17037. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17038. };
  17039. /**
  17040. * Gets the value of a given query
  17041. * @param query defines the query to check
  17042. * @returns the value of the query
  17043. */
  17044. Engine.prototype.getQueryResult = function (query) {
  17045. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17046. };
  17047. /**
  17048. * Initiates an occlusion query
  17049. * @param algorithmType defines the algorithm to use
  17050. * @param query defines the query to use
  17051. * @returns the current engine
  17052. * @see http://doc.babylonjs.com/features/occlusionquery
  17053. */
  17054. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17055. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17056. this._gl.beginQuery(glAlgorithm, query);
  17057. return this;
  17058. };
  17059. /**
  17060. * Ends an occlusion query
  17061. * @see http://doc.babylonjs.com/features/occlusionquery
  17062. * @param algorithmType defines the algorithm to use
  17063. * @returns the current engine
  17064. */
  17065. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17066. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17067. this._gl.endQuery(glAlgorithm);
  17068. return this;
  17069. };
  17070. /* Time queries */
  17071. Engine.prototype._createTimeQuery = function () {
  17072. var timerQuery = this._caps.timerQuery;
  17073. if (timerQuery.createQueryEXT) {
  17074. return timerQuery.createQueryEXT();
  17075. }
  17076. return this.createQuery();
  17077. };
  17078. Engine.prototype._deleteTimeQuery = function (query) {
  17079. var timerQuery = this._caps.timerQuery;
  17080. if (timerQuery.deleteQueryEXT) {
  17081. timerQuery.deleteQueryEXT(query);
  17082. return;
  17083. }
  17084. this.deleteQuery(query);
  17085. };
  17086. Engine.prototype._getTimeQueryResult = function (query) {
  17087. var timerQuery = this._caps.timerQuery;
  17088. if (timerQuery.getQueryObjectEXT) {
  17089. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17090. }
  17091. return this.getQueryResult(query);
  17092. };
  17093. Engine.prototype._getTimeQueryAvailability = function (query) {
  17094. var timerQuery = this._caps.timerQuery;
  17095. if (timerQuery.getQueryObjectEXT) {
  17096. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17097. }
  17098. return this.isQueryResultAvailable(query);
  17099. };
  17100. /**
  17101. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17102. * Please note that only one query can be issued at a time
  17103. * @returns a time token used to track the time span
  17104. */
  17105. Engine.prototype.startTimeQuery = function () {
  17106. var timerQuery = this._caps.timerQuery;
  17107. if (!timerQuery) {
  17108. return null;
  17109. }
  17110. var token = new BABYLON._TimeToken();
  17111. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17112. if (this._caps.canUseTimestampForTimerQuery) {
  17113. token._startTimeQuery = this._createTimeQuery();
  17114. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17115. }
  17116. else {
  17117. if (this._currentNonTimestampToken) {
  17118. return this._currentNonTimestampToken;
  17119. }
  17120. token._timeElapsedQuery = this._createTimeQuery();
  17121. if (timerQuery.beginQueryEXT) {
  17122. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17123. }
  17124. else {
  17125. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17126. }
  17127. this._currentNonTimestampToken = token;
  17128. }
  17129. return token;
  17130. };
  17131. /**
  17132. * Ends a time query
  17133. * @param token defines the token used to measure the time span
  17134. * @returns the time spent (in ns)
  17135. */
  17136. Engine.prototype.endTimeQuery = function (token) {
  17137. var timerQuery = this._caps.timerQuery;
  17138. if (!timerQuery || !token) {
  17139. return -1;
  17140. }
  17141. if (this._caps.canUseTimestampForTimerQuery) {
  17142. if (!token._startTimeQuery) {
  17143. return -1;
  17144. }
  17145. if (!token._endTimeQuery) {
  17146. token._endTimeQuery = this._createTimeQuery();
  17147. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17148. }
  17149. }
  17150. else if (!token._timeElapsedQueryEnded) {
  17151. if (!token._timeElapsedQuery) {
  17152. return -1;
  17153. }
  17154. if (timerQuery.endQueryEXT) {
  17155. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17156. }
  17157. else {
  17158. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17159. }
  17160. token._timeElapsedQueryEnded = true;
  17161. }
  17162. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17163. var available = false;
  17164. if (token._endTimeQuery) {
  17165. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17166. }
  17167. else if (token._timeElapsedQuery) {
  17168. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17169. }
  17170. if (available && !disjoint) {
  17171. var result = 0;
  17172. if (this._caps.canUseTimestampForTimerQuery) {
  17173. if (!token._startTimeQuery || !token._endTimeQuery) {
  17174. return -1;
  17175. }
  17176. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17177. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17178. result = timeEnd - timeStart;
  17179. this._deleteTimeQuery(token._startTimeQuery);
  17180. this._deleteTimeQuery(token._endTimeQuery);
  17181. token._startTimeQuery = null;
  17182. token._endTimeQuery = null;
  17183. }
  17184. else {
  17185. if (!token._timeElapsedQuery) {
  17186. return -1;
  17187. }
  17188. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17189. this._deleteTimeQuery(token._timeElapsedQuery);
  17190. token._timeElapsedQuery = null;
  17191. token._timeElapsedQueryEnded = false;
  17192. this._currentNonTimestampToken = null;
  17193. }
  17194. return result;
  17195. }
  17196. return -1;
  17197. };
  17198. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17199. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17200. };
  17201. // Transform feedback
  17202. /**
  17203. * Creates a webGL transform feedback object
  17204. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17205. * @returns the webGL transform feedback object
  17206. */
  17207. Engine.prototype.createTransformFeedback = function () {
  17208. return this._gl.createTransformFeedback();
  17209. };
  17210. /**
  17211. * Delete a webGL transform feedback object
  17212. * @param value defines the webGL transform feedback object to delete
  17213. */
  17214. Engine.prototype.deleteTransformFeedback = function (value) {
  17215. this._gl.deleteTransformFeedback(value);
  17216. };
  17217. /**
  17218. * Bind a webGL transform feedback object to the webgl context
  17219. * @param value defines the webGL transform feedback object to bind
  17220. */
  17221. Engine.prototype.bindTransformFeedback = function (value) {
  17222. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17223. };
  17224. /**
  17225. * Begins a transform feedback operation
  17226. * @param usePoints defines if points or triangles must be used
  17227. */
  17228. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17229. if (usePoints === void 0) { usePoints = true; }
  17230. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17231. };
  17232. /**
  17233. * Ends a transform feedback operation
  17234. */
  17235. Engine.prototype.endTransformFeedback = function () {
  17236. this._gl.endTransformFeedback();
  17237. };
  17238. /**
  17239. * Specify the varyings to use with transform feedback
  17240. * @param program defines the associated webGL program
  17241. * @param value defines the list of strings representing the varying names
  17242. */
  17243. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17244. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17245. };
  17246. /**
  17247. * Bind a webGL buffer for a transform feedback operation
  17248. * @param value defines the webGL buffer to bind
  17249. */
  17250. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17251. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17252. };
  17253. /** @hidden */
  17254. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17255. var _this = this;
  17256. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17257. this._activeRequests.push(request);
  17258. request.onCompleteObservable.add(function (request) {
  17259. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17260. });
  17261. return request;
  17262. };
  17263. /** @hidden */
  17264. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17265. var _this = this;
  17266. return new Promise(function (resolve, reject) {
  17267. _this._loadFile(url, function (data) {
  17268. resolve(data);
  17269. }, undefined, database, useArrayBuffer, function (request, exception) {
  17270. reject(exception);
  17271. });
  17272. });
  17273. };
  17274. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17275. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17276. var onload = function (data) {
  17277. loadedFiles[index] = data;
  17278. loadedFiles._internalCount++;
  17279. if (loadedFiles._internalCount === 6) {
  17280. onfinish(loadedFiles);
  17281. }
  17282. };
  17283. var onerror = function (request, exception) {
  17284. if (onErrorCallBack && request) {
  17285. onErrorCallBack(request.status + " " + request.statusText, exception);
  17286. }
  17287. };
  17288. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17289. };
  17290. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17291. if (onError === void 0) { onError = null; }
  17292. var loadedFiles = [];
  17293. loadedFiles._internalCount = 0;
  17294. for (var index = 0; index < 6; index++) {
  17295. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17296. }
  17297. };
  17298. // Statics
  17299. /**
  17300. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17301. * @returns true if the engine can be created
  17302. * @ignorenaming
  17303. */
  17304. Engine.isSupported = function () {
  17305. try {
  17306. var tempcanvas = document.createElement("canvas");
  17307. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17308. return gl != null && !!window.WebGLRenderingContext;
  17309. }
  17310. catch (e) {
  17311. return false;
  17312. }
  17313. };
  17314. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17315. Engine.ExceptionList = [
  17316. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17317. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17318. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17319. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17320. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17321. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17322. ];
  17323. /** Gets the list of created engines */
  17324. Engine.Instances = new Array();
  17325. // Const statics
  17326. Engine._ALPHA_DISABLE = 0;
  17327. Engine._ALPHA_ADD = 1;
  17328. Engine._ALPHA_COMBINE = 2;
  17329. Engine._ALPHA_SUBTRACT = 3;
  17330. Engine._ALPHA_MULTIPLY = 4;
  17331. Engine._ALPHA_MAXIMIZED = 5;
  17332. Engine._ALPHA_ONEONE = 6;
  17333. Engine._ALPHA_PREMULTIPLIED = 7;
  17334. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17335. Engine._ALPHA_INTERPOLATE = 9;
  17336. Engine._ALPHA_SCREENMODE = 10;
  17337. Engine._DELAYLOADSTATE_NONE = 0;
  17338. Engine._DELAYLOADSTATE_LOADED = 1;
  17339. Engine._DELAYLOADSTATE_LOADING = 2;
  17340. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17341. Engine._TEXTUREFORMAT_ALPHA = 0;
  17342. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17343. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17344. Engine._TEXTUREFORMAT_RGB = 4;
  17345. Engine._TEXTUREFORMAT_RGBA = 5;
  17346. Engine._TEXTUREFORMAT_R32F = 6;
  17347. Engine._TEXTUREFORMAT_RG32F = 7;
  17348. Engine._TEXTUREFORMAT_RGB32F = 8;
  17349. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17350. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17351. Engine._TEXTURETYPE_FLOAT = 1;
  17352. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17353. // Depht or Stencil test Constants.
  17354. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17355. 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.
  17356. 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.
  17357. 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.
  17358. 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.
  17359. 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.
  17360. 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.
  17361. 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.
  17362. // Stencil Actions Constants.
  17363. Engine._KEEP = 0x1E00;
  17364. Engine._REPLACE = 0x1E01;
  17365. Engine._INCR = 0x1E02;
  17366. Engine._DECR = 0x1E03;
  17367. Engine._INVERT = 0x150A;
  17368. Engine._INCR_WRAP = 0x8507;
  17369. Engine._DECR_WRAP = 0x8508;
  17370. // Texture rescaling mode
  17371. Engine._SCALEMODE_FLOOR = 1;
  17372. Engine._SCALEMODE_NEAREST = 2;
  17373. Engine._SCALEMODE_CEILING = 3;
  17374. // Updatable statics so stick with vars here
  17375. /**
  17376. * Gets or sets the epsilon value used by collision engine
  17377. */
  17378. Engine.CollisionsEpsilon = 0.001;
  17379. /**
  17380. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17381. */
  17382. Engine.CodeRepository = "src/";
  17383. /**
  17384. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17385. */
  17386. Engine.ShadersRepository = "src/Shaders/";
  17387. return Engine;
  17388. }());
  17389. BABYLON.Engine = Engine;
  17390. })(BABYLON || (BABYLON = {}));
  17391. //# sourceMappingURL=babylon.engine.js.map
  17392. var BABYLON;
  17393. (function (BABYLON) {
  17394. /**
  17395. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17396. */
  17397. var Node = /** @class */ (function () {
  17398. /**
  17399. * Creates a new Node
  17400. * @param {string} name - the name and id to be given to this node
  17401. * @param {BABYLON.Scene} the scene this node will be added to
  17402. */
  17403. function Node(name, scene) {
  17404. if (scene === void 0) { scene = null; }
  17405. /**
  17406. * Gets or sets a string used to store user defined state for the node
  17407. */
  17408. this.state = "";
  17409. /**
  17410. * Gets or sets an object used to store user defined information for the node
  17411. */
  17412. this.metadata = null;
  17413. /**
  17414. * Gets or sets a boolean used to define if the node must be serialized
  17415. */
  17416. this.doNotSerialize = false;
  17417. /** @hidden */
  17418. this._isDisposed = false;
  17419. /**
  17420. * Gets a list of Animations associated with the node
  17421. */
  17422. this.animations = new Array();
  17423. this._ranges = {};
  17424. this._isEnabled = true;
  17425. this._isReady = true;
  17426. /** @hidden */
  17427. this._currentRenderId = -1;
  17428. this._parentRenderId = -1;
  17429. this._childRenderId = -1;
  17430. this._animationPropertiesOverride = null;
  17431. /**
  17432. * An event triggered when the mesh is disposed
  17433. */
  17434. this.onDisposeObservable = new BABYLON.Observable();
  17435. // Behaviors
  17436. this._behaviors = new Array();
  17437. this.name = name;
  17438. this.id = name;
  17439. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17440. this.uniqueId = this._scene.getUniqueId();
  17441. this._initCache();
  17442. }
  17443. /**
  17444. * Gets a boolean indicating if the node has been disposed
  17445. * @returns true if the node was disposed
  17446. */
  17447. Node.prototype.isDisposed = function () {
  17448. return this._isDisposed;
  17449. };
  17450. Object.defineProperty(Node.prototype, "parent", {
  17451. get: function () {
  17452. return this._parentNode;
  17453. },
  17454. /**
  17455. * Gets or sets the parent of the node
  17456. */
  17457. set: function (parent) {
  17458. if (this._parentNode === parent) {
  17459. return;
  17460. }
  17461. // Remove self from list of children of parent
  17462. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17463. var index = this._parentNode._children.indexOf(this);
  17464. if (index !== -1) {
  17465. this._parentNode._children.splice(index, 1);
  17466. }
  17467. }
  17468. // Store new parent
  17469. this._parentNode = parent;
  17470. // Add as child to new parent
  17471. if (this._parentNode) {
  17472. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17473. this._parentNode._children = new Array();
  17474. }
  17475. this._parentNode._children.push(this);
  17476. }
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17482. /**
  17483. * Gets or sets the animation properties override
  17484. */
  17485. get: function () {
  17486. if (!this._animationPropertiesOverride) {
  17487. return this._scene.animationPropertiesOverride;
  17488. }
  17489. return this._animationPropertiesOverride;
  17490. },
  17491. set: function (value) {
  17492. this._animationPropertiesOverride = value;
  17493. },
  17494. enumerable: true,
  17495. configurable: true
  17496. });
  17497. /**
  17498. * Gets a string idenfifying the name of the class
  17499. * @returns "Node" string
  17500. */
  17501. Node.prototype.getClassName = function () {
  17502. return "Node";
  17503. };
  17504. Object.defineProperty(Node.prototype, "onDispose", {
  17505. /**
  17506. * Sets a callback that will be raised when the node will be disposed
  17507. */
  17508. set: function (callback) {
  17509. if (this._onDisposeObserver) {
  17510. this.onDisposeObservable.remove(this._onDisposeObserver);
  17511. }
  17512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. /**
  17518. * Gets the scene of the node
  17519. * @returns a {BABYLON.Scene}
  17520. */
  17521. Node.prototype.getScene = function () {
  17522. return this._scene;
  17523. };
  17524. /**
  17525. * Gets the engine of the node
  17526. * @returns a {BABYLON.Engine}
  17527. */
  17528. Node.prototype.getEngine = function () {
  17529. return this._scene.getEngine();
  17530. };
  17531. /**
  17532. * Attach a behavior to the node
  17533. * @see http://doc.babylonjs.com/features/behaviour
  17534. * @param behavior defines the behavior to attach
  17535. * @returns the current Node
  17536. */
  17537. Node.prototype.addBehavior = function (behavior) {
  17538. var _this = this;
  17539. var index = this._behaviors.indexOf(behavior);
  17540. if (index !== -1) {
  17541. return this;
  17542. }
  17543. behavior.init();
  17544. if (this._scene.isLoading) {
  17545. // We defer the attach when the scene will be loaded
  17546. var observer = this._scene.onDataLoadedObservable.add(function () {
  17547. behavior.attach(_this);
  17548. setTimeout(function () {
  17549. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17550. _this._scene.onDataLoadedObservable.remove(observer);
  17551. }, 0);
  17552. });
  17553. }
  17554. else {
  17555. behavior.attach(this);
  17556. }
  17557. this._behaviors.push(behavior);
  17558. return this;
  17559. };
  17560. /**
  17561. * Remove an attached behavior
  17562. * @see http://doc.babylonjs.com/features/behaviour
  17563. * @param behavior defines the behavior to attach
  17564. * @returns the current Node
  17565. */
  17566. Node.prototype.removeBehavior = function (behavior) {
  17567. var index = this._behaviors.indexOf(behavior);
  17568. if (index === -1) {
  17569. return this;
  17570. }
  17571. this._behaviors[index].detach();
  17572. this._behaviors.splice(index, 1);
  17573. return this;
  17574. };
  17575. Object.defineProperty(Node.prototype, "behaviors", {
  17576. /**
  17577. * Gets the list of attached behaviors
  17578. * @see http://doc.babylonjs.com/features/behaviour
  17579. */
  17580. get: function () {
  17581. return this._behaviors;
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. /**
  17587. * Gets an attached behavior by name
  17588. * @param name defines the name of the behavior to look for
  17589. * @see http://doc.babylonjs.com/features/behaviour
  17590. * @returns null if behavior was not found else the requested behavior
  17591. */
  17592. Node.prototype.getBehaviorByName = function (name) {
  17593. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17594. var behavior = _a[_i];
  17595. if (behavior.name === name) {
  17596. return behavior;
  17597. }
  17598. }
  17599. return null;
  17600. };
  17601. /**
  17602. * Returns the world matrix of the node
  17603. * @returns a matrix containing the node's world matrix
  17604. */
  17605. Node.prototype.getWorldMatrix = function () {
  17606. return BABYLON.Matrix.Identity();
  17607. };
  17608. /** @hidden */
  17609. Node.prototype._getWorldMatrixDeterminant = function () {
  17610. return 1;
  17611. };
  17612. // override it in derived class if you add new variables to the cache
  17613. // and call the parent class method
  17614. /** @hidden */
  17615. Node.prototype._initCache = function () {
  17616. this._cache = {};
  17617. this._cache.parent = undefined;
  17618. };
  17619. /** @hidden */
  17620. Node.prototype.updateCache = function (force) {
  17621. if (!force && this.isSynchronized())
  17622. return;
  17623. this._cache.parent = this.parent;
  17624. this._updateCache();
  17625. };
  17626. // override it in derived class if you add new variables to the cache
  17627. // and call the parent class method if !ignoreParentClass
  17628. /** @hidden */
  17629. Node.prototype._updateCache = function (ignoreParentClass) {
  17630. };
  17631. // override it in derived class if you add new variables to the cache
  17632. /** @hidden */
  17633. Node.prototype._isSynchronized = function () {
  17634. return true;
  17635. };
  17636. /** @hidden */
  17637. Node.prototype._markSyncedWithParent = function () {
  17638. if (this.parent) {
  17639. this._parentRenderId = this.parent._childRenderId;
  17640. }
  17641. };
  17642. /** @hidden */
  17643. Node.prototype.isSynchronizedWithParent = function () {
  17644. if (!this.parent) {
  17645. return true;
  17646. }
  17647. if (this._parentRenderId !== this.parent._childRenderId) {
  17648. return false;
  17649. }
  17650. return this.parent.isSynchronized();
  17651. };
  17652. /** @hidden */
  17653. Node.prototype.isSynchronized = function (updateCache) {
  17654. var check = this.hasNewParent();
  17655. check = check || !this.isSynchronizedWithParent();
  17656. check = check || !this._isSynchronized();
  17657. if (updateCache)
  17658. this.updateCache(true);
  17659. return !check;
  17660. };
  17661. /** @hidden */
  17662. Node.prototype.hasNewParent = function (update) {
  17663. if (this._cache.parent === this.parent)
  17664. return false;
  17665. if (update)
  17666. this._cache.parent = this.parent;
  17667. return true;
  17668. };
  17669. /**
  17670. * Is this node ready to be used/rendered
  17671. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17672. * @return true if the node is ready
  17673. */
  17674. Node.prototype.isReady = function (completeCheck) {
  17675. if (completeCheck === void 0) { completeCheck = false; }
  17676. return this._isReady;
  17677. };
  17678. /**
  17679. * Is this node enabled?
  17680. * 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
  17681. * @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
  17682. * @return whether this node (and its parent) is enabled
  17683. */
  17684. Node.prototype.isEnabled = function (checkAncestors) {
  17685. if (checkAncestors === void 0) { checkAncestors = true; }
  17686. if (checkAncestors === false) {
  17687. return this._isEnabled;
  17688. }
  17689. if (this._isEnabled === false) {
  17690. return false;
  17691. }
  17692. if (this.parent !== undefined && this.parent !== null) {
  17693. return this.parent.isEnabled(checkAncestors);
  17694. }
  17695. return true;
  17696. };
  17697. /**
  17698. * Set the enabled state of this node
  17699. * @param value defines the new enabled state
  17700. */
  17701. Node.prototype.setEnabled = function (value) {
  17702. this._isEnabled = value;
  17703. };
  17704. /**
  17705. * Is this node a descendant of the given node?
  17706. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17707. * @param ancestor defines the parent node to inspect
  17708. * @returns a boolean indicating if this node is a descendant of the given node
  17709. */
  17710. Node.prototype.isDescendantOf = function (ancestor) {
  17711. if (this.parent) {
  17712. if (this.parent === ancestor) {
  17713. return true;
  17714. }
  17715. return this.parent.isDescendantOf(ancestor);
  17716. }
  17717. return false;
  17718. };
  17719. /** @hidden */
  17720. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17721. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17722. if (!this._children) {
  17723. return;
  17724. }
  17725. for (var index = 0; index < this._children.length; index++) {
  17726. var item = this._children[index];
  17727. if (!predicate || predicate(item)) {
  17728. results.push(item);
  17729. }
  17730. if (!directDescendantsOnly) {
  17731. item._getDescendants(results, false, predicate);
  17732. }
  17733. }
  17734. };
  17735. /**
  17736. * Will return all nodes that have this node as ascendant
  17737. * @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
  17738. * @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
  17739. * @return all children nodes of all types
  17740. */
  17741. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17742. var results = new Array();
  17743. this._getDescendants(results, directDescendantsOnly, predicate);
  17744. return results;
  17745. };
  17746. /**
  17747. * Get all child-meshes of this node
  17748. * @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
  17749. * @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
  17750. * @returns an array of {BABYLON.AbstractMesh}
  17751. */
  17752. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17753. var results = [];
  17754. this._getDescendants(results, directDescendantsOnly, function (node) {
  17755. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17756. });
  17757. return results;
  17758. };
  17759. /**
  17760. * Get all child-transformNodes of this node
  17761. * @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
  17762. * @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
  17763. * @returns an array of {BABYLON.TransformNode}
  17764. */
  17765. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17766. var results = [];
  17767. this._getDescendants(results, directDescendantsOnly, function (node) {
  17768. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17769. });
  17770. return results;
  17771. };
  17772. /**
  17773. * Get all direct children of this node
  17774. * @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
  17775. * @returns an array of {BABYLON.Node}
  17776. */
  17777. Node.prototype.getChildren = function (predicate) {
  17778. return this.getDescendants(true, predicate);
  17779. };
  17780. /** @hidden */
  17781. Node.prototype._setReady = function (state) {
  17782. if (state === this._isReady) {
  17783. return;
  17784. }
  17785. if (!state) {
  17786. this._isReady = false;
  17787. return;
  17788. }
  17789. if (this.onReady) {
  17790. this.onReady(this);
  17791. }
  17792. this._isReady = true;
  17793. };
  17794. /**
  17795. * Get an animation by name
  17796. * @param name defines the name of the animation to look for
  17797. * @returns null if not found else the requested animation
  17798. */
  17799. Node.prototype.getAnimationByName = function (name) {
  17800. for (var i = 0; i < this.animations.length; i++) {
  17801. var animation = this.animations[i];
  17802. if (animation.name === name) {
  17803. return animation;
  17804. }
  17805. }
  17806. return null;
  17807. };
  17808. /**
  17809. * Creates an animation range for this node
  17810. * @param name defines the name of the range
  17811. * @param from defines the starting key
  17812. * @param to defines the end key
  17813. */
  17814. Node.prototype.createAnimationRange = function (name, from, to) {
  17815. // check name not already in use
  17816. if (!this._ranges[name]) {
  17817. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17818. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17819. if (this.animations[i]) {
  17820. this.animations[i].createRange(name, from, to);
  17821. }
  17822. }
  17823. }
  17824. };
  17825. /**
  17826. * Delete a specific animation range
  17827. * @param name defines the name of the range to delete
  17828. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17829. */
  17830. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17831. if (deleteFrames === void 0) { deleteFrames = true; }
  17832. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17833. if (this.animations[i]) {
  17834. this.animations[i].deleteRange(name, deleteFrames);
  17835. }
  17836. }
  17837. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17838. };
  17839. /**
  17840. * Get an animation range by name
  17841. * @param name defines the name of the animation range to look for
  17842. * @returns null if not found else the requested animation range
  17843. */
  17844. Node.prototype.getAnimationRange = function (name) {
  17845. return this._ranges[name];
  17846. };
  17847. /**
  17848. * Will start the animation sequence
  17849. * @param name defines the range frames for animation sequence
  17850. * @param loop defines if the animation should loop (false by default)
  17851. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17852. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17853. * @returns the object created for this animation. If range does not exist, it will return null
  17854. */
  17855. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17856. var range = this.getAnimationRange(name);
  17857. if (!range) {
  17858. return null;
  17859. }
  17860. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17861. };
  17862. /**
  17863. * Serialize animation ranges into a JSON compatible object
  17864. * @returns serialization object
  17865. */
  17866. Node.prototype.serializeAnimationRanges = function () {
  17867. var serializationRanges = [];
  17868. for (var name in this._ranges) {
  17869. var localRange = this._ranges[name];
  17870. if (!localRange) {
  17871. continue;
  17872. }
  17873. var range = {};
  17874. range.name = name;
  17875. range.from = localRange.from;
  17876. range.to = localRange.to;
  17877. serializationRanges.push(range);
  17878. }
  17879. return serializationRanges;
  17880. };
  17881. /**
  17882. * Computes the world matrix of the node
  17883. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17884. * @returns the world matrix
  17885. */
  17886. Node.prototype.computeWorldMatrix = function (force) {
  17887. return BABYLON.Matrix.Identity();
  17888. };
  17889. /**
  17890. * Releases resources associated with this node.
  17891. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17892. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17893. */
  17894. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17895. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17896. if (!doNotRecurse) {
  17897. var nodes = this.getDescendants(true);
  17898. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17899. var node = nodes_1[_i];
  17900. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17901. }
  17902. }
  17903. else {
  17904. var transformNodes = this.getChildTransformNodes(true);
  17905. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17906. var transformNode = transformNodes_1[_a];
  17907. transformNode.parent = null;
  17908. transformNode.computeWorldMatrix(true);
  17909. }
  17910. }
  17911. this.parent = null;
  17912. // Callback
  17913. this.onDisposeObservable.notifyObservers(this);
  17914. this.onDisposeObservable.clear();
  17915. // Behaviors
  17916. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17917. var behavior = _c[_b];
  17918. behavior.detach();
  17919. }
  17920. this._behaviors = [];
  17921. this._isDisposed = true;
  17922. };
  17923. /**
  17924. * Parse animation range data from a serialization object and store them into a given node
  17925. * @param node defines where to store the animation ranges
  17926. * @param parsedNode defines the serialization object to read data from
  17927. * @param scene defines the hosting scene
  17928. */
  17929. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17930. if (parsedNode.ranges) {
  17931. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17932. var data = parsedNode.ranges[index];
  17933. node.createAnimationRange(data.name, data.from, data.to);
  17934. }
  17935. }
  17936. };
  17937. __decorate([
  17938. BABYLON.serialize()
  17939. ], Node.prototype, "name", void 0);
  17940. __decorate([
  17941. BABYLON.serialize()
  17942. ], Node.prototype, "id", void 0);
  17943. __decorate([
  17944. BABYLON.serialize()
  17945. ], Node.prototype, "uniqueId", void 0);
  17946. __decorate([
  17947. BABYLON.serialize()
  17948. ], Node.prototype, "state", void 0);
  17949. __decorate([
  17950. BABYLON.serialize()
  17951. ], Node.prototype, "metadata", void 0);
  17952. return Node;
  17953. }());
  17954. BABYLON.Node = Node;
  17955. })(BABYLON || (BABYLON = {}));
  17956. //# sourceMappingURL=babylon.node.js.map
  17957. var BABYLON;
  17958. (function (BABYLON) {
  17959. var BoundingSphere = /** @class */ (function () {
  17960. /**
  17961. * Creates a new bounding sphere
  17962. * @param min defines the minimum vector (in local space)
  17963. * @param max defines the maximum vector (in local space)
  17964. */
  17965. function BoundingSphere(min, max) {
  17966. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17967. this.reConstruct(min, max);
  17968. }
  17969. /**
  17970. * Recreates the entire bounding sphere from scratch
  17971. * @param min defines the new minimum vector (in local space)
  17972. * @param max defines the new maximum vector (in local space)
  17973. */
  17974. BoundingSphere.prototype.reConstruct = function (min, max) {
  17975. this.minimum = min.clone();
  17976. this.maximum = max.clone();
  17977. var distance = BABYLON.Vector3.Distance(min, max);
  17978. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17979. this.radius = distance * 0.5;
  17980. this.centerWorld = BABYLON.Vector3.Zero();
  17981. this._update(BABYLON.Matrix.Identity());
  17982. };
  17983. // Methods
  17984. BoundingSphere.prototype._update = function (world) {
  17985. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17986. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17987. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17988. };
  17989. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17990. for (var i = 0; i < 6; i++) {
  17991. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17992. return false;
  17993. }
  17994. return true;
  17995. };
  17996. BoundingSphere.prototype.intersectsPoint = function (point) {
  17997. var x = this.centerWorld.x - point.x;
  17998. var y = this.centerWorld.y - point.y;
  17999. var z = this.centerWorld.z - point.z;
  18000. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18001. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18002. return false;
  18003. return true;
  18004. };
  18005. // Statics
  18006. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18007. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18008. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18009. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18010. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18011. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18012. return false;
  18013. return true;
  18014. };
  18015. return BoundingSphere;
  18016. }());
  18017. BABYLON.BoundingSphere = BoundingSphere;
  18018. })(BABYLON || (BABYLON = {}));
  18019. //# sourceMappingURL=babylon.boundingSphere.js.map
  18020. var BABYLON;
  18021. (function (BABYLON) {
  18022. var BoundingBox = /** @class */ (function () {
  18023. /**
  18024. * Creates a new bounding box
  18025. * @param min defines the minimum vector (in local space)
  18026. * @param max defines the maximum vector (in local space)
  18027. */
  18028. function BoundingBox(min, max) {
  18029. this.vectorsWorld = new Array();
  18030. this.reConstruct(min, max);
  18031. }
  18032. // Methods
  18033. /**
  18034. * Recreates the entire bounding box from scratch
  18035. * @param min defines the new minimum vector (in local space)
  18036. * @param max defines the new maximum vector (in local space)
  18037. */
  18038. BoundingBox.prototype.reConstruct = function (min, max) {
  18039. this.minimum = min.clone();
  18040. this.maximum = max.clone();
  18041. // Bounding vectors
  18042. this.vectors = new Array();
  18043. this.vectors.push(this.minimum.clone());
  18044. this.vectors.push(this.maximum.clone());
  18045. this.vectors.push(this.minimum.clone());
  18046. this.vectors[2].x = this.maximum.x;
  18047. this.vectors.push(this.minimum.clone());
  18048. this.vectors[3].y = this.maximum.y;
  18049. this.vectors.push(this.minimum.clone());
  18050. this.vectors[4].z = this.maximum.z;
  18051. this.vectors.push(this.maximum.clone());
  18052. this.vectors[5].z = this.minimum.z;
  18053. this.vectors.push(this.maximum.clone());
  18054. this.vectors[6].x = this.minimum.x;
  18055. this.vectors.push(this.maximum.clone());
  18056. this.vectors[7].y = this.minimum.y;
  18057. // OBB
  18058. this.center = this.maximum.add(this.minimum).scale(0.5);
  18059. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18060. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18061. // World
  18062. for (var index = 0; index < this.vectors.length; index++) {
  18063. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18064. }
  18065. this.minimumWorld = BABYLON.Vector3.Zero();
  18066. this.maximumWorld = BABYLON.Vector3.Zero();
  18067. this.centerWorld = BABYLON.Vector3.Zero();
  18068. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18069. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18070. };
  18071. BoundingBox.prototype.getWorldMatrix = function () {
  18072. return this._worldMatrix;
  18073. };
  18074. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18075. this._worldMatrix.copyFrom(matrix);
  18076. return this;
  18077. };
  18078. BoundingBox.prototype._update = function (world) {
  18079. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18080. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18081. for (var index = 0; index < this.vectors.length; index++) {
  18082. var v = this.vectorsWorld[index];
  18083. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18084. if (v.x < this.minimumWorld.x)
  18085. this.minimumWorld.x = v.x;
  18086. if (v.y < this.minimumWorld.y)
  18087. this.minimumWorld.y = v.y;
  18088. if (v.z < this.minimumWorld.z)
  18089. this.minimumWorld.z = v.z;
  18090. if (v.x > this.maximumWorld.x)
  18091. this.maximumWorld.x = v.x;
  18092. if (v.y > this.maximumWorld.y)
  18093. this.maximumWorld.y = v.y;
  18094. if (v.z > this.maximumWorld.z)
  18095. this.maximumWorld.z = v.z;
  18096. }
  18097. // Extend
  18098. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18099. this.extendSizeWorld.scaleInPlace(0.5);
  18100. // OBB
  18101. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18102. this.centerWorld.scaleInPlace(0.5);
  18103. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18104. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18105. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18106. this._worldMatrix = world;
  18107. };
  18108. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18109. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18110. };
  18111. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18112. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18113. };
  18114. BoundingBox.prototype.intersectsPoint = function (point) {
  18115. var delta = -BABYLON.Epsilon;
  18116. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18117. return false;
  18118. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18119. return false;
  18120. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18121. return false;
  18122. return true;
  18123. };
  18124. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18125. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18126. };
  18127. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18128. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18129. return false;
  18130. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18131. return false;
  18132. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18133. return false;
  18134. return true;
  18135. };
  18136. // Statics
  18137. BoundingBox.Intersects = function (box0, box1) {
  18138. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18139. return false;
  18140. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18141. return false;
  18142. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18143. return false;
  18144. return true;
  18145. };
  18146. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18147. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18148. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18149. return (num <= (sphereRadius * sphereRadius));
  18150. };
  18151. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18152. for (var p = 0; p < 6; p++) {
  18153. for (var i = 0; i < 8; i++) {
  18154. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18155. return false;
  18156. }
  18157. }
  18158. }
  18159. return true;
  18160. };
  18161. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18162. for (var p = 0; p < 6; p++) {
  18163. var inCount = 8;
  18164. for (var i = 0; i < 8; i++) {
  18165. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18166. --inCount;
  18167. }
  18168. else {
  18169. break;
  18170. }
  18171. }
  18172. if (inCount === 0)
  18173. return false;
  18174. }
  18175. return true;
  18176. };
  18177. return BoundingBox;
  18178. }());
  18179. BABYLON.BoundingBox = BoundingBox;
  18180. })(BABYLON || (BABYLON = {}));
  18181. //# sourceMappingURL=babylon.boundingBox.js.map
  18182. var BABYLON;
  18183. (function (BABYLON) {
  18184. var computeBoxExtents = function (axis, box) {
  18185. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18186. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18187. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18188. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18189. var r = r0 + r1 + r2;
  18190. return {
  18191. min: p - r,
  18192. max: p + r
  18193. };
  18194. };
  18195. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18196. var axisOverlap = function (axis, box0, box1) {
  18197. var result0 = computeBoxExtents(axis, box0);
  18198. var result1 = computeBoxExtents(axis, box1);
  18199. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18200. };
  18201. var BoundingInfo = /** @class */ (function () {
  18202. function BoundingInfo(minimum, maximum) {
  18203. this.minimum = minimum;
  18204. this.maximum = maximum;
  18205. this._isLocked = false;
  18206. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18207. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18208. }
  18209. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18210. get: function () {
  18211. return this._isLocked;
  18212. },
  18213. set: function (value) {
  18214. this._isLocked = value;
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. // Methods
  18220. BoundingInfo.prototype.update = function (world) {
  18221. if (this._isLocked) {
  18222. return;
  18223. }
  18224. this.boundingBox._update(world);
  18225. this.boundingSphere._update(world);
  18226. };
  18227. /**
  18228. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18229. * @param center New center of the bounding info
  18230. * @param extend New extend of the bounding info
  18231. */
  18232. BoundingInfo.prototype.centerOn = function (center, extend) {
  18233. this.minimum = center.subtract(extend);
  18234. this.maximum = center.add(extend);
  18235. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18236. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18237. return this;
  18238. };
  18239. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18240. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18241. return false;
  18242. return this.boundingBox.isInFrustum(frustumPlanes);
  18243. };
  18244. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18245. /**
  18246. * Gets the world distance between the min and max points of the bounding box
  18247. */
  18248. get: function () {
  18249. var boundingBox = this.boundingBox;
  18250. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18251. return size.length();
  18252. },
  18253. enumerable: true,
  18254. configurable: true
  18255. });
  18256. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18257. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18258. };
  18259. BoundingInfo.prototype._checkCollision = function (collider) {
  18260. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18261. };
  18262. BoundingInfo.prototype.intersectsPoint = function (point) {
  18263. if (!this.boundingSphere.centerWorld) {
  18264. return false;
  18265. }
  18266. if (!this.boundingSphere.intersectsPoint(point)) {
  18267. return false;
  18268. }
  18269. if (!this.boundingBox.intersectsPoint(point)) {
  18270. return false;
  18271. }
  18272. return true;
  18273. };
  18274. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18275. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18276. return false;
  18277. }
  18278. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18279. return false;
  18280. }
  18281. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18282. return false;
  18283. }
  18284. if (!precise) {
  18285. return true;
  18286. }
  18287. var box0 = this.boundingBox;
  18288. var box1 = boundingInfo.boundingBox;
  18289. if (!axisOverlap(box0.directions[0], box0, box1))
  18290. return false;
  18291. if (!axisOverlap(box0.directions[1], box0, box1))
  18292. return false;
  18293. if (!axisOverlap(box0.directions[2], box0, box1))
  18294. return false;
  18295. if (!axisOverlap(box1.directions[0], box0, box1))
  18296. return false;
  18297. if (!axisOverlap(box1.directions[1], box0, box1))
  18298. return false;
  18299. if (!axisOverlap(box1.directions[2], box0, box1))
  18300. return false;
  18301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18302. return false;
  18303. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18304. return false;
  18305. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18306. return false;
  18307. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18308. return false;
  18309. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18310. return false;
  18311. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18312. return false;
  18313. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18314. return false;
  18315. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18316. return false;
  18317. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18318. return false;
  18319. return true;
  18320. };
  18321. return BoundingInfo;
  18322. }());
  18323. BABYLON.BoundingInfo = BoundingInfo;
  18324. })(BABYLON || (BABYLON = {}));
  18325. //# sourceMappingURL=babylon.boundingInfo.js.map
  18326. var BABYLON;
  18327. (function (BABYLON) {
  18328. var TransformNode = /** @class */ (function (_super) {
  18329. __extends(TransformNode, _super);
  18330. function TransformNode(name, scene, isPure) {
  18331. if (scene === void 0) { scene = null; }
  18332. if (isPure === void 0) { isPure = true; }
  18333. var _this = _super.call(this, name, scene) || this;
  18334. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18335. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18336. _this._up = new BABYLON.Vector3(0, 1, 0);
  18337. _this._right = new BABYLON.Vector3(1, 0, 0);
  18338. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18339. // Properties
  18340. _this._rotation = BABYLON.Vector3.Zero();
  18341. _this._scaling = BABYLON.Vector3.One();
  18342. _this._isDirty = false;
  18343. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18344. _this.scalingDeterminant = 1;
  18345. _this.infiniteDistance = false;
  18346. _this.position = BABYLON.Vector3.Zero();
  18347. _this._localWorld = BABYLON.Matrix.Zero();
  18348. _this._worldMatrix = BABYLON.Matrix.Zero();
  18349. _this._worldMatrixDeterminant = 0;
  18350. _this._absolutePosition = BABYLON.Vector3.Zero();
  18351. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18352. _this._postMultiplyPivotMatrix = false;
  18353. _this._isWorldMatrixFrozen = false;
  18354. /**
  18355. * An event triggered after the world matrix is updated
  18356. */
  18357. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18358. _this._nonUniformScaling = false;
  18359. if (isPure) {
  18360. _this.getScene().addTransformNode(_this);
  18361. }
  18362. return _this;
  18363. }
  18364. /**
  18365. * Gets a string idenfifying the name of the class
  18366. * @returns "TransformNode" string
  18367. */
  18368. TransformNode.prototype.getClassName = function () {
  18369. return "TransformNode";
  18370. };
  18371. Object.defineProperty(TransformNode.prototype, "rotation", {
  18372. /**
  18373. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18374. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18375. * Default : (0.0, 0.0, 0.0)
  18376. */
  18377. get: function () {
  18378. return this._rotation;
  18379. },
  18380. set: function (newRotation) {
  18381. this._rotation = newRotation;
  18382. },
  18383. enumerable: true,
  18384. configurable: true
  18385. });
  18386. Object.defineProperty(TransformNode.prototype, "scaling", {
  18387. /**
  18388. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18389. * Default : (1.0, 1.0, 1.0)
  18390. */
  18391. get: function () {
  18392. return this._scaling;
  18393. },
  18394. /**
  18395. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18396. * Default : (1.0, 1.0, 1.0)
  18397. */
  18398. set: function (newScaling) {
  18399. this._scaling = newScaling;
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18405. /**
  18406. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18407. * It's null by default.
  18408. * 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)
  18409. */
  18410. get: function () {
  18411. return this._rotationQuaternion;
  18412. },
  18413. set: function (quaternion) {
  18414. this._rotationQuaternion = quaternion;
  18415. //reset the rotation vector.
  18416. if (quaternion && this.rotation.length()) {
  18417. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18418. }
  18419. },
  18420. enumerable: true,
  18421. configurable: true
  18422. });
  18423. Object.defineProperty(TransformNode.prototype, "forward", {
  18424. /**
  18425. * The forward direction of that transform in world space.
  18426. */
  18427. get: function () {
  18428. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(TransformNode.prototype, "up", {
  18434. /**
  18435. * The up direction of that transform in world space.
  18436. */
  18437. get: function () {
  18438. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. Object.defineProperty(TransformNode.prototype, "right", {
  18444. /**
  18445. * The right direction of that transform in world space.
  18446. */
  18447. get: function () {
  18448. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18449. },
  18450. enumerable: true,
  18451. configurable: true
  18452. });
  18453. /**
  18454. * Returns the latest update of the World matrix
  18455. * Returns a Matrix.
  18456. */
  18457. TransformNode.prototype.getWorldMatrix = function () {
  18458. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18459. this.computeWorldMatrix();
  18460. }
  18461. return this._worldMatrix;
  18462. };
  18463. /** @hidden */
  18464. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18465. return this._worldMatrixDeterminant;
  18466. };
  18467. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18468. /**
  18469. * Returns directly the latest state of the mesh World matrix.
  18470. * A Matrix is returned.
  18471. */
  18472. get: function () {
  18473. return this._worldMatrix;
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. /**
  18479. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18480. * Returns the TransformNode.
  18481. */
  18482. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18483. this._poseMatrix.copyFrom(matrix);
  18484. return this;
  18485. };
  18486. /**
  18487. * Returns the mesh Pose matrix.
  18488. * Returned object : Matrix
  18489. */
  18490. TransformNode.prototype.getPoseMatrix = function () {
  18491. return this._poseMatrix;
  18492. };
  18493. TransformNode.prototype._isSynchronized = function () {
  18494. if (this._isDirty) {
  18495. return false;
  18496. }
  18497. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18498. return false;
  18499. if (this._cache.pivotMatrixUpdated) {
  18500. return false;
  18501. }
  18502. if (this.infiniteDistance) {
  18503. return false;
  18504. }
  18505. if (!this._cache.position.equals(this.position))
  18506. return false;
  18507. if (this.rotationQuaternion) {
  18508. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18509. return false;
  18510. }
  18511. if (!this._cache.rotation.equals(this.rotation))
  18512. return false;
  18513. if (!this._cache.scaling.equals(this.scaling))
  18514. return false;
  18515. return true;
  18516. };
  18517. TransformNode.prototype._initCache = function () {
  18518. _super.prototype._initCache.call(this);
  18519. this._cache.localMatrixUpdated = false;
  18520. this._cache.position = BABYLON.Vector3.Zero();
  18521. this._cache.scaling = BABYLON.Vector3.Zero();
  18522. this._cache.rotation = BABYLON.Vector3.Zero();
  18523. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18524. this._cache.billboardMode = -1;
  18525. };
  18526. TransformNode.prototype.markAsDirty = function (property) {
  18527. if (property === "rotation") {
  18528. this.rotationQuaternion = null;
  18529. }
  18530. this._currentRenderId = Number.MAX_VALUE;
  18531. this._isDirty = true;
  18532. return this;
  18533. };
  18534. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18535. /**
  18536. * Returns the current mesh absolute position.
  18537. * Retuns a Vector3.
  18538. */
  18539. get: function () {
  18540. return this._absolutePosition;
  18541. },
  18542. enumerable: true,
  18543. configurable: true
  18544. });
  18545. /**
  18546. * Sets a new matrix to apply before all other transformation
  18547. * @param matrix defines the transform matrix
  18548. * @returns the current TransformNode
  18549. */
  18550. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18551. return this.setPivotMatrix(matrix, false);
  18552. };
  18553. /**
  18554. * Sets a new pivot matrix to the current node
  18555. * @param matrix defines the new pivot matrix to use
  18556. * @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
  18557. * @returns the current TransformNode
  18558. */
  18559. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18560. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18561. this._pivotMatrix = matrix.clone();
  18562. this._cache.pivotMatrixUpdated = true;
  18563. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18564. if (this._postMultiplyPivotMatrix) {
  18565. if (!this._pivotMatrixInverse) {
  18566. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18567. }
  18568. else {
  18569. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18570. }
  18571. }
  18572. return this;
  18573. };
  18574. /**
  18575. * Returns the mesh pivot matrix.
  18576. * Default : Identity.
  18577. * A Matrix is returned.
  18578. */
  18579. TransformNode.prototype.getPivotMatrix = function () {
  18580. return this._pivotMatrix;
  18581. };
  18582. /**
  18583. * Prevents the World matrix to be computed any longer.
  18584. * Returns the TransformNode.
  18585. */
  18586. TransformNode.prototype.freezeWorldMatrix = function () {
  18587. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18588. this.computeWorldMatrix(true);
  18589. this._isWorldMatrixFrozen = true;
  18590. return this;
  18591. };
  18592. /**
  18593. * Allows back the World matrix computation.
  18594. * Returns the TransformNode.
  18595. */
  18596. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18597. this._isWorldMatrixFrozen = false;
  18598. this.computeWorldMatrix(true);
  18599. return this;
  18600. };
  18601. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18602. /**
  18603. * True if the World matrix has been frozen.
  18604. * Returns a boolean.
  18605. */
  18606. get: function () {
  18607. return this._isWorldMatrixFrozen;
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. /**
  18613. * Retuns the mesh absolute position in the World.
  18614. * Returns a Vector3.
  18615. */
  18616. TransformNode.prototype.getAbsolutePosition = function () {
  18617. this.computeWorldMatrix();
  18618. return this._absolutePosition;
  18619. };
  18620. /**
  18621. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18622. * Returns the TransformNode.
  18623. */
  18624. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18625. if (!absolutePosition) {
  18626. return this;
  18627. }
  18628. var absolutePositionX;
  18629. var absolutePositionY;
  18630. var absolutePositionZ;
  18631. if (absolutePosition.x === undefined) {
  18632. if (arguments.length < 3) {
  18633. return this;
  18634. }
  18635. absolutePositionX = arguments[0];
  18636. absolutePositionY = arguments[1];
  18637. absolutePositionZ = arguments[2];
  18638. }
  18639. else {
  18640. absolutePositionX = absolutePosition.x;
  18641. absolutePositionY = absolutePosition.y;
  18642. absolutePositionZ = absolutePosition.z;
  18643. }
  18644. if (this.parent) {
  18645. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18646. invertParentWorldMatrix.invert();
  18647. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18648. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18649. }
  18650. else {
  18651. this.position.x = absolutePositionX;
  18652. this.position.y = absolutePositionY;
  18653. this.position.z = absolutePositionZ;
  18654. }
  18655. return this;
  18656. };
  18657. /**
  18658. * Sets the mesh position in its local space.
  18659. * Returns the TransformNode.
  18660. */
  18661. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18662. this.computeWorldMatrix();
  18663. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18664. return this;
  18665. };
  18666. /**
  18667. * Returns the mesh position in the local space from the current World matrix values.
  18668. * Returns a new Vector3.
  18669. */
  18670. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18671. this.computeWorldMatrix();
  18672. var invLocalWorldMatrix = this._localWorld.clone();
  18673. invLocalWorldMatrix.invert();
  18674. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18675. };
  18676. /**
  18677. * Translates the mesh along the passed Vector3 in its local space.
  18678. * Returns the TransformNode.
  18679. */
  18680. TransformNode.prototype.locallyTranslate = function (vector3) {
  18681. this.computeWorldMatrix(true);
  18682. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18683. return this;
  18684. };
  18685. /**
  18686. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18687. * @param targetPoint the position (must be in same space as current mesh) to look at
  18688. * @param yawCor optional yaw (y-axis) correction in radians
  18689. * @param pitchCor optional pitch (x-axis) correction in radians
  18690. * @param rollCor optional roll (z-axis) correction in radians
  18691. * @param space the choosen space of the target
  18692. * @returns the TransformNode.
  18693. */
  18694. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18695. if (yawCor === void 0) { yawCor = 0; }
  18696. if (pitchCor === void 0) { pitchCor = 0; }
  18697. if (rollCor === void 0) { rollCor = 0; }
  18698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18699. var dv = TransformNode._lookAtVectorCache;
  18700. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18701. targetPoint.subtractToRef(pos, dv);
  18702. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18703. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18704. var pitch = Math.atan2(dv.y, len);
  18705. if (this.rotationQuaternion) {
  18706. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18707. }
  18708. else {
  18709. this.rotation.x = pitch + pitchCor;
  18710. this.rotation.y = yaw + yawCor;
  18711. this.rotation.z = rollCor;
  18712. }
  18713. return this;
  18714. };
  18715. /**
  18716. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18717. * This Vector3 is expressed in the World space.
  18718. */
  18719. TransformNode.prototype.getDirection = function (localAxis) {
  18720. var result = BABYLON.Vector3.Zero();
  18721. this.getDirectionToRef(localAxis, result);
  18722. return result;
  18723. };
  18724. /**
  18725. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18726. * localAxis is expressed in the mesh local space.
  18727. * result is computed in the Wordl space from the mesh World matrix.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18731. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18732. return this;
  18733. };
  18734. /**
  18735. * Sets a new pivot point to the current node
  18736. * @param point defines the new pivot point to use
  18737. * @param space defines if the point is in world or local space (local by default)
  18738. * @returns the current TransformNode
  18739. */
  18740. TransformNode.prototype.setPivotPoint = function (point, space) {
  18741. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18742. if (this.getScene().getRenderId() == 0) {
  18743. this.computeWorldMatrix(true);
  18744. }
  18745. var wm = this.getWorldMatrix();
  18746. if (space == BABYLON.Space.WORLD) {
  18747. var tmat = BABYLON.Tmp.Matrix[0];
  18748. wm.invertToRef(tmat);
  18749. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18750. }
  18751. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18752. };
  18753. /**
  18754. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18755. */
  18756. TransformNode.prototype.getPivotPoint = function () {
  18757. var point = BABYLON.Vector3.Zero();
  18758. this.getPivotPointToRef(point);
  18759. return point;
  18760. };
  18761. /**
  18762. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18763. * Returns the TransformNode.
  18764. */
  18765. TransformNode.prototype.getPivotPointToRef = function (result) {
  18766. result.x = -this._pivotMatrix.m[12];
  18767. result.y = -this._pivotMatrix.m[13];
  18768. result.z = -this._pivotMatrix.m[14];
  18769. return this;
  18770. };
  18771. /**
  18772. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18773. */
  18774. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18775. var point = BABYLON.Vector3.Zero();
  18776. this.getAbsolutePivotPointToRef(point);
  18777. return point;
  18778. };
  18779. /**
  18780. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18781. * Returns the TransformNode.
  18782. */
  18783. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18784. result.x = this._pivotMatrix.m[12];
  18785. result.y = this._pivotMatrix.m[13];
  18786. result.z = this._pivotMatrix.m[14];
  18787. this.getPivotPointToRef(result);
  18788. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18789. return this;
  18790. };
  18791. /**
  18792. * Defines the passed node as the parent of the current node.
  18793. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18794. * Returns the TransformNode.
  18795. */
  18796. TransformNode.prototype.setParent = function (node) {
  18797. if (node === null) {
  18798. var rotation = BABYLON.Tmp.Quaternion[0];
  18799. var position = BABYLON.Tmp.Vector3[0];
  18800. var scale = BABYLON.Tmp.Vector3[1];
  18801. if (this.parent && this.parent.computeWorldMatrix) {
  18802. this.parent.computeWorldMatrix(true);
  18803. }
  18804. this.computeWorldMatrix(true);
  18805. this.getWorldMatrix().decompose(scale, rotation, position);
  18806. if (this.rotationQuaternion) {
  18807. this.rotationQuaternion.copyFrom(rotation);
  18808. }
  18809. else {
  18810. rotation.toEulerAnglesToRef(this.rotation);
  18811. }
  18812. this.scaling.x = scale.x;
  18813. this.scaling.y = scale.y;
  18814. this.scaling.z = scale.z;
  18815. this.position.x = position.x;
  18816. this.position.y = position.y;
  18817. this.position.z = position.z;
  18818. }
  18819. else {
  18820. var rotation = BABYLON.Tmp.Quaternion[0];
  18821. var position = BABYLON.Tmp.Vector3[0];
  18822. var scale = BABYLON.Tmp.Vector3[1];
  18823. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18824. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18825. this.computeWorldMatrix(true);
  18826. node.computeWorldMatrix(true);
  18827. node.getWorldMatrix().invertToRef(invParentMatrix);
  18828. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18829. diffMatrix.decompose(scale, rotation, position);
  18830. if (this.rotationQuaternion) {
  18831. this.rotationQuaternion.copyFrom(rotation);
  18832. }
  18833. else {
  18834. rotation.toEulerAnglesToRef(this.rotation);
  18835. }
  18836. this.position.x = position.x;
  18837. this.position.y = position.y;
  18838. this.position.z = position.z;
  18839. this.scaling.x = scale.x;
  18840. this.scaling.y = scale.y;
  18841. this.scaling.z = scale.z;
  18842. }
  18843. this.parent = node;
  18844. return this;
  18845. };
  18846. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18847. get: function () {
  18848. return this._nonUniformScaling;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18854. if (this._nonUniformScaling === value) {
  18855. return false;
  18856. }
  18857. this._nonUniformScaling = true;
  18858. return true;
  18859. };
  18860. /**
  18861. * Attach the current TransformNode to another TransformNode associated with a bone
  18862. * @param bone Bone affecting the TransformNode
  18863. * @param affectedTransformNode TransformNode associated with the bone
  18864. */
  18865. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18866. this._transformToBoneReferal = affectedTransformNode;
  18867. this.parent = bone;
  18868. if (bone.getWorldMatrix().determinant() < 0) {
  18869. this.scalingDeterminant *= -1;
  18870. }
  18871. return this;
  18872. };
  18873. TransformNode.prototype.detachFromBone = function () {
  18874. if (!this.parent) {
  18875. return this;
  18876. }
  18877. if (this.parent.getWorldMatrix().determinant() < 0) {
  18878. this.scalingDeterminant *= -1;
  18879. }
  18880. this._transformToBoneReferal = null;
  18881. this.parent = null;
  18882. return this;
  18883. };
  18884. /**
  18885. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18886. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18887. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18888. * The passed axis is also normalized.
  18889. * Returns the TransformNode.
  18890. */
  18891. TransformNode.prototype.rotate = function (axis, amount, space) {
  18892. axis.normalize();
  18893. if (!this.rotationQuaternion) {
  18894. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18895. this.rotation = BABYLON.Vector3.Zero();
  18896. }
  18897. var rotationQuaternion;
  18898. if (!space || space === BABYLON.Space.LOCAL) {
  18899. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18900. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18901. }
  18902. else {
  18903. if (this.parent) {
  18904. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18905. invertParentWorldMatrix.invert();
  18906. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18907. }
  18908. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18909. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18915. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18916. * The passed axis is also normalized.
  18917. * Returns the TransformNode.
  18918. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18919. */
  18920. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18921. axis.normalize();
  18922. if (!this.rotationQuaternion) {
  18923. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18924. this.rotation.copyFromFloats(0, 0, 0);
  18925. }
  18926. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18927. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18928. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18929. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18930. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18931. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18932. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18933. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18934. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18935. return this;
  18936. };
  18937. /**
  18938. * Translates the mesh along the axis vector for the passed distance in the given space.
  18939. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18940. * Returns the TransformNode.
  18941. */
  18942. TransformNode.prototype.translate = function (axis, distance, space) {
  18943. var displacementVector = axis.scale(distance);
  18944. if (!space || space === BABYLON.Space.LOCAL) {
  18945. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18946. this.setPositionWithLocalVector(tempV3);
  18947. }
  18948. else {
  18949. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18950. }
  18951. return this;
  18952. };
  18953. /**
  18954. * Adds a rotation step to the mesh current rotation.
  18955. * x, y, z are Euler angles expressed in radians.
  18956. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18957. * This means this rotation is made in the mesh local space only.
  18958. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18959. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18960. * ```javascript
  18961. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18962. * ```
  18963. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18964. * 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.
  18965. * Returns the TransformNode.
  18966. */
  18967. TransformNode.prototype.addRotation = function (x, y, z) {
  18968. var rotationQuaternion;
  18969. if (this.rotationQuaternion) {
  18970. rotationQuaternion = this.rotationQuaternion;
  18971. }
  18972. else {
  18973. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18974. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18975. }
  18976. var accumulation = BABYLON.Tmp.Quaternion[0];
  18977. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18978. rotationQuaternion.multiplyInPlace(accumulation);
  18979. if (!this.rotationQuaternion) {
  18980. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18981. }
  18982. return this;
  18983. };
  18984. /**
  18985. * Computes the mesh World matrix and returns it.
  18986. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18987. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18988. * If the parameter `force`is set to `true`, the actual computation is done.
  18989. * Returns the mesh World Matrix.
  18990. */
  18991. TransformNode.prototype.computeWorldMatrix = function (force) {
  18992. if (this._isWorldMatrixFrozen) {
  18993. return this._worldMatrix;
  18994. }
  18995. if (!force && this.isSynchronized(true)) {
  18996. this._currentRenderId = this.getScene().getRenderId();
  18997. return this._worldMatrix;
  18998. }
  18999. this._cache.position.copyFrom(this.position);
  19000. this._cache.scaling.copyFrom(this.scaling);
  19001. this._cache.pivotMatrixUpdated = false;
  19002. this._cache.billboardMode = this.billboardMode;
  19003. this._currentRenderId = this.getScene().getRenderId();
  19004. this._childRenderId = this.getScene().getRenderId();
  19005. this._isDirty = false;
  19006. // Scaling
  19007. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19008. // Rotation
  19009. //rotate, if quaternion is set and rotation was used
  19010. if (this.rotationQuaternion) {
  19011. var len = this.rotation.length();
  19012. if (len) {
  19013. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19014. this.rotation.copyFromFloats(0, 0, 0);
  19015. }
  19016. }
  19017. if (this.rotationQuaternion) {
  19018. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19019. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19020. }
  19021. else {
  19022. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19023. this._cache.rotation.copyFrom(this.rotation);
  19024. }
  19025. // Translation
  19026. var camera = this.getScene().activeCamera;
  19027. if (this.infiniteDistance && !this.parent && camera) {
  19028. var cameraWorldMatrix = camera.getWorldMatrix();
  19029. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19030. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19031. }
  19032. else {
  19033. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19034. }
  19035. // Composing transformations
  19036. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19037. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19038. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19039. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19040. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19041. // Need to decompose each rotation here
  19042. var currentPosition = BABYLON.Tmp.Vector3[3];
  19043. if (this.parent && this.parent.getWorldMatrix) {
  19044. if (this._transformToBoneReferal) {
  19045. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19046. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19047. }
  19048. else {
  19049. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19050. }
  19051. }
  19052. else {
  19053. currentPosition.copyFrom(this.position);
  19054. }
  19055. currentPosition.subtractInPlace(camera.globalPosition);
  19056. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19057. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19058. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19059. }
  19060. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19061. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19062. }
  19063. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19064. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19065. }
  19066. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19067. }
  19068. else {
  19069. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19070. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19071. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19072. }
  19073. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19074. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19075. }
  19076. // Local world
  19077. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19078. // Parent
  19079. if (this.parent && this.parent.getWorldMatrix) {
  19080. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19081. if (this._transformToBoneReferal) {
  19082. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19083. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19084. }
  19085. else {
  19086. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19087. }
  19088. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19089. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19090. this._worldMatrix.copyFrom(this._localWorld);
  19091. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19092. }
  19093. else {
  19094. if (this._transformToBoneReferal) {
  19095. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19096. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19097. }
  19098. else {
  19099. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19100. }
  19101. }
  19102. this._markSyncedWithParent();
  19103. }
  19104. else {
  19105. this._worldMatrix.copyFrom(this._localWorld);
  19106. }
  19107. // Post multiply inverse of pivotMatrix
  19108. if (this._postMultiplyPivotMatrix) {
  19109. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19110. }
  19111. // Normal matrix
  19112. if (this.scaling.isNonUniform) {
  19113. this._updateNonUniformScalingState(true);
  19114. }
  19115. else if (this.parent && this.parent._nonUniformScaling) {
  19116. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19117. }
  19118. else {
  19119. this._updateNonUniformScalingState(false);
  19120. }
  19121. this._afterComputeWorldMatrix();
  19122. // Absolute position
  19123. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19124. // Callbacks
  19125. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19126. if (!this._poseMatrix) {
  19127. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19128. }
  19129. // Cache the determinant
  19130. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19131. return this._worldMatrix;
  19132. };
  19133. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19134. };
  19135. /**
  19136. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19137. * @param func: callback function to add
  19138. *
  19139. * Returns the TransformNode.
  19140. */
  19141. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19142. this.onAfterWorldMatrixUpdateObservable.add(func);
  19143. return this;
  19144. };
  19145. /**
  19146. * Removes a registered callback function.
  19147. * Returns the TransformNode.
  19148. */
  19149. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19150. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19151. return this;
  19152. };
  19153. /**
  19154. * Clone the current transform node
  19155. * Returns the new transform node
  19156. * @param name Name of the new clone
  19157. * @param newParent New parent for the clone
  19158. * @param doNotCloneChildren Do not clone children hierarchy
  19159. */
  19160. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19161. var _this = this;
  19162. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19163. result.name = name;
  19164. result.id = name;
  19165. if (newParent) {
  19166. result.parent = newParent;
  19167. }
  19168. if (!doNotCloneChildren) {
  19169. // Children
  19170. var directDescendants = this.getDescendants(true);
  19171. for (var index = 0; index < directDescendants.length; index++) {
  19172. var child = directDescendants[index];
  19173. if (child.clone) {
  19174. child.clone(name + "." + child.name, result);
  19175. }
  19176. }
  19177. }
  19178. return result;
  19179. };
  19180. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19181. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19182. serializationObject.type = this.getClassName();
  19183. // Parent
  19184. if (this.parent) {
  19185. serializationObject.parentId = this.parent.id;
  19186. }
  19187. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19188. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19189. }
  19190. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19191. serializationObject.isEnabled = this.isEnabled();
  19192. // Parent
  19193. if (this.parent) {
  19194. serializationObject.parentId = this.parent.id;
  19195. }
  19196. return serializationObject;
  19197. };
  19198. // Statics
  19199. /**
  19200. * Returns a new TransformNode object parsed from the source provided.
  19201. * The parameter `parsedMesh` is the source.
  19202. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19203. */
  19204. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19205. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19206. if (BABYLON.Tags) {
  19207. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19208. }
  19209. if (parsedTransformNode.localMatrix) {
  19210. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19211. }
  19212. else if (parsedTransformNode.pivotMatrix) {
  19213. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19214. }
  19215. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19216. // Parent
  19217. if (parsedTransformNode.parentId) {
  19218. transformNode._waitingParentId = parsedTransformNode.parentId;
  19219. }
  19220. return transformNode;
  19221. };
  19222. /**
  19223. * Releases resources associated with this transform node.
  19224. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19225. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19226. */
  19227. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19228. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19229. // Animations
  19230. this.getScene().stopAnimation(this);
  19231. // Remove from scene
  19232. this.getScene().removeTransformNode(this);
  19233. this.onAfterWorldMatrixUpdateObservable.clear();
  19234. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19235. };
  19236. // Statics
  19237. TransformNode.BILLBOARDMODE_NONE = 0;
  19238. TransformNode.BILLBOARDMODE_X = 1;
  19239. TransformNode.BILLBOARDMODE_Y = 2;
  19240. TransformNode.BILLBOARDMODE_Z = 4;
  19241. TransformNode.BILLBOARDMODE_ALL = 7;
  19242. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19243. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19244. __decorate([
  19245. BABYLON.serializeAsVector3()
  19246. ], TransformNode.prototype, "_rotation", void 0);
  19247. __decorate([
  19248. BABYLON.serializeAsQuaternion()
  19249. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19250. __decorate([
  19251. BABYLON.serializeAsVector3()
  19252. ], TransformNode.prototype, "_scaling", void 0);
  19253. __decorate([
  19254. BABYLON.serialize()
  19255. ], TransformNode.prototype, "billboardMode", void 0);
  19256. __decorate([
  19257. BABYLON.serialize()
  19258. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19259. __decorate([
  19260. BABYLON.serialize()
  19261. ], TransformNode.prototype, "infiniteDistance", void 0);
  19262. __decorate([
  19263. BABYLON.serializeAsVector3()
  19264. ], TransformNode.prototype, "position", void 0);
  19265. return TransformNode;
  19266. }(BABYLON.Node));
  19267. BABYLON.TransformNode = TransformNode;
  19268. })(BABYLON || (BABYLON = {}));
  19269. //# sourceMappingURL=babylon.transformNode.js.map
  19270. var BABYLON;
  19271. (function (BABYLON) {
  19272. /**
  19273. * Class used to store all common mesh properties
  19274. */
  19275. var AbstractMesh = /** @class */ (function (_super) {
  19276. __extends(AbstractMesh, _super);
  19277. // Constructor
  19278. /**
  19279. * Creates a new AbstractMesh
  19280. * @param name defines the name of the mesh
  19281. * @param scene defines the hosting scene
  19282. */
  19283. function AbstractMesh(name, scene) {
  19284. if (scene === void 0) { scene = null; }
  19285. var _this = _super.call(this, name, scene, false) || this;
  19286. _this._facetNb = 0; // facet number
  19287. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19288. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19289. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19290. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19291. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19292. _this._subDiv = {
  19293. max: 1,
  19294. X: 1,
  19295. Y: 1,
  19296. Z: 1
  19297. };
  19298. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19299. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19300. // Events
  19301. /**
  19302. * An event triggered when this mesh collides with another one
  19303. */
  19304. _this.onCollideObservable = new BABYLON.Observable();
  19305. /**
  19306. * An event triggered when the collision's position changes
  19307. */
  19308. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19309. /**
  19310. * An event triggered when material is changed
  19311. */
  19312. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19313. // Properties
  19314. /**
  19315. * Gets or sets the orientation for POV movement & rotation
  19316. */
  19317. _this.definedFacingForward = true;
  19318. /**
  19319. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19320. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19321. * * 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.
  19322. * @see http://doc.babylonjs.com/features/occlusionquery
  19323. */
  19324. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19325. /**
  19326. * 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:
  19327. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19328. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19329. * * 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.
  19330. * @see http://doc.babylonjs.com/features/occlusionquery
  19331. */
  19332. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19333. /**
  19334. * 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.
  19335. * The default value is -1 which means don't break the query and wait till the result
  19336. * @see http://doc.babylonjs.com/features/occlusionquery
  19337. */
  19338. _this.occlusionRetryCount = -1;
  19339. _this._occlusionInternalRetryCounter = 0;
  19340. _this._isOccluded = false;
  19341. _this._isOcclusionQueryInProgress = false;
  19342. _this._visibility = 1.0;
  19343. /** Gets or sets the alpha index used to sort transparent meshes
  19344. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19345. */
  19346. _this.alphaIndex = Number.MAX_VALUE;
  19347. /**
  19348. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19349. */
  19350. _this.isVisible = true;
  19351. /**
  19352. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19353. */
  19354. _this.isPickable = true;
  19355. /**
  19356. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19357. */
  19358. _this.showBoundingBox = false;
  19359. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19360. _this.showSubMeshesBoundingBox = false;
  19361. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19362. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19363. */
  19364. _this.isBlocker = false;
  19365. /**
  19366. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19367. */
  19368. _this.enablePointerMoveEvents = false;
  19369. /**
  19370. * Specifies the rendering group id for this mesh (0 by default)
  19371. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19372. */
  19373. _this.renderingGroupId = 0;
  19374. _this._receiveShadows = false;
  19375. /**
  19376. * Gets or sets a boolean indicating if the outline must be rendered as well
  19377. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19378. */
  19379. _this.renderOutline = false;
  19380. /** Defines color to use when rendering outline */
  19381. _this.outlineColor = BABYLON.Color3.Red();
  19382. /** Define width to use when rendering outline */
  19383. _this.outlineWidth = 0.02;
  19384. /**
  19385. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19386. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19387. */
  19388. _this.renderOverlay = false;
  19389. /** Defines color to use when rendering overlay */
  19390. _this.overlayColor = BABYLON.Color3.Red();
  19391. /** Defines alpha to use when rendering overlay */
  19392. _this.overlayAlpha = 0.5;
  19393. _this._hasVertexAlpha = false;
  19394. _this._useVertexColors = true;
  19395. _this._computeBonesUsingShaders = true;
  19396. _this._numBoneInfluencers = 4;
  19397. _this._applyFog = true;
  19398. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19399. _this.useOctreeForRenderingSelection = true;
  19400. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19401. _this.useOctreeForPicking = true;
  19402. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19403. _this.useOctreeForCollisions = true;
  19404. _this._layerMask = 0x0FFFFFFF;
  19405. /**
  19406. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19407. */
  19408. _this.alwaysSelectAsActiveMesh = false;
  19409. /**
  19410. * Gets or sets the current action manager
  19411. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19412. */
  19413. _this.actionManager = null;
  19414. /**
  19415. * Gets or sets impostor used for physic simulation
  19416. * @see http://doc.babylonjs.com/features/physics_engine
  19417. */
  19418. _this.physicsImpostor = null;
  19419. // Collisions
  19420. _this._checkCollisions = false;
  19421. _this._collisionMask = -1;
  19422. _this._collisionGroup = -1;
  19423. /**
  19424. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19425. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19426. */
  19427. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19428. /**
  19429. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19430. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19431. */
  19432. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19433. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19434. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19435. // Edges
  19436. /**
  19437. * Defines edge width used when edgesRenderer is enabled
  19438. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19439. */
  19440. _this.edgesWidth = 1;
  19441. /**
  19442. * Defines edge color used when edgesRenderer is enabled
  19443. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19444. */
  19445. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19446. // Cache
  19447. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19448. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19449. /** @hidden */
  19450. _this._renderId = 0;
  19451. /** @hidden */
  19452. _this._intersectionsInProgress = new Array();
  19453. /** @hidden */
  19454. _this._unIndexed = false;
  19455. /** @hidden */
  19456. _this._lightSources = new Array();
  19457. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19458. if (collidedMesh === void 0) { collidedMesh = null; }
  19459. //TODO move this to the collision coordinator!
  19460. if (_this.getScene().workerCollisions)
  19461. newPosition.multiplyInPlace(_this._collider._radius);
  19462. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19463. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19464. _this.position.addInPlace(_this._diffPositionForCollisions);
  19465. }
  19466. if (collidedMesh) {
  19467. _this.onCollideObservable.notifyObservers(collidedMesh);
  19468. }
  19469. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19470. };
  19471. _this.getScene().addMesh(_this);
  19472. _this._resyncLightSources();
  19473. return _this;
  19474. }
  19475. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19476. /**
  19477. * No billboard
  19478. */
  19479. get: function () {
  19480. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19486. /** Billboard on X axis */
  19487. get: function () {
  19488. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19494. /** Billboard on Y axis */
  19495. get: function () {
  19496. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19502. /** Billboard on Z axis */
  19503. get: function () {
  19504. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19510. /** Billboard on all axes */
  19511. get: function () {
  19512. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19518. /**
  19519. * Gets the number of facets in the mesh
  19520. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19521. */
  19522. get: function () {
  19523. return this._facetNb;
  19524. },
  19525. enumerable: true,
  19526. configurable: true
  19527. });
  19528. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19529. /**
  19530. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19531. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19532. */
  19533. get: function () {
  19534. return this._partitioningSubdivisions;
  19535. },
  19536. set: function (nb) {
  19537. this._partitioningSubdivisions = nb;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19543. /**
  19544. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19545. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19547. */
  19548. get: function () {
  19549. return this._partitioningBBoxRatio;
  19550. },
  19551. set: function (ratio) {
  19552. this._partitioningBBoxRatio = ratio;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19558. /**
  19559. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19560. * Works only for updatable meshes.
  19561. * Doesn't work with multi-materials
  19562. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19563. */
  19564. get: function () {
  19565. return this._facetDepthSort;
  19566. },
  19567. set: function (sort) {
  19568. this._facetDepthSort = sort;
  19569. },
  19570. enumerable: true,
  19571. configurable: true
  19572. });
  19573. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19574. /**
  19575. * The location (Vector3) where the facet depth sort must be computed from.
  19576. * By default, the active camera position.
  19577. * Used only when facet depth sort is enabled
  19578. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19579. */
  19580. get: function () {
  19581. return this._facetDepthSortFrom;
  19582. },
  19583. set: function (location) {
  19584. this._facetDepthSortFrom = location;
  19585. },
  19586. enumerable: true,
  19587. configurable: true
  19588. });
  19589. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19590. /**
  19591. * gets a boolean indicating if facetData is enabled
  19592. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19593. */
  19594. get: function () {
  19595. return this._facetDataEnabled;
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. /** @hidden */
  19601. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19602. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19603. return false;
  19604. }
  19605. this._markSubMeshesAsMiscDirty();
  19606. return true;
  19607. };
  19608. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19609. /** Set a function to call when this mesh collides with another one */
  19610. set: function (callback) {
  19611. if (this._onCollideObserver) {
  19612. this.onCollideObservable.remove(this._onCollideObserver);
  19613. }
  19614. this._onCollideObserver = this.onCollideObservable.add(callback);
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19620. /** Set a function to call when the collision's position changes */
  19621. set: function (callback) {
  19622. if (this._onCollisionPositionChangeObserver) {
  19623. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19624. }
  19625. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19631. /**
  19632. * 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
  19633. * @see http://doc.babylonjs.com/features/occlusionquery
  19634. */
  19635. get: function () {
  19636. return this._isOccluded;
  19637. },
  19638. set: function (value) {
  19639. this._isOccluded = value;
  19640. },
  19641. enumerable: true,
  19642. configurable: true
  19643. });
  19644. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19645. /**
  19646. * Flag to check the progress status of the query
  19647. * @see http://doc.babylonjs.com/features/occlusionquery
  19648. */
  19649. get: function () {
  19650. return this._isOcclusionQueryInProgress;
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19656. /**
  19657. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19658. */
  19659. get: function () {
  19660. return this._visibility;
  19661. },
  19662. /**
  19663. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19664. */
  19665. set: function (value) {
  19666. if (this._visibility === value) {
  19667. return;
  19668. }
  19669. this._visibility = value;
  19670. this._markSubMeshesAsMiscDirty();
  19671. },
  19672. enumerable: true,
  19673. configurable: true
  19674. });
  19675. Object.defineProperty(AbstractMesh.prototype, "material", {
  19676. /** Gets or sets current material */
  19677. get: function () {
  19678. return this._material;
  19679. },
  19680. set: function (value) {
  19681. if (this._material === value) {
  19682. return;
  19683. }
  19684. this._material = value;
  19685. if (this.onMaterialChangedObservable.hasObservers) {
  19686. this.onMaterialChangedObservable.notifyObservers(this);
  19687. }
  19688. if (!this.subMeshes) {
  19689. return;
  19690. }
  19691. this._unBindEffect();
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19697. /**
  19698. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19699. * @see http://doc.babylonjs.com/babylon101/shadows
  19700. */
  19701. get: function () {
  19702. return this._receiveShadows;
  19703. },
  19704. set: function (value) {
  19705. if (this._receiveShadows === value) {
  19706. return;
  19707. }
  19708. this._receiveShadows = value;
  19709. this._markSubMeshesAsLightDirty();
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19715. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19716. get: function () {
  19717. return this._hasVertexAlpha;
  19718. },
  19719. set: function (value) {
  19720. if (this._hasVertexAlpha === value) {
  19721. return;
  19722. }
  19723. this._hasVertexAlpha = value;
  19724. this._markSubMeshesAsAttributesDirty();
  19725. this._markSubMeshesAsMiscDirty();
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19731. /** 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) */
  19732. get: function () {
  19733. return this._useVertexColors;
  19734. },
  19735. set: function (value) {
  19736. if (this._useVertexColors === value) {
  19737. return;
  19738. }
  19739. this._useVertexColors = value;
  19740. this._markSubMeshesAsAttributesDirty();
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19746. /**
  19747. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19748. */
  19749. get: function () {
  19750. return this._computeBonesUsingShaders;
  19751. },
  19752. set: function (value) {
  19753. if (this._computeBonesUsingShaders === value) {
  19754. return;
  19755. }
  19756. this._computeBonesUsingShaders = value;
  19757. this._markSubMeshesAsAttributesDirty();
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19763. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19764. get: function () {
  19765. return this._numBoneInfluencers;
  19766. },
  19767. set: function (value) {
  19768. if (this._numBoneInfluencers === value) {
  19769. return;
  19770. }
  19771. this._numBoneInfluencers = value;
  19772. this._markSubMeshesAsAttributesDirty();
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19778. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19779. get: function () {
  19780. return this._applyFog;
  19781. },
  19782. set: function (value) {
  19783. if (this._applyFog === value) {
  19784. return;
  19785. }
  19786. this._applyFog = value;
  19787. this._markSubMeshesAsMiscDirty();
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19793. /**
  19794. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19795. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19796. */
  19797. get: function () {
  19798. return this._layerMask;
  19799. },
  19800. set: function (value) {
  19801. if (value === this._layerMask) {
  19802. return;
  19803. }
  19804. this._layerMask = value;
  19805. this._resyncLightSources();
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19811. /**
  19812. * Gets or sets a collision mask used to mask collisions (default is -1).
  19813. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19814. */
  19815. get: function () {
  19816. return this._collisionMask;
  19817. },
  19818. set: function (mask) {
  19819. this._collisionMask = !isNaN(mask) ? mask : -1;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19825. /**
  19826. * Gets or sets the current collision group mask (-1 by default).
  19827. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19828. */
  19829. get: function () {
  19830. return this._collisionGroup;
  19831. },
  19832. set: function (mask) {
  19833. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19839. /** @hidden */
  19840. get: function () {
  19841. return null;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19847. get: function () {
  19848. return this._skeleton;
  19849. },
  19850. /**
  19851. * Gets or sets a skeleton to apply skining transformations
  19852. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19853. */
  19854. set: function (value) {
  19855. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19856. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19857. }
  19858. if (value && value.needInitialSkinMatrix) {
  19859. value._registerMeshWithPoseMatrix(this);
  19860. }
  19861. this._skeleton = value;
  19862. if (!this._skeleton) {
  19863. this._bonesTransformMatrices = null;
  19864. }
  19865. this._markSubMeshesAsAttributesDirty();
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. /**
  19871. * Returns the string "AbstractMesh"
  19872. * @returns "AbstractMesh"
  19873. */
  19874. AbstractMesh.prototype.getClassName = function () {
  19875. return "AbstractMesh";
  19876. };
  19877. /**
  19878. * Gets a string representation of the current mesh
  19879. * @param fullDetails defines a boolean indicating if full details must be included
  19880. * @returns a string representation of the current mesh
  19881. */
  19882. AbstractMesh.prototype.toString = function (fullDetails) {
  19883. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19884. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19885. if (this._skeleton) {
  19886. ret += ", skeleton: " + this._skeleton.name;
  19887. }
  19888. if (fullDetails) {
  19889. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19890. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19891. }
  19892. return ret;
  19893. };
  19894. /** @hidden */
  19895. AbstractMesh.prototype._rebuild = function () {
  19896. if (this._occlusionQuery) {
  19897. this._occlusionQuery = null;
  19898. }
  19899. if (this._edgesRenderer) {
  19900. this._edgesRenderer._rebuild();
  19901. }
  19902. if (!this.subMeshes) {
  19903. return;
  19904. }
  19905. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19906. var subMesh = _a[_i];
  19907. subMesh._rebuild();
  19908. }
  19909. };
  19910. /** @hidden */
  19911. AbstractMesh.prototype._resyncLightSources = function () {
  19912. this._lightSources.length = 0;
  19913. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19914. var light = _a[_i];
  19915. if (!light.isEnabled()) {
  19916. continue;
  19917. }
  19918. if (light.canAffectMesh(this)) {
  19919. this._lightSources.push(light);
  19920. }
  19921. }
  19922. this._markSubMeshesAsLightDirty();
  19923. };
  19924. /** @hidden */
  19925. AbstractMesh.prototype._resyncLighSource = function (light) {
  19926. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19927. var index = this._lightSources.indexOf(light);
  19928. if (index === -1) {
  19929. if (!isIn) {
  19930. return;
  19931. }
  19932. this._lightSources.push(light);
  19933. }
  19934. else {
  19935. if (isIn) {
  19936. return;
  19937. }
  19938. this._lightSources.splice(index, 1);
  19939. }
  19940. this._markSubMeshesAsLightDirty();
  19941. };
  19942. /** @hidden */
  19943. AbstractMesh.prototype._unBindEffect = function () {
  19944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19945. var subMesh = _a[_i];
  19946. subMesh.setEffect(null);
  19947. }
  19948. };
  19949. /** @hidden */
  19950. AbstractMesh.prototype._removeLightSource = function (light) {
  19951. var index = this._lightSources.indexOf(light);
  19952. if (index === -1) {
  19953. return;
  19954. }
  19955. this._lightSources.splice(index, 1);
  19956. this._markSubMeshesAsLightDirty();
  19957. };
  19958. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19959. if (!this.subMeshes) {
  19960. return;
  19961. }
  19962. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19963. var subMesh = _a[_i];
  19964. if (subMesh._materialDefines) {
  19965. func(subMesh._materialDefines);
  19966. }
  19967. }
  19968. };
  19969. /** @hidden */
  19970. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19971. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19972. };
  19973. /** @hidden */
  19974. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19975. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19976. };
  19977. /** @hidden */
  19978. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19979. if (!this.subMeshes) {
  19980. return;
  19981. }
  19982. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19983. var subMesh = _a[_i];
  19984. var material = subMesh.getMaterial();
  19985. if (material) {
  19986. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19987. }
  19988. }
  19989. };
  19990. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19991. /**
  19992. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19993. */
  19994. get: function () {
  19995. return this._scaling;
  19996. },
  19997. set: function (newScaling) {
  19998. this._scaling = newScaling;
  19999. if (this.physicsImpostor) {
  20000. this.physicsImpostor.forceUpdate();
  20001. }
  20002. },
  20003. enumerable: true,
  20004. configurable: true
  20005. });
  20006. // Methods
  20007. /**
  20008. * Disables the mesh edge rendering mode
  20009. * @returns the currentAbstractMesh
  20010. */
  20011. AbstractMesh.prototype.disableEdgesRendering = function () {
  20012. if (this._edgesRenderer) {
  20013. this._edgesRenderer.dispose();
  20014. this._edgesRenderer = null;
  20015. }
  20016. return this;
  20017. };
  20018. /**
  20019. * Enables the edge rendering mode on the mesh.
  20020. * This mode makes the mesh edges visible
  20021. * @param epsilon defines the maximal distance between two angles to detect a face
  20022. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20023. * @returns the currentAbstractMesh
  20024. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20025. */
  20026. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20027. if (epsilon === void 0) { epsilon = 0.95; }
  20028. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20029. this.disableEdgesRendering();
  20030. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20031. return this;
  20032. };
  20033. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20034. /**
  20035. * Returns true if the mesh is blocked. Implemented by child classes
  20036. */
  20037. get: function () {
  20038. return false;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. /**
  20044. * Returns the mesh itself by default. Implemented by child classes
  20045. * @param camera defines the camera to use to pick the right LOD level
  20046. * @returns the currentAbstractMesh
  20047. */
  20048. AbstractMesh.prototype.getLOD = function (camera) {
  20049. return this;
  20050. };
  20051. /**
  20052. * Returns 0 by default. Implemented by child classes
  20053. * @returns an integer
  20054. */
  20055. AbstractMesh.prototype.getTotalVertices = function () {
  20056. return 0;
  20057. };
  20058. /**
  20059. * Returns null by default. Implemented by child classes
  20060. * @returns null
  20061. */
  20062. AbstractMesh.prototype.getIndices = function () {
  20063. return null;
  20064. };
  20065. /**
  20066. * Returns the array of the requested vertex data kind. Implemented by child classes
  20067. * @param kind defines the vertex data kind to use
  20068. * @returns null
  20069. */
  20070. AbstractMesh.prototype.getVerticesData = function (kind) {
  20071. return null;
  20072. };
  20073. /**
  20074. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20075. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20076. * Note that a new underlying VertexBuffer object is created each call.
  20077. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20078. * @param kind defines vertex data kind:
  20079. * * BABYLON.VertexBuffer.PositionKind
  20080. * * BABYLON.VertexBuffer.UVKind
  20081. * * BABYLON.VertexBuffer.UV2Kind
  20082. * * BABYLON.VertexBuffer.UV3Kind
  20083. * * BABYLON.VertexBuffer.UV4Kind
  20084. * * BABYLON.VertexBuffer.UV5Kind
  20085. * * BABYLON.VertexBuffer.UV6Kind
  20086. * * BABYLON.VertexBuffer.ColorKind
  20087. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20088. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20089. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20090. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20091. * @param data defines the data source
  20092. * @param updatable defines if the data must be flagged as updatable (or static)
  20093. * @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
  20094. * @returns the current mesh
  20095. */
  20096. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20097. return this;
  20098. };
  20099. /**
  20100. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20101. * If the mesh has no geometry, it is simply returned as it is.
  20102. * @param kind defines vertex data kind:
  20103. * * BABYLON.VertexBuffer.PositionKind
  20104. * * BABYLON.VertexBuffer.UVKind
  20105. * * BABYLON.VertexBuffer.UV2Kind
  20106. * * BABYLON.VertexBuffer.UV3Kind
  20107. * * BABYLON.VertexBuffer.UV4Kind
  20108. * * BABYLON.VertexBuffer.UV5Kind
  20109. * * BABYLON.VertexBuffer.UV6Kind
  20110. * * BABYLON.VertexBuffer.ColorKind
  20111. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20112. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20113. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20114. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20115. * @param data defines the data source
  20116. * @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
  20117. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20118. * @returns the current mesh
  20119. */
  20120. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20121. return this;
  20122. };
  20123. /**
  20124. * Sets the mesh indices,
  20125. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20126. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20127. * @param totalVertices Defines the total number of vertices
  20128. * @returns the current mesh
  20129. */
  20130. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20131. return this;
  20132. };
  20133. /**
  20134. * Gets a boolean indicating if specific vertex data is present
  20135. * @param kind defines the vertex data kind to use
  20136. * @returns true is data kind is present
  20137. */
  20138. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20139. return false;
  20140. };
  20141. /**
  20142. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20143. * @returns a BoundingInfo
  20144. */
  20145. AbstractMesh.prototype.getBoundingInfo = function () {
  20146. if (this._masterMesh) {
  20147. return this._masterMesh.getBoundingInfo();
  20148. }
  20149. if (!this._boundingInfo) {
  20150. // this._boundingInfo is being created here
  20151. this._updateBoundingInfo();
  20152. }
  20153. // cannot be null.
  20154. return this._boundingInfo;
  20155. };
  20156. /**
  20157. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20158. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20159. * @returns the current mesh
  20160. */
  20161. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20162. if (includeDescendants === void 0) { includeDescendants = true; }
  20163. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20164. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20165. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20166. if (maxDimension === 0) {
  20167. return this;
  20168. }
  20169. var scale = 1 / maxDimension;
  20170. this.scaling.scaleInPlace(scale);
  20171. return this;
  20172. };
  20173. /**
  20174. * Overwrite the current bounding info
  20175. * @param boundingInfo defines the new bounding info
  20176. * @returns the current mesh
  20177. */
  20178. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20179. this._boundingInfo = boundingInfo;
  20180. return this;
  20181. };
  20182. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20183. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20184. get: function () {
  20185. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. /** @hidden */
  20191. AbstractMesh.prototype._preActivate = function () {
  20192. };
  20193. /** @hidden */
  20194. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20195. };
  20196. /** @hidden */
  20197. AbstractMesh.prototype._activate = function (renderId) {
  20198. this._renderId = renderId;
  20199. };
  20200. /**
  20201. * Gets the current world matrix
  20202. * @returns a Matrix
  20203. */
  20204. AbstractMesh.prototype.getWorldMatrix = function () {
  20205. if (this._masterMesh) {
  20206. return this._masterMesh.getWorldMatrix();
  20207. }
  20208. return _super.prototype.getWorldMatrix.call(this);
  20209. };
  20210. /** @hidden */
  20211. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20212. if (this._masterMesh) {
  20213. return this._masterMesh._getWorldMatrixDeterminant();
  20214. }
  20215. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20216. };
  20217. // ================================== Point of View Movement =================================
  20218. /**
  20219. * Perform relative position change from the point of view of behind the front of the mesh.
  20220. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20221. * Supports definition of mesh facing forward or backward
  20222. * @param amountRight defines the distance on the right axis
  20223. * @param amountUp defines the distance on the up axis
  20224. * @param amountForward defines the distance on the forward axis
  20225. * @returns the current mesh
  20226. */
  20227. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20228. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20229. return this;
  20230. };
  20231. /**
  20232. * Calculate relative position change from the point of view of behind the front of the mesh.
  20233. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20234. * Supports definition of mesh facing forward or backward
  20235. * @param amountRight defines the distance on the right axis
  20236. * @param amountUp defines the distance on the up axis
  20237. * @param amountForward defines the distance on the forward axis
  20238. * @returns the new displacement vector
  20239. */
  20240. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20241. var rotMatrix = new BABYLON.Matrix();
  20242. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20243. rotQuaternion.toRotationMatrix(rotMatrix);
  20244. var translationDelta = BABYLON.Vector3.Zero();
  20245. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20246. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20247. return translationDelta;
  20248. };
  20249. // ================================== Point of View Rotation =================================
  20250. /**
  20251. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20252. * Supports definition of mesh facing forward or backward
  20253. * @param flipBack defines the flip
  20254. * @param twirlClockwise defines the twirl
  20255. * @param tiltRight defines the tilt
  20256. * @returns the current mesh
  20257. */
  20258. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20259. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20260. return this;
  20261. };
  20262. /**
  20263. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20264. * Supports definition of mesh facing forward or backward.
  20265. * @param flipBack defines the flip
  20266. * @param twirlClockwise defines the twirl
  20267. * @param tiltRight defines the tilt
  20268. * @returns the new rotation vector
  20269. */
  20270. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20271. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20272. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20273. };
  20274. /**
  20275. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20276. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20277. * @returns the new bounding vectors
  20278. */
  20279. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20280. if (includeDescendants === void 0) { includeDescendants = true; }
  20281. // Ensures that all world matrix will be recomputed.
  20282. this.getScene().incrementRenderId();
  20283. this.computeWorldMatrix(true);
  20284. var min;
  20285. var max;
  20286. var boundingInfo = this.getBoundingInfo();
  20287. if (!this.subMeshes) {
  20288. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20289. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20290. }
  20291. else {
  20292. min = boundingInfo.boundingBox.minimumWorld;
  20293. max = boundingInfo.boundingBox.maximumWorld;
  20294. }
  20295. if (includeDescendants) {
  20296. var descendants = this.getDescendants(false);
  20297. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20298. var descendant = descendants_1[_i];
  20299. var childMesh = descendant;
  20300. childMesh.computeWorldMatrix(true);
  20301. //make sure we have the needed params to get mix and max
  20302. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20303. continue;
  20304. }
  20305. var childBoundingInfo = childMesh.getBoundingInfo();
  20306. var boundingBox = childBoundingInfo.boundingBox;
  20307. var minBox = boundingBox.minimumWorld;
  20308. var maxBox = boundingBox.maximumWorld;
  20309. BABYLON.Tools.CheckExtends(minBox, min, max);
  20310. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20311. }
  20312. }
  20313. return {
  20314. min: min,
  20315. max: max
  20316. };
  20317. };
  20318. /** @hidden */
  20319. AbstractMesh.prototype._updateBoundingInfo = function () {
  20320. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20321. this._boundingInfo.update(this.worldMatrixFromCache);
  20322. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20323. return this;
  20324. };
  20325. /** @hidden */
  20326. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20327. if (!this.subMeshes) {
  20328. return this;
  20329. }
  20330. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20331. var subMesh = this.subMeshes[subIndex];
  20332. if (!subMesh.IsGlobal) {
  20333. subMesh.updateBoundingInfo(matrix);
  20334. }
  20335. }
  20336. return this;
  20337. };
  20338. /** @hidden */
  20339. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20340. // Bounding info
  20341. this._updateBoundingInfo();
  20342. };
  20343. /**
  20344. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20345. * A mesh is in the frustum if its bounding box intersects the frustum
  20346. * @param frustumPlanes defines the frustum to test
  20347. * @returns true if the mesh is in the frustum planes
  20348. */
  20349. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20350. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20351. };
  20352. /**
  20353. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20354. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20355. * @param frustumPlanes defines the frustum to test
  20356. * @returns true if the mesh is completely in the frustum planes
  20357. */
  20358. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20359. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20360. };
  20361. /**
  20362. * True if the mesh intersects another mesh or a SolidParticle object
  20363. * @param mesh defines a target mesh or SolidParticle to test
  20364. * @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)
  20365. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20366. * @returns true if there is an intersection
  20367. */
  20368. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20369. if (precise === void 0) { precise = false; }
  20370. if (!this._boundingInfo || !mesh._boundingInfo) {
  20371. return false;
  20372. }
  20373. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20374. return true;
  20375. }
  20376. if (includeDescendants) {
  20377. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20378. var child = _a[_i];
  20379. if (child.intersectsMesh(mesh, precise, true)) {
  20380. return true;
  20381. }
  20382. }
  20383. }
  20384. return false;
  20385. };
  20386. /**
  20387. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20388. * @param point defines the point to test
  20389. * @returns true if there is an intersection
  20390. */
  20391. AbstractMesh.prototype.intersectsPoint = function (point) {
  20392. if (!this._boundingInfo) {
  20393. return false;
  20394. }
  20395. return this._boundingInfo.intersectsPoint(point);
  20396. };
  20397. /**
  20398. * Gets the current physics impostor
  20399. * @see http://doc.babylonjs.com/features/physics_engine
  20400. * @returns a physics impostor or null
  20401. */
  20402. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20403. return this.physicsImpostor;
  20404. };
  20405. /**
  20406. * Gets the position of the current mesh in camera space
  20407. * @param camera defines the camera to use
  20408. * @returns a position
  20409. */
  20410. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20411. if (camera === void 0) { camera = null; }
  20412. if (!camera) {
  20413. camera = this.getScene().activeCamera;
  20414. }
  20415. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20416. };
  20417. /**
  20418. * Returns the distance from the mesh to the active camera
  20419. * @param camera defines the camera to use
  20420. * @returns the distance
  20421. */
  20422. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20423. if (camera === void 0) { camera = null; }
  20424. if (!camera) {
  20425. camera = this.getScene().activeCamera;
  20426. }
  20427. return this.absolutePosition.subtract(camera.position).length();
  20428. };
  20429. /**
  20430. * Apply a physic impulse to the mesh
  20431. * @param force defines the force to apply
  20432. * @param contactPoint defines where to apply the force
  20433. * @returns the current mesh
  20434. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20435. */
  20436. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20437. if (!this.physicsImpostor) {
  20438. return this;
  20439. }
  20440. this.physicsImpostor.applyImpulse(force, contactPoint);
  20441. return this;
  20442. };
  20443. /**
  20444. * Creates a physic joint between two meshes
  20445. * @param otherMesh defines the other mesh to use
  20446. * @param pivot1 defines the pivot to use on this mesh
  20447. * @param pivot2 defines the pivot to use on the other mesh
  20448. * @param options defines additional options (can be plugin dependent)
  20449. * @returns the current mesh
  20450. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20451. */
  20452. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20453. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20454. return this;
  20455. }
  20456. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20457. mainPivot: pivot1,
  20458. connectedPivot: pivot2,
  20459. nativeParams: options
  20460. });
  20461. return this;
  20462. };
  20463. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20464. // Collisions
  20465. /**
  20466. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20467. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20468. */
  20469. get: function () {
  20470. return this._checkCollisions;
  20471. },
  20472. set: function (collisionEnabled) {
  20473. this._checkCollisions = collisionEnabled;
  20474. if (this.getScene().workerCollisions) {
  20475. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20476. }
  20477. },
  20478. enumerable: true,
  20479. configurable: true
  20480. });
  20481. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20482. /**
  20483. * Gets Collider object used to compute collisions (not physics)
  20484. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20485. */
  20486. get: function () {
  20487. return this._collider;
  20488. },
  20489. enumerable: true,
  20490. configurable: true
  20491. });
  20492. /**
  20493. * Move the mesh using collision engine
  20494. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20495. * @param displacement defines the requested displacement vector
  20496. * @returns the current mesh
  20497. */
  20498. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20499. var globalPosition = this.getAbsolutePosition();
  20500. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20501. if (!this._collider) {
  20502. this._collider = new BABYLON.Collider();
  20503. }
  20504. this._collider._radius = this.ellipsoid;
  20505. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20506. return this;
  20507. };
  20508. // Submeshes octree
  20509. /**
  20510. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20511. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20512. * @param maxCapacity defines the maximum size of each block (64 by default)
  20513. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20514. * @returns the new octree
  20515. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20516. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20517. */
  20518. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20519. if (maxCapacity === void 0) { maxCapacity = 64; }
  20520. if (maxDepth === void 0) { maxDepth = 2; }
  20521. if (!this._submeshesOctree) {
  20522. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20523. }
  20524. this.computeWorldMatrix(true);
  20525. var boundingInfo = this.getBoundingInfo();
  20526. // Update octree
  20527. var bbox = boundingInfo.boundingBox;
  20528. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20529. return this._submeshesOctree;
  20530. };
  20531. // Collisions
  20532. /** @hidden */
  20533. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20534. this._generatePointsArray();
  20535. if (!this._positions) {
  20536. return this;
  20537. }
  20538. // Transformation
  20539. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20540. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20541. subMesh._lastColliderWorldVertices = [];
  20542. subMesh._trianglePlanes = [];
  20543. var start = subMesh.verticesStart;
  20544. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20545. for (var i = start; i < end; i++) {
  20546. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20547. }
  20548. }
  20549. // Collide
  20550. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20551. if (collider.collisionFound) {
  20552. collider.collidedMesh = this;
  20553. }
  20554. return this;
  20555. };
  20556. /** @hidden */
  20557. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20558. var subMeshes;
  20559. var len;
  20560. // Octrees
  20561. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20562. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20563. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20564. len = intersections.length;
  20565. subMeshes = intersections.data;
  20566. }
  20567. else {
  20568. subMeshes = this.subMeshes;
  20569. len = subMeshes.length;
  20570. }
  20571. for (var index = 0; index < len; index++) {
  20572. var subMesh = subMeshes[index];
  20573. // Bounding test
  20574. if (len > 1 && !subMesh._checkCollision(collider))
  20575. continue;
  20576. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20577. }
  20578. return this;
  20579. };
  20580. /** @hidden */
  20581. AbstractMesh.prototype._checkCollision = function (collider) {
  20582. // Bounding box test
  20583. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20584. return this;
  20585. // Transformation matrix
  20586. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20587. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20588. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20589. return this;
  20590. };
  20591. // Picking
  20592. /** @hidden */
  20593. AbstractMesh.prototype._generatePointsArray = function () {
  20594. return false;
  20595. };
  20596. /**
  20597. * Checks if the passed Ray intersects with the mesh
  20598. * @param ray defines the ray to use
  20599. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20600. * @returns the picking info
  20601. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20602. */
  20603. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20604. var pickingInfo = new BABYLON.PickingInfo();
  20605. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20606. return pickingInfo;
  20607. }
  20608. if (!this._generatePointsArray()) {
  20609. return pickingInfo;
  20610. }
  20611. var intersectInfo = null;
  20612. // Octrees
  20613. var subMeshes;
  20614. var len;
  20615. if (this._submeshesOctree && this.useOctreeForPicking) {
  20616. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20617. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20618. len = intersections.length;
  20619. subMeshes = intersections.data;
  20620. }
  20621. else {
  20622. subMeshes = this.subMeshes;
  20623. len = subMeshes.length;
  20624. }
  20625. for (var index = 0; index < len; index++) {
  20626. var subMesh = subMeshes[index];
  20627. // Bounding test
  20628. if (len > 1 && !subMesh.canIntersects(ray))
  20629. continue;
  20630. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20631. if (currentIntersectInfo) {
  20632. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20633. intersectInfo = currentIntersectInfo;
  20634. intersectInfo.subMeshId = index;
  20635. if (fastCheck) {
  20636. break;
  20637. }
  20638. }
  20639. }
  20640. }
  20641. if (intersectInfo) {
  20642. // Get picked point
  20643. var world = this.getWorldMatrix();
  20644. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20645. var direction = ray.direction.clone();
  20646. direction = direction.scale(intersectInfo.distance);
  20647. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20648. var pickedPoint = worldOrigin.add(worldDirection);
  20649. // Return result
  20650. pickingInfo.hit = true;
  20651. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20652. pickingInfo.pickedPoint = pickedPoint;
  20653. pickingInfo.pickedMesh = this;
  20654. pickingInfo.bu = intersectInfo.bu || 0;
  20655. pickingInfo.bv = intersectInfo.bv || 0;
  20656. pickingInfo.faceId = intersectInfo.faceId;
  20657. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20658. return pickingInfo;
  20659. }
  20660. return pickingInfo;
  20661. };
  20662. /**
  20663. * Clones the current mesh
  20664. * @param name defines the mesh name
  20665. * @param newParent defines the new mesh parent
  20666. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20667. * @returns the new mesh
  20668. */
  20669. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20670. return null;
  20671. };
  20672. /**
  20673. * Disposes all the submeshes of the current meshnp
  20674. * @returns the current mesh
  20675. */
  20676. AbstractMesh.prototype.releaseSubMeshes = function () {
  20677. if (this.subMeshes) {
  20678. while (this.subMeshes.length) {
  20679. this.subMeshes[0].dispose();
  20680. }
  20681. }
  20682. else {
  20683. this.subMeshes = new Array();
  20684. }
  20685. return this;
  20686. };
  20687. /**
  20688. * Releases resources associated with this abstract mesh.
  20689. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20690. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20691. */
  20692. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20693. var _this = this;
  20694. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20695. var index;
  20696. // Smart Array Retainers.
  20697. this.getScene().freeActiveMeshes();
  20698. this.getScene().freeRenderingGroups();
  20699. // Action manager
  20700. if (this.actionManager !== undefined && this.actionManager !== null) {
  20701. this.actionManager.dispose();
  20702. this.actionManager = null;
  20703. }
  20704. // Skeleton
  20705. this._skeleton = null;
  20706. // Physics
  20707. if (this.physicsImpostor) {
  20708. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20709. }
  20710. // Intersections in progress
  20711. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20712. var other = this._intersectionsInProgress[index];
  20713. var pos = other._intersectionsInProgress.indexOf(this);
  20714. other._intersectionsInProgress.splice(pos, 1);
  20715. }
  20716. this._intersectionsInProgress = [];
  20717. // Lights
  20718. var lights = this.getScene().lights;
  20719. lights.forEach(function (light) {
  20720. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20721. if (meshIndex !== -1) {
  20722. light.includedOnlyMeshes.splice(meshIndex, 1);
  20723. }
  20724. meshIndex = light.excludedMeshes.indexOf(_this);
  20725. if (meshIndex !== -1) {
  20726. light.excludedMeshes.splice(meshIndex, 1);
  20727. }
  20728. // Shadow generators
  20729. var generator = light.getShadowGenerator();
  20730. if (generator) {
  20731. var shadowMap = generator.getShadowMap();
  20732. if (shadowMap && shadowMap.renderList) {
  20733. meshIndex = shadowMap.renderList.indexOf(_this);
  20734. if (meshIndex !== -1) {
  20735. shadowMap.renderList.splice(meshIndex, 1);
  20736. }
  20737. }
  20738. }
  20739. });
  20740. // Edges
  20741. if (this._edgesRenderer) {
  20742. this._edgesRenderer.dispose();
  20743. this._edgesRenderer = null;
  20744. }
  20745. // SubMeshes
  20746. if (this.getClassName() !== "InstancedMesh") {
  20747. this.releaseSubMeshes();
  20748. }
  20749. // Octree
  20750. var sceneOctree = this.getScene().selectionOctree;
  20751. if (sceneOctree !== undefined && sceneOctree !== null) {
  20752. var index = sceneOctree.dynamicContent.indexOf(this);
  20753. if (index !== -1) {
  20754. sceneOctree.dynamicContent.splice(index, 1);
  20755. }
  20756. }
  20757. // Query
  20758. var engine = this.getScene().getEngine();
  20759. if (this._occlusionQuery) {
  20760. this._isOcclusionQueryInProgress = false;
  20761. engine.deleteQuery(this._occlusionQuery);
  20762. this._occlusionQuery = null;
  20763. }
  20764. // Engine
  20765. engine.wipeCaches();
  20766. // Remove from scene
  20767. this.getScene().removeMesh(this);
  20768. if (disposeMaterialAndTextures) {
  20769. if (this.material) {
  20770. this.material.dispose(false, true);
  20771. }
  20772. }
  20773. if (!doNotRecurse) {
  20774. // Particles
  20775. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20776. if (this.getScene().particleSystems[index].emitter === this) {
  20777. this.getScene().particleSystems[index].dispose();
  20778. index--;
  20779. }
  20780. }
  20781. }
  20782. // facet data
  20783. if (this._facetDataEnabled) {
  20784. this.disableFacetData();
  20785. }
  20786. this.onAfterWorldMatrixUpdateObservable.clear();
  20787. this.onCollideObservable.clear();
  20788. this.onCollisionPositionChangeObservable.clear();
  20789. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20790. };
  20791. /**
  20792. * Adds the passed mesh as a child to the current mesh
  20793. * @param mesh defines the child mesh
  20794. * @returns the current mesh
  20795. */
  20796. AbstractMesh.prototype.addChild = function (mesh) {
  20797. mesh.setParent(this);
  20798. return this;
  20799. };
  20800. /**
  20801. * Removes the passed mesh from the current mesh children list
  20802. * @param mesh defines the child mesh
  20803. * @returns the current mesh
  20804. */
  20805. AbstractMesh.prototype.removeChild = function (mesh) {
  20806. mesh.setParent(null);
  20807. return this;
  20808. };
  20809. // Facet data
  20810. /** @hidden */
  20811. AbstractMesh.prototype._initFacetData = function () {
  20812. if (!this._facetNormals) {
  20813. this._facetNormals = new Array();
  20814. }
  20815. if (!this._facetPositions) {
  20816. this._facetPositions = new Array();
  20817. }
  20818. if (!this._facetPartitioning) {
  20819. this._facetPartitioning = new Array();
  20820. }
  20821. this._facetNb = (this.getIndices().length / 3) | 0;
  20822. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20823. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20824. for (var f = 0; f < this._facetNb; f++) {
  20825. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20826. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20827. }
  20828. this._facetDataEnabled = true;
  20829. return this;
  20830. };
  20831. /**
  20832. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20833. * This method can be called within the render loop.
  20834. * 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
  20835. * @returns the current mesh
  20836. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20837. */
  20838. AbstractMesh.prototype.updateFacetData = function () {
  20839. if (!this._facetDataEnabled) {
  20840. this._initFacetData();
  20841. }
  20842. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20843. var indices = this.getIndices();
  20844. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20845. var bInfo = this.getBoundingInfo();
  20846. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20847. // init arrays, matrix and sort function on first call
  20848. this._facetDepthSortEnabled = true;
  20849. if (indices instanceof Uint16Array) {
  20850. this._depthSortedIndices = new Uint16Array(indices);
  20851. }
  20852. else if (indices instanceof Uint32Array) {
  20853. this._depthSortedIndices = new Uint32Array(indices);
  20854. }
  20855. else {
  20856. var needs32bits = false;
  20857. for (var i = 0; i < indices.length; i++) {
  20858. if (indices[i] > 65535) {
  20859. needs32bits = true;
  20860. break;
  20861. }
  20862. }
  20863. if (needs32bits) {
  20864. this._depthSortedIndices = new Uint32Array(indices);
  20865. }
  20866. else {
  20867. this._depthSortedIndices = new Uint16Array(indices);
  20868. }
  20869. }
  20870. this._facetDepthSortFunction = function (f1, f2) {
  20871. return (f2.sqDistance - f1.sqDistance);
  20872. };
  20873. if (!this._facetDepthSortFrom) {
  20874. var camera = this.getScene().activeCamera;
  20875. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20876. }
  20877. this._depthSortedFacets = [];
  20878. for (var f = 0; f < this._facetNb; f++) {
  20879. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20880. this._depthSortedFacets.push(depthSortedFacet);
  20881. }
  20882. this._invertedMatrix = BABYLON.Matrix.Identity();
  20883. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20884. }
  20885. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20886. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20887. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20888. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20889. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20890. this._subDiv.max = this._partitioningSubdivisions;
  20891. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20892. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20893. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20894. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20895. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20896. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20897. // set the parameters for ComputeNormals()
  20898. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20899. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20900. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20901. this._facetParameters.bInfo = bInfo;
  20902. this._facetParameters.bbSize = this._bbSize;
  20903. this._facetParameters.subDiv = this._subDiv;
  20904. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20905. this._facetParameters.depthSort = this._facetDepthSort;
  20906. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20907. this.computeWorldMatrix(true);
  20908. this._worldMatrix.invertToRef(this._invertedMatrix);
  20909. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20910. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20911. }
  20912. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20913. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20914. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20915. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20916. var l = (this._depthSortedIndices.length / 3) | 0;
  20917. for (var f = 0; f < l; f++) {
  20918. var sind = this._depthSortedFacets[f].ind;
  20919. this._depthSortedIndices[f * 3] = indices[sind];
  20920. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20921. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20922. }
  20923. this.updateIndices(this._depthSortedIndices);
  20924. }
  20925. return this;
  20926. };
  20927. /**
  20928. * Returns the facetLocalNormals array.
  20929. * The normals are expressed in the mesh local spac
  20930. * @returns an array of Vector3
  20931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20932. */
  20933. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20934. if (!this._facetNormals) {
  20935. this.updateFacetData();
  20936. }
  20937. return this._facetNormals;
  20938. };
  20939. /**
  20940. * Returns the facetLocalPositions array.
  20941. * The facet positions are expressed in the mesh local space
  20942. * @returns an array of Vector3
  20943. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20944. */
  20945. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20946. if (!this._facetPositions) {
  20947. this.updateFacetData();
  20948. }
  20949. return this._facetPositions;
  20950. };
  20951. /**
  20952. * Returns the facetLocalPartioning array
  20953. * @returns an array of array of numbers
  20954. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20955. */
  20956. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20957. if (!this._facetPartitioning) {
  20958. this.updateFacetData();
  20959. }
  20960. return this._facetPartitioning;
  20961. };
  20962. /**
  20963. * Returns the i-th facet position in the world system.
  20964. * This method allocates a new Vector3 per call
  20965. * @param i defines the facet index
  20966. * @returns a new Vector3
  20967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20968. */
  20969. AbstractMesh.prototype.getFacetPosition = function (i) {
  20970. var pos = BABYLON.Vector3.Zero();
  20971. this.getFacetPositionToRef(i, pos);
  20972. return pos;
  20973. };
  20974. /**
  20975. * Sets the reference Vector3 with the i-th facet position in the world system
  20976. * @param i defines the facet index
  20977. * @param ref defines the target vector
  20978. * @returns the current mesh
  20979. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20980. */
  20981. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20982. var localPos = (this.getFacetLocalPositions())[i];
  20983. var world = this.getWorldMatrix();
  20984. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20985. return this;
  20986. };
  20987. /**
  20988. * Returns the i-th facet normal in the world system.
  20989. * This method allocates a new Vector3 per call
  20990. * @param i defines the facet index
  20991. * @returns a new Vector3
  20992. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20993. */
  20994. AbstractMesh.prototype.getFacetNormal = function (i) {
  20995. var norm = BABYLON.Vector3.Zero();
  20996. this.getFacetNormalToRef(i, norm);
  20997. return norm;
  20998. };
  20999. /**
  21000. * Sets the reference Vector3 with the i-th facet normal in the world system
  21001. * @param i defines the facet index
  21002. * @param ref defines the target vector
  21003. * @returns the current mesh
  21004. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21005. */
  21006. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21007. var localNorm = (this.getFacetLocalNormals())[i];
  21008. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21009. return this;
  21010. };
  21011. /**
  21012. * 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)
  21013. * @param x defines x coordinate
  21014. * @param y defines y coordinate
  21015. * @param z defines z coordinate
  21016. * @returns the array of facet indexes
  21017. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21018. */
  21019. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21020. var bInfo = this.getBoundingInfo();
  21021. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21022. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21023. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21024. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21025. return null;
  21026. }
  21027. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21028. };
  21029. /**
  21030. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21031. * @param projected sets as the (x,y,z) world projection on the facet
  21032. * @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
  21033. * @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
  21034. * @param x defines x coordinate
  21035. * @param y defines y coordinate
  21036. * @param z defines z coordinate
  21037. * @returns the face index if found (or null instead)
  21038. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21039. */
  21040. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21041. if (checkFace === void 0) { checkFace = false; }
  21042. if (facing === void 0) { facing = true; }
  21043. var world = this.getWorldMatrix();
  21044. var invMat = BABYLON.Tmp.Matrix[5];
  21045. world.invertToRef(invMat);
  21046. var invVect = BABYLON.Tmp.Vector3[8];
  21047. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21048. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21049. if (projected) {
  21050. // tranform the local computed projected vector to world coordinates
  21051. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21052. }
  21053. return closest;
  21054. };
  21055. /**
  21056. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21057. * @param projected sets as the (x,y,z) local projection on the facet
  21058. * @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
  21059. * @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
  21060. * @param x defines x coordinate
  21061. * @param y defines y coordinate
  21062. * @param z defines z coordinate
  21063. * @returns the face index if found (or null instead)
  21064. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21065. */
  21066. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21067. if (checkFace === void 0) { checkFace = false; }
  21068. if (facing === void 0) { facing = true; }
  21069. var closest = null;
  21070. var tmpx = 0.0;
  21071. var tmpy = 0.0;
  21072. var tmpz = 0.0;
  21073. var d = 0.0; // tmp dot facet normal * facet position
  21074. var t0 = 0.0;
  21075. var projx = 0.0;
  21076. var projy = 0.0;
  21077. var projz = 0.0;
  21078. // Get all the facets in the same partitioning block than (x, y, z)
  21079. var facetPositions = this.getFacetLocalPositions();
  21080. var facetNormals = this.getFacetLocalNormals();
  21081. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21082. if (!facetsInBlock) {
  21083. return null;
  21084. }
  21085. // Get the closest facet to (x, y, z)
  21086. var shortest = Number.MAX_VALUE; // init distance vars
  21087. var tmpDistance = shortest;
  21088. var fib; // current facet in the block
  21089. var norm; // current facet normal
  21090. var p0; // current facet barycenter position
  21091. // loop on all the facets in the current partitioning block
  21092. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21093. fib = facetsInBlock[idx];
  21094. norm = facetNormals[fib];
  21095. p0 = facetPositions[fib];
  21096. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21097. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21098. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21099. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21100. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21101. projx = x + norm.x * t0;
  21102. projy = y + norm.y * t0;
  21103. projz = z + norm.z * t0;
  21104. tmpx = projx - x;
  21105. tmpy = projy - y;
  21106. tmpz = projz - z;
  21107. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21108. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21109. shortest = tmpDistance;
  21110. closest = fib;
  21111. if (projected) {
  21112. projected.x = projx;
  21113. projected.y = projy;
  21114. projected.z = projz;
  21115. }
  21116. }
  21117. }
  21118. }
  21119. return closest;
  21120. };
  21121. /**
  21122. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21123. * @returns the parameters
  21124. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21125. */
  21126. AbstractMesh.prototype.getFacetDataParameters = function () {
  21127. return this._facetParameters;
  21128. };
  21129. /**
  21130. * Disables the feature FacetData and frees the related memory
  21131. * @returns the current mesh
  21132. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21133. */
  21134. AbstractMesh.prototype.disableFacetData = function () {
  21135. if (this._facetDataEnabled) {
  21136. this._facetDataEnabled = false;
  21137. this._facetPositions = new Array();
  21138. this._facetNormals = new Array();
  21139. this._facetPartitioning = new Array();
  21140. this._facetParameters = null;
  21141. this._depthSortedIndices = new Uint32Array(0);
  21142. }
  21143. return this;
  21144. };
  21145. /**
  21146. * Updates the AbstractMesh indices array
  21147. * @param indices defines the data source
  21148. * @returns the current mesh
  21149. */
  21150. AbstractMesh.prototype.updateIndices = function (indices) {
  21151. return this;
  21152. };
  21153. /**
  21154. * Creates new normals data for the mesh
  21155. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21156. * @returns the current mesh
  21157. */
  21158. AbstractMesh.prototype.createNormals = function (updatable) {
  21159. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21160. var indices = this.getIndices();
  21161. var normals;
  21162. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21163. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21164. }
  21165. else {
  21166. normals = [];
  21167. }
  21168. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21169. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21170. return this;
  21171. };
  21172. /**
  21173. * Align the mesh with a normal
  21174. * @param normal defines the normal to use
  21175. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21176. * @returns the current mesh
  21177. */
  21178. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21179. if (!upDirection) {
  21180. upDirection = BABYLON.Axis.Y;
  21181. }
  21182. var axisX = BABYLON.Tmp.Vector3[0];
  21183. var axisZ = BABYLON.Tmp.Vector3[1];
  21184. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21185. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21186. if (this.rotationQuaternion) {
  21187. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21188. }
  21189. else {
  21190. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21191. }
  21192. return this;
  21193. };
  21194. /** @hidden */
  21195. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21196. var engine = this.getEngine();
  21197. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21198. this._isOccluded = false;
  21199. return;
  21200. }
  21201. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21202. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21203. if (isOcclusionQueryAvailable) {
  21204. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21205. this._isOcclusionQueryInProgress = false;
  21206. this._occlusionInternalRetryCounter = 0;
  21207. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21208. }
  21209. else {
  21210. this._occlusionInternalRetryCounter++;
  21211. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21212. this._isOcclusionQueryInProgress = false;
  21213. this._occlusionInternalRetryCounter = 0;
  21214. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21215. // if strict continue the last state of the object.
  21216. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21217. }
  21218. else {
  21219. return;
  21220. }
  21221. }
  21222. }
  21223. var scene = this.getScene();
  21224. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21225. if (!this._occlusionQuery) {
  21226. this._occlusionQuery = engine.createQuery();
  21227. }
  21228. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21229. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21230. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21231. this._isOcclusionQueryInProgress = true;
  21232. };
  21233. /** No occlusion */
  21234. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21235. /** Occlusion set to optimisitic */
  21236. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21237. /** Occlusion set to strict */
  21238. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21239. /** Use an accurante occlusion algorithm */
  21240. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21241. /** Use a conservative occlusion algorithm */
  21242. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21243. return AbstractMesh;
  21244. }(BABYLON.TransformNode));
  21245. BABYLON.AbstractMesh = AbstractMesh;
  21246. })(BABYLON || (BABYLON = {}));
  21247. //# sourceMappingURL=babylon.abstractMesh.js.map
  21248. var BABYLON;
  21249. (function (BABYLON) {
  21250. /**
  21251. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21252. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21253. * 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.
  21254. */
  21255. var Light = /** @class */ (function (_super) {
  21256. __extends(Light, _super);
  21257. /**
  21258. * Creates a Light object in the scene.
  21259. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21260. * @param name The firendly name of the light
  21261. * @param scene The scene the light belongs too
  21262. */
  21263. function Light(name, scene) {
  21264. var _this = _super.call(this, name, scene) || this;
  21265. /**
  21266. * Diffuse gives the basic color to an object.
  21267. */
  21268. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21269. /**
  21270. * Specular produces a highlight color on an object.
  21271. * Note: This is note affecting PBR materials.
  21272. */
  21273. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21274. /**
  21275. * Strength of the light.
  21276. * Note: By default it is define in the framework own unit.
  21277. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21278. */
  21279. _this.intensity = 1.0;
  21280. /**
  21281. * Defines how far from the source the light is impacting in scene units.
  21282. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21283. */
  21284. _this.range = Number.MAX_VALUE;
  21285. /**
  21286. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21287. * of light.
  21288. */
  21289. _this._photometricScale = 1.0;
  21290. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21291. _this._radius = 0.00001;
  21292. /**
  21293. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21294. * exceeding the number allowed of the materials.
  21295. */
  21296. _this.renderPriority = 0;
  21297. /**
  21298. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21299. * the current shadow generator.
  21300. */
  21301. _this.shadowEnabled = true;
  21302. _this._excludeWithLayerMask = 0;
  21303. _this._includeOnlyWithLayerMask = 0;
  21304. _this._lightmapMode = 0;
  21305. /**
  21306. * @hidden Internal use only.
  21307. */
  21308. _this._excludedMeshesIds = new Array();
  21309. /**
  21310. * @hidden Internal use only.
  21311. */
  21312. _this._includedOnlyMeshesIds = new Array();
  21313. _this.getScene().addLight(_this);
  21314. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21315. _this._buildUniformLayout();
  21316. _this.includedOnlyMeshes = new Array();
  21317. _this.excludedMeshes = new Array();
  21318. _this._resyncMeshes();
  21319. return _this;
  21320. }
  21321. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21322. /**
  21323. * If every light affecting the material is in this lightmapMode,
  21324. * material.lightmapTexture adds or multiplies
  21325. * (depends on material.useLightmapAsShadowmap)
  21326. * after every other light calculations.
  21327. */
  21328. get: function () {
  21329. return Light._LIGHTMAP_DEFAULT;
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21335. /**
  21336. * material.lightmapTexture as only diffuse lighting from this light
  21337. * adds only specular lighting from this light
  21338. * adds dynamic shadows
  21339. */
  21340. get: function () {
  21341. return Light._LIGHTMAP_SPECULAR;
  21342. },
  21343. enumerable: true,
  21344. configurable: true
  21345. });
  21346. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21347. /**
  21348. * material.lightmapTexture as only lighting
  21349. * no light calculation from this light
  21350. * only adds dynamic shadows from this light
  21351. */
  21352. get: function () {
  21353. return Light._LIGHTMAP_SHADOWSONLY;
  21354. },
  21355. enumerable: true,
  21356. configurable: true
  21357. });
  21358. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21359. /**
  21360. * Each light type uses the default quantity according to its type:
  21361. * point/spot lights use luminous intensity
  21362. * directional lights use illuminance
  21363. */
  21364. get: function () {
  21365. return Light._INTENSITYMODE_AUTOMATIC;
  21366. },
  21367. enumerable: true,
  21368. configurable: true
  21369. });
  21370. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21371. /**
  21372. * lumen (lm)
  21373. */
  21374. get: function () {
  21375. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21381. /**
  21382. * candela (lm/sr)
  21383. */
  21384. get: function () {
  21385. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21391. /**
  21392. * lux (lm/m^2)
  21393. */
  21394. get: function () {
  21395. return Light._INTENSITYMODE_ILLUMINANCE;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21401. /**
  21402. * nit (cd/m^2)
  21403. */
  21404. get: function () {
  21405. return Light._INTENSITYMODE_LUMINANCE;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21411. /**
  21412. * Light type const id of the point light.
  21413. */
  21414. get: function () {
  21415. return Light._LIGHTTYPEID_POINTLIGHT;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21421. /**
  21422. * Light type const id of the directional light.
  21423. */
  21424. get: function () {
  21425. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21426. },
  21427. enumerable: true,
  21428. configurable: true
  21429. });
  21430. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21431. /**
  21432. * Light type const id of the spot light.
  21433. */
  21434. get: function () {
  21435. return Light._LIGHTTYPEID_SPOTLIGHT;
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21441. /**
  21442. * Light type const id of the hemispheric light.
  21443. */
  21444. get: function () {
  21445. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21446. },
  21447. enumerable: true,
  21448. configurable: true
  21449. });
  21450. Object.defineProperty(Light.prototype, "intensityMode", {
  21451. /**
  21452. * Gets the photometric scale used to interpret the intensity.
  21453. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21454. */
  21455. get: function () {
  21456. return this._intensityMode;
  21457. },
  21458. /**
  21459. * Sets the photometric scale used to interpret the intensity.
  21460. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21461. */
  21462. set: function (value) {
  21463. this._intensityMode = value;
  21464. this._computePhotometricScale();
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. ;
  21470. ;
  21471. Object.defineProperty(Light.prototype, "radius", {
  21472. /**
  21473. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21474. */
  21475. get: function () {
  21476. return this._radius;
  21477. },
  21478. /**
  21479. * sets the light radius used by PBR Materials to simulate soft area lights.
  21480. */
  21481. set: function (value) {
  21482. this._radius = value;
  21483. this._computePhotometricScale();
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. ;
  21489. ;
  21490. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21491. /**
  21492. * Gets the only meshes impacted by this light.
  21493. */
  21494. get: function () {
  21495. return this._includedOnlyMeshes;
  21496. },
  21497. /**
  21498. * Sets the only meshes impacted by this light.
  21499. */
  21500. set: function (value) {
  21501. this._includedOnlyMeshes = value;
  21502. this._hookArrayForIncludedOnly(value);
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21508. /**
  21509. * Gets the meshes not impacted by this light.
  21510. */
  21511. get: function () {
  21512. return this._excludedMeshes;
  21513. },
  21514. /**
  21515. * Sets the meshes not impacted by this light.
  21516. */
  21517. set: function (value) {
  21518. this._excludedMeshes = value;
  21519. this._hookArrayForExcluded(value);
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21525. /**
  21526. * Gets the layer id use to find what meshes are not impacted by the light.
  21527. * Inactive if 0
  21528. */
  21529. get: function () {
  21530. return this._excludeWithLayerMask;
  21531. },
  21532. /**
  21533. * Sets the layer id use to find what meshes are not impacted by the light.
  21534. * Inactive if 0
  21535. */
  21536. set: function (value) {
  21537. this._excludeWithLayerMask = value;
  21538. this._resyncMeshes();
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21544. /**
  21545. * Gets the layer id use to find what meshes are impacted by the light.
  21546. * Inactive if 0
  21547. */
  21548. get: function () {
  21549. return this._includeOnlyWithLayerMask;
  21550. },
  21551. /**
  21552. * Sets the layer id use to find what meshes are impacted by the light.
  21553. * Inactive if 0
  21554. */
  21555. set: function (value) {
  21556. this._includeOnlyWithLayerMask = value;
  21557. this._resyncMeshes();
  21558. },
  21559. enumerable: true,
  21560. configurable: true
  21561. });
  21562. Object.defineProperty(Light.prototype, "lightmapMode", {
  21563. /**
  21564. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21565. */
  21566. get: function () {
  21567. return this._lightmapMode;
  21568. },
  21569. /**
  21570. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21571. */
  21572. set: function (value) {
  21573. if (this._lightmapMode === value) {
  21574. return;
  21575. }
  21576. this._lightmapMode = value;
  21577. this._markMeshesAsLightDirty();
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. /**
  21583. * Returns the string "Light".
  21584. * @returns the class name
  21585. */
  21586. Light.prototype.getClassName = function () {
  21587. return "Light";
  21588. };
  21589. /**
  21590. * Converts the light information to a readable string for debug purpose.
  21591. * @param fullDetails Supports for multiple levels of logging within scene loading
  21592. * @returns the human readable light info
  21593. */
  21594. Light.prototype.toString = function (fullDetails) {
  21595. var ret = "Name: " + this.name;
  21596. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21597. if (this.animations) {
  21598. for (var i = 0; i < this.animations.length; i++) {
  21599. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21600. }
  21601. }
  21602. if (fullDetails) {
  21603. }
  21604. return ret;
  21605. };
  21606. /**
  21607. * Set the enabled state of this node.
  21608. * @param value - the new enabled state
  21609. */
  21610. Light.prototype.setEnabled = function (value) {
  21611. _super.prototype.setEnabled.call(this, value);
  21612. this._resyncMeshes();
  21613. };
  21614. /**
  21615. * Returns the Light associated shadow generator if any.
  21616. * @return the associated shadow generator.
  21617. */
  21618. Light.prototype.getShadowGenerator = function () {
  21619. return this._shadowGenerator;
  21620. };
  21621. /**
  21622. * Returns a Vector3, the absolute light position in the World.
  21623. * @returns the world space position of the light
  21624. */
  21625. Light.prototype.getAbsolutePosition = function () {
  21626. return BABYLON.Vector3.Zero();
  21627. };
  21628. /**
  21629. * Specifies if the light will affect the passed mesh.
  21630. * @param mesh The mesh to test against the light
  21631. * @return true the mesh is affected otherwise, false.
  21632. */
  21633. Light.prototype.canAffectMesh = function (mesh) {
  21634. if (!mesh) {
  21635. return true;
  21636. }
  21637. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21638. return false;
  21639. }
  21640. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21641. return false;
  21642. }
  21643. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21644. return false;
  21645. }
  21646. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21647. return false;
  21648. }
  21649. return true;
  21650. };
  21651. /**
  21652. * Computes and Returns the light World matrix.
  21653. * @returns the world matrix
  21654. */
  21655. Light.prototype.getWorldMatrix = function () {
  21656. this._currentRenderId = this.getScene().getRenderId();
  21657. this._childRenderId = this._currentRenderId;
  21658. var worldMatrix = this._getWorldMatrix();
  21659. if (this.parent && this.parent.getWorldMatrix) {
  21660. if (!this._parentedWorldMatrix) {
  21661. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21662. }
  21663. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21664. this._markSyncedWithParent();
  21665. return this._parentedWorldMatrix;
  21666. }
  21667. return worldMatrix;
  21668. };
  21669. /**
  21670. * Sort function to order lights for rendering.
  21671. * @param a First Light object to compare to second.
  21672. * @param b Second Light object to compare first.
  21673. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21674. */
  21675. Light.CompareLightsPriority = function (a, b) {
  21676. //shadow-casting lights have priority over non-shadow-casting lights
  21677. //the renderPrioirty is a secondary sort criterion
  21678. if (a.shadowEnabled !== b.shadowEnabled) {
  21679. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21680. }
  21681. return b.renderPriority - a.renderPriority;
  21682. };
  21683. /**
  21684. * Releases resources associated with this node.
  21685. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21686. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21687. */
  21688. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21689. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21690. if (this._shadowGenerator) {
  21691. this._shadowGenerator.dispose();
  21692. this._shadowGenerator = null;
  21693. }
  21694. // Animations
  21695. this.getScene().stopAnimation(this);
  21696. // Remove from meshes
  21697. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21698. var mesh = _a[_i];
  21699. mesh._removeLightSource(this);
  21700. }
  21701. this._uniformBuffer.dispose();
  21702. // Remove from scene
  21703. this.getScene().removeLight(this);
  21704. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21705. };
  21706. /**
  21707. * Returns the light type ID (integer).
  21708. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21709. */
  21710. Light.prototype.getTypeID = function () {
  21711. return 0;
  21712. };
  21713. /**
  21714. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21715. * @returns the scaled intensity in intensity mode unit
  21716. */
  21717. Light.prototype.getScaledIntensity = function () {
  21718. return this._photometricScale * this.intensity;
  21719. };
  21720. /**
  21721. * Returns a new Light object, named "name", from the current one.
  21722. * @param name The name of the cloned light
  21723. * @returns the new created light
  21724. */
  21725. Light.prototype.clone = function (name) {
  21726. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21727. if (!constructor) {
  21728. return null;
  21729. }
  21730. return BABYLON.SerializationHelper.Clone(constructor, this);
  21731. };
  21732. /**
  21733. * Serializes the current light into a Serialization object.
  21734. * @returns the serialized object.
  21735. */
  21736. Light.prototype.serialize = function () {
  21737. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21738. // Type
  21739. serializationObject.type = this.getTypeID();
  21740. // Parent
  21741. if (this.parent) {
  21742. serializationObject.parentId = this.parent.id;
  21743. }
  21744. // Inclusion / exclusions
  21745. if (this.excludedMeshes.length > 0) {
  21746. serializationObject.excludedMeshesIds = [];
  21747. this.excludedMeshes.forEach(function (mesh) {
  21748. serializationObject.excludedMeshesIds.push(mesh.id);
  21749. });
  21750. }
  21751. if (this.includedOnlyMeshes.length > 0) {
  21752. serializationObject.includedOnlyMeshesIds = [];
  21753. this.includedOnlyMeshes.forEach(function (mesh) {
  21754. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21755. });
  21756. }
  21757. // Animations
  21758. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21759. serializationObject.ranges = this.serializeAnimationRanges();
  21760. return serializationObject;
  21761. };
  21762. /**
  21763. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21764. * This new light is named "name" and added to the passed scene.
  21765. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21766. * @param name The friendly name of the light
  21767. * @param scene The scene the new light will belong to
  21768. * @returns the constructor function
  21769. */
  21770. Light.GetConstructorFromName = function (type, name, scene) {
  21771. switch (type) {
  21772. case 0:
  21773. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21774. case 1:
  21775. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21776. case 2:
  21777. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21778. case 3:
  21779. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21780. }
  21781. return null;
  21782. };
  21783. /**
  21784. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21785. * @param parsedLight The JSON representation of the light
  21786. * @param scene The scene to create the parsed light in
  21787. * @returns the created light after parsing
  21788. */
  21789. Light.Parse = function (parsedLight, scene) {
  21790. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21791. if (!constructor) {
  21792. return null;
  21793. }
  21794. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21795. // Inclusion / exclusions
  21796. if (parsedLight.excludedMeshesIds) {
  21797. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21798. }
  21799. if (parsedLight.includedOnlyMeshesIds) {
  21800. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21801. }
  21802. // Parent
  21803. if (parsedLight.parentId) {
  21804. light._waitingParentId = parsedLight.parentId;
  21805. }
  21806. // Animations
  21807. if (parsedLight.animations) {
  21808. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21809. var parsedAnimation = parsedLight.animations[animationIndex];
  21810. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21811. }
  21812. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21813. }
  21814. if (parsedLight.autoAnimate) {
  21815. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21816. }
  21817. return light;
  21818. };
  21819. Light.prototype._hookArrayForExcluded = function (array) {
  21820. var _this = this;
  21821. var oldPush = array.push;
  21822. array.push = function () {
  21823. var items = [];
  21824. for (var _i = 0; _i < arguments.length; _i++) {
  21825. items[_i] = arguments[_i];
  21826. }
  21827. var result = oldPush.apply(array, items);
  21828. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21829. var item = items_1[_a];
  21830. item._resyncLighSource(_this);
  21831. }
  21832. return result;
  21833. };
  21834. var oldSplice = array.splice;
  21835. array.splice = function (index, deleteCount) {
  21836. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21837. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21838. var item = deleted_1[_i];
  21839. item._resyncLighSource(_this);
  21840. }
  21841. return deleted;
  21842. };
  21843. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21844. var item = array_1[_i];
  21845. item._resyncLighSource(this);
  21846. }
  21847. };
  21848. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21849. var _this = this;
  21850. var oldPush = array.push;
  21851. array.push = function () {
  21852. var items = [];
  21853. for (var _i = 0; _i < arguments.length; _i++) {
  21854. items[_i] = arguments[_i];
  21855. }
  21856. var result = oldPush.apply(array, items);
  21857. _this._resyncMeshes();
  21858. return result;
  21859. };
  21860. var oldSplice = array.splice;
  21861. array.splice = function (index, deleteCount) {
  21862. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21863. _this._resyncMeshes();
  21864. return deleted;
  21865. };
  21866. this._resyncMeshes();
  21867. };
  21868. Light.prototype._resyncMeshes = function () {
  21869. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21870. var mesh = _a[_i];
  21871. mesh._resyncLighSource(this);
  21872. }
  21873. };
  21874. /**
  21875. * Forces the meshes to update their light related information in their rendering used effects
  21876. * @hidden Internal Use Only
  21877. */
  21878. Light.prototype._markMeshesAsLightDirty = function () {
  21879. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21880. var mesh = _a[_i];
  21881. if (mesh._lightSources.indexOf(this) !== -1) {
  21882. mesh._markSubMeshesAsLightDirty();
  21883. }
  21884. }
  21885. };
  21886. /**
  21887. * Recomputes the cached photometric scale if needed.
  21888. */
  21889. Light.prototype._computePhotometricScale = function () {
  21890. this._photometricScale = this._getPhotometricScale();
  21891. this.getScene().resetCachedMaterial();
  21892. };
  21893. /**
  21894. * Returns the Photometric Scale according to the light type and intensity mode.
  21895. */
  21896. Light.prototype._getPhotometricScale = function () {
  21897. var photometricScale = 0.0;
  21898. var lightTypeID = this.getTypeID();
  21899. //get photometric mode
  21900. var photometricMode = this.intensityMode;
  21901. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21902. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21903. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21904. }
  21905. else {
  21906. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21907. }
  21908. }
  21909. //compute photometric scale
  21910. switch (lightTypeID) {
  21911. case Light.LIGHTTYPEID_POINTLIGHT:
  21912. case Light.LIGHTTYPEID_SPOTLIGHT:
  21913. switch (photometricMode) {
  21914. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21915. photometricScale = 1.0 / (4.0 * Math.PI);
  21916. break;
  21917. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21918. photometricScale = 1.0;
  21919. break;
  21920. case Light.INTENSITYMODE_LUMINANCE:
  21921. photometricScale = this.radius * this.radius;
  21922. break;
  21923. }
  21924. break;
  21925. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21926. switch (photometricMode) {
  21927. case Light.INTENSITYMODE_ILLUMINANCE:
  21928. photometricScale = 1.0;
  21929. break;
  21930. case Light.INTENSITYMODE_LUMINANCE:
  21931. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21932. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21933. var apexAngleRadians = this.radius;
  21934. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21935. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21936. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21937. photometricScale = solidAngle;
  21938. break;
  21939. }
  21940. break;
  21941. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21942. // No fall off in hemisperic light.
  21943. photometricScale = 1.0;
  21944. break;
  21945. }
  21946. return photometricScale;
  21947. };
  21948. /**
  21949. * Reorder the light in the scene according to their defined priority.
  21950. * @hidden Internal Use Only
  21951. */
  21952. Light.prototype._reorderLightsInScene = function () {
  21953. var scene = this.getScene();
  21954. if (this._renderPriority != 0) {
  21955. scene.requireLightSorting = true;
  21956. }
  21957. this.getScene().sortLightsByPriority();
  21958. };
  21959. //lightmapMode Consts
  21960. Light._LIGHTMAP_DEFAULT = 0;
  21961. Light._LIGHTMAP_SPECULAR = 1;
  21962. Light._LIGHTMAP_SHADOWSONLY = 2;
  21963. // Intensity Mode Consts
  21964. Light._INTENSITYMODE_AUTOMATIC = 0;
  21965. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21966. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21967. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21968. Light._INTENSITYMODE_LUMINANCE = 4;
  21969. // Light types ids const.
  21970. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21971. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21972. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21973. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21974. __decorate([
  21975. BABYLON.serializeAsColor3()
  21976. ], Light.prototype, "diffuse", void 0);
  21977. __decorate([
  21978. BABYLON.serializeAsColor3()
  21979. ], Light.prototype, "specular", void 0);
  21980. __decorate([
  21981. BABYLON.serialize()
  21982. ], Light.prototype, "intensity", void 0);
  21983. __decorate([
  21984. BABYLON.serialize()
  21985. ], Light.prototype, "range", void 0);
  21986. __decorate([
  21987. BABYLON.serialize()
  21988. ], Light.prototype, "intensityMode", null);
  21989. __decorate([
  21990. BABYLON.serialize()
  21991. ], Light.prototype, "radius", null);
  21992. __decorate([
  21993. BABYLON.serialize()
  21994. ], Light.prototype, "_renderPriority", void 0);
  21995. __decorate([
  21996. BABYLON.expandToProperty("_reorderLightsInScene")
  21997. ], Light.prototype, "renderPriority", void 0);
  21998. __decorate([
  21999. BABYLON.serialize()
  22000. ], Light.prototype, "shadowEnabled", void 0);
  22001. __decorate([
  22002. BABYLON.serialize("excludeWithLayerMask")
  22003. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22004. __decorate([
  22005. BABYLON.serialize("includeOnlyWithLayerMask")
  22006. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22007. __decorate([
  22008. BABYLON.serialize("lightmapMode")
  22009. ], Light.prototype, "_lightmapMode", void 0);
  22010. return Light;
  22011. }(BABYLON.Node));
  22012. BABYLON.Light = Light;
  22013. })(BABYLON || (BABYLON = {}));
  22014. //# sourceMappingURL=babylon.light.js.map
  22015. var BABYLON;
  22016. (function (BABYLON) {
  22017. var Camera = /** @class */ (function (_super) {
  22018. __extends(Camera, _super);
  22019. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22020. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22021. var _this = _super.call(this, name, scene) || this;
  22022. /**
  22023. * The vector the camera should consider as up.
  22024. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22025. */
  22026. _this.upVector = BABYLON.Vector3.Up();
  22027. _this.orthoLeft = null;
  22028. _this.orthoRight = null;
  22029. _this.orthoBottom = null;
  22030. _this.orthoTop = null;
  22031. /**
  22032. * FOV is set in Radians. (default is 0.8)
  22033. */
  22034. _this.fov = 0.8;
  22035. _this.minZ = 1;
  22036. _this.maxZ = 10000.0;
  22037. _this.inertia = 0.9;
  22038. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22039. _this.isIntermediate = false;
  22040. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22041. /**
  22042. * Restricts the camera to viewing objects with the same layerMask.
  22043. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22044. */
  22045. _this.layerMask = 0x0FFFFFFF;
  22046. /**
  22047. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22048. */
  22049. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22050. // Camera rig members
  22051. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22052. _this._rigCameras = new Array();
  22053. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22054. _this._skipRendering = false;
  22055. _this.customRenderTargets = new Array();
  22056. // Observables
  22057. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22058. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22059. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22060. _this.onRestoreStateObservable = new BABYLON.Observable();
  22061. // Cache
  22062. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22063. _this._projectionMatrix = new BABYLON.Matrix();
  22064. _this._doNotComputeProjectionMatrix = false;
  22065. _this._worldMatrix = BABYLON.Matrix.Identity();
  22066. _this._postProcesses = new Array();
  22067. _this._transformMatrix = BABYLON.Matrix.Zero();
  22068. _this._activeMeshes = new BABYLON.SmartArray(256);
  22069. _this._globalPosition = BABYLON.Vector3.Zero();
  22070. _this._refreshFrustumPlanes = true;
  22071. _this.getScene().addCamera(_this);
  22072. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22073. _this.getScene().activeCamera = _this;
  22074. }
  22075. _this.position = position;
  22076. return _this;
  22077. }
  22078. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22079. get: function () {
  22080. return Camera._PERSPECTIVE_CAMERA;
  22081. },
  22082. enumerable: true,
  22083. configurable: true
  22084. });
  22085. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22086. get: function () {
  22087. return Camera._ORTHOGRAPHIC_CAMERA;
  22088. },
  22089. enumerable: true,
  22090. configurable: true
  22091. });
  22092. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22093. /**
  22094. * This is the default FOV mode for perspective cameras.
  22095. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22096. *
  22097. */
  22098. get: function () {
  22099. return Camera._FOVMODE_VERTICAL_FIXED;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22105. /**
  22106. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22107. *
  22108. */
  22109. get: function () {
  22110. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22111. },
  22112. enumerable: true,
  22113. configurable: true
  22114. });
  22115. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22116. get: function () {
  22117. return Camera._RIG_MODE_NONE;
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22123. get: function () {
  22124. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22130. get: function () {
  22131. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22137. get: function () {
  22138. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22144. get: function () {
  22145. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22151. get: function () {
  22152. return Camera._RIG_MODE_VR;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22158. get: function () {
  22159. return Camera._RIG_MODE_WEBVR;
  22160. },
  22161. enumerable: true,
  22162. configurable: true
  22163. });
  22164. /**
  22165. * Store current camera state (fov, position, etc..)
  22166. */
  22167. Camera.prototype.storeState = function () {
  22168. this._stateStored = true;
  22169. this._storedFov = this.fov;
  22170. return this;
  22171. };
  22172. /**
  22173. * Restores the camera state values if it has been stored. You must call storeState() first
  22174. */
  22175. Camera.prototype._restoreStateValues = function () {
  22176. if (!this._stateStored) {
  22177. return false;
  22178. }
  22179. this.fov = this._storedFov;
  22180. return true;
  22181. };
  22182. /**
  22183. * Restored camera state. You must call storeState() first
  22184. */
  22185. Camera.prototype.restoreState = function () {
  22186. if (this._restoreStateValues()) {
  22187. this.onRestoreStateObservable.notifyObservers(this);
  22188. return true;
  22189. }
  22190. return false;
  22191. };
  22192. Camera.prototype.getClassName = function () {
  22193. return "Camera";
  22194. };
  22195. /**
  22196. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22197. */
  22198. Camera.prototype.toString = function (fullDetails) {
  22199. var ret = "Name: " + this.name;
  22200. ret += ", type: " + this.getClassName();
  22201. if (this.animations) {
  22202. for (var i = 0; i < this.animations.length; i++) {
  22203. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22204. }
  22205. }
  22206. if (fullDetails) {
  22207. }
  22208. return ret;
  22209. };
  22210. Object.defineProperty(Camera.prototype, "globalPosition", {
  22211. get: function () {
  22212. return this._globalPosition;
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. Camera.prototype.getActiveMeshes = function () {
  22218. return this._activeMeshes;
  22219. };
  22220. Camera.prototype.isActiveMesh = function (mesh) {
  22221. return (this._activeMeshes.indexOf(mesh) !== -1);
  22222. };
  22223. /**
  22224. * Is this camera ready to be used/rendered
  22225. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22226. * @return true if the camera is ready
  22227. */
  22228. Camera.prototype.isReady = function (completeCheck) {
  22229. if (completeCheck === void 0) { completeCheck = false; }
  22230. if (completeCheck) {
  22231. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22232. var pp = _a[_i];
  22233. if (pp && !pp.isReady()) {
  22234. return false;
  22235. }
  22236. }
  22237. }
  22238. return _super.prototype.isReady.call(this, completeCheck);
  22239. };
  22240. //Cache
  22241. Camera.prototype._initCache = function () {
  22242. _super.prototype._initCache.call(this);
  22243. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22244. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22245. this._cache.mode = undefined;
  22246. this._cache.minZ = undefined;
  22247. this._cache.maxZ = undefined;
  22248. this._cache.fov = undefined;
  22249. this._cache.fovMode = undefined;
  22250. this._cache.aspectRatio = undefined;
  22251. this._cache.orthoLeft = undefined;
  22252. this._cache.orthoRight = undefined;
  22253. this._cache.orthoBottom = undefined;
  22254. this._cache.orthoTop = undefined;
  22255. this._cache.renderWidth = undefined;
  22256. this._cache.renderHeight = undefined;
  22257. };
  22258. Camera.prototype._updateCache = function (ignoreParentClass) {
  22259. if (!ignoreParentClass) {
  22260. _super.prototype._updateCache.call(this);
  22261. }
  22262. this._cache.position.copyFrom(this.position);
  22263. this._cache.upVector.copyFrom(this.upVector);
  22264. };
  22265. // Synchronized
  22266. Camera.prototype._isSynchronized = function () {
  22267. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22268. };
  22269. Camera.prototype._isSynchronizedViewMatrix = function () {
  22270. if (!_super.prototype._isSynchronized.call(this))
  22271. return false;
  22272. return this._cache.position.equals(this.position)
  22273. && this._cache.upVector.equals(this.upVector)
  22274. && this.isSynchronizedWithParent();
  22275. };
  22276. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22277. var check = this._cache.mode === this.mode
  22278. && this._cache.minZ === this.minZ
  22279. && this._cache.maxZ === this.maxZ;
  22280. if (!check) {
  22281. return false;
  22282. }
  22283. var engine = this.getEngine();
  22284. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22285. check = this._cache.fov === this.fov
  22286. && this._cache.fovMode === this.fovMode
  22287. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22288. }
  22289. else {
  22290. check = this._cache.orthoLeft === this.orthoLeft
  22291. && this._cache.orthoRight === this.orthoRight
  22292. && this._cache.orthoBottom === this.orthoBottom
  22293. && this._cache.orthoTop === this.orthoTop
  22294. && this._cache.renderWidth === engine.getRenderWidth()
  22295. && this._cache.renderHeight === engine.getRenderHeight();
  22296. }
  22297. return check;
  22298. };
  22299. // Controls
  22300. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22301. };
  22302. Camera.prototype.detachControl = function (element) {
  22303. };
  22304. Camera.prototype.update = function () {
  22305. this._checkInputs();
  22306. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22307. this._updateRigCameras();
  22308. }
  22309. };
  22310. Camera.prototype._checkInputs = function () {
  22311. this.onAfterCheckInputsObservable.notifyObservers(this);
  22312. };
  22313. Object.defineProperty(Camera.prototype, "rigCameras", {
  22314. get: function () {
  22315. return this._rigCameras;
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22321. get: function () {
  22322. return this._rigPostProcess;
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. /**
  22328. * Internal, gets the first post proces.
  22329. * @returns the first post process to be run on this camera.
  22330. */
  22331. Camera.prototype._getFirstPostProcess = function () {
  22332. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22333. if (this._postProcesses[ppIndex] !== null) {
  22334. return this._postProcesses[ppIndex];
  22335. }
  22336. }
  22337. return null;
  22338. };
  22339. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22340. // invalidate framebuffer
  22341. var firstPostProcess = this._getFirstPostProcess();
  22342. if (firstPostProcess) {
  22343. firstPostProcess.markTextureDirty();
  22344. }
  22345. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22346. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22347. var cam = this._rigCameras[i];
  22348. var rigPostProcess = cam._rigPostProcess;
  22349. // for VR rig, there does not have to be a post process
  22350. if (rigPostProcess) {
  22351. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22352. if (isPass) {
  22353. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22354. cam.isIntermediate = this._postProcesses.length === 0;
  22355. }
  22356. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22357. rigPostProcess.markTextureDirty();
  22358. }
  22359. else {
  22360. cam._postProcesses = this._postProcesses.slice(0);
  22361. }
  22362. }
  22363. };
  22364. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22365. if (insertAt === void 0) { insertAt = null; }
  22366. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22367. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22368. return 0;
  22369. }
  22370. if (insertAt == null || insertAt < 0) {
  22371. this._postProcesses.push(postProcess);
  22372. }
  22373. else if (this._postProcesses[insertAt] === null) {
  22374. this._postProcesses[insertAt] = postProcess;
  22375. }
  22376. else {
  22377. this._postProcesses.splice(insertAt, 0, postProcess);
  22378. }
  22379. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22380. return this._postProcesses.indexOf(postProcess);
  22381. };
  22382. Camera.prototype.detachPostProcess = function (postProcess) {
  22383. var idx = this._postProcesses.indexOf(postProcess);
  22384. if (idx !== -1) {
  22385. this._postProcesses[idx] = null;
  22386. }
  22387. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22388. };
  22389. Camera.prototype.getWorldMatrix = function () {
  22390. if (this._isSynchronizedViewMatrix()) {
  22391. return this._worldMatrix;
  22392. }
  22393. // Getting the the view matrix will also compute the world matrix.
  22394. this.getViewMatrix();
  22395. return this._worldMatrix;
  22396. };
  22397. Camera.prototype._getViewMatrix = function () {
  22398. return BABYLON.Matrix.Identity();
  22399. };
  22400. Camera.prototype.getViewMatrix = function (force) {
  22401. if (!force && this._isSynchronizedViewMatrix()) {
  22402. return this._computedViewMatrix;
  22403. }
  22404. this.updateCache();
  22405. this._computedViewMatrix = this._getViewMatrix();
  22406. this._currentRenderId = this.getScene().getRenderId();
  22407. this._childRenderId = this._currentRenderId;
  22408. this._refreshFrustumPlanes = true;
  22409. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22410. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22411. }
  22412. this.onViewMatrixChangedObservable.notifyObservers(this);
  22413. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22414. return this._computedViewMatrix;
  22415. };
  22416. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22417. this._doNotComputeProjectionMatrix = true;
  22418. if (projection !== undefined) {
  22419. this._projectionMatrix = projection;
  22420. }
  22421. };
  22422. ;
  22423. Camera.prototype.unfreezeProjectionMatrix = function () {
  22424. this._doNotComputeProjectionMatrix = false;
  22425. };
  22426. ;
  22427. Camera.prototype.getProjectionMatrix = function (force) {
  22428. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22429. return this._projectionMatrix;
  22430. }
  22431. // Cache
  22432. this._cache.mode = this.mode;
  22433. this._cache.minZ = this.minZ;
  22434. this._cache.maxZ = this.maxZ;
  22435. // Matrix
  22436. this._refreshFrustumPlanes = true;
  22437. var engine = this.getEngine();
  22438. var scene = this.getScene();
  22439. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22440. this._cache.fov = this.fov;
  22441. this._cache.fovMode = this.fovMode;
  22442. this._cache.aspectRatio = engine.getAspectRatio(this);
  22443. if (this.minZ <= 0) {
  22444. this.minZ = 0.1;
  22445. }
  22446. if (scene.useRightHandedSystem) {
  22447. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22448. }
  22449. else {
  22450. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22451. }
  22452. }
  22453. else {
  22454. var halfWidth = engine.getRenderWidth() / 2.0;
  22455. var halfHeight = engine.getRenderHeight() / 2.0;
  22456. if (scene.useRightHandedSystem) {
  22457. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22458. }
  22459. else {
  22460. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22461. }
  22462. this._cache.orthoLeft = this.orthoLeft;
  22463. this._cache.orthoRight = this.orthoRight;
  22464. this._cache.orthoBottom = this.orthoBottom;
  22465. this._cache.orthoTop = this.orthoTop;
  22466. this._cache.renderWidth = engine.getRenderWidth();
  22467. this._cache.renderHeight = engine.getRenderHeight();
  22468. }
  22469. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22470. return this._projectionMatrix;
  22471. };
  22472. Camera.prototype.getTranformationMatrix = function () {
  22473. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22474. return this._transformMatrix;
  22475. };
  22476. Camera.prototype.updateFrustumPlanes = function () {
  22477. if (!this._refreshFrustumPlanes) {
  22478. return;
  22479. }
  22480. this.getTranformationMatrix();
  22481. if (!this._frustumPlanes) {
  22482. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22483. }
  22484. else {
  22485. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22486. }
  22487. this._refreshFrustumPlanes = false;
  22488. };
  22489. Camera.prototype.isInFrustum = function (target) {
  22490. this.updateFrustumPlanes();
  22491. return target.isInFrustum(this._frustumPlanes);
  22492. };
  22493. Camera.prototype.isCompletelyInFrustum = function (target) {
  22494. this.updateFrustumPlanes();
  22495. return target.isCompletelyInFrustum(this._frustumPlanes);
  22496. };
  22497. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22498. if (length === void 0) { length = 100; }
  22499. if (!transform) {
  22500. transform = this.getWorldMatrix();
  22501. }
  22502. if (!origin) {
  22503. origin = this.position;
  22504. }
  22505. var forward = new BABYLON.Vector3(0, 0, 1);
  22506. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22507. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22508. return new BABYLON.Ray(origin, direction, length);
  22509. };
  22510. /**
  22511. * Releases resources associated with this node.
  22512. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22513. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22514. */
  22515. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22516. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22517. // Observables
  22518. this.onViewMatrixChangedObservable.clear();
  22519. this.onProjectionMatrixChangedObservable.clear();
  22520. this.onAfterCheckInputsObservable.clear();
  22521. this.onRestoreStateObservable.clear();
  22522. // Inputs
  22523. if (this.inputs) {
  22524. this.inputs.clear();
  22525. }
  22526. // Animations
  22527. this.getScene().stopAnimation(this);
  22528. // Remove from scene
  22529. this.getScene().removeCamera(this);
  22530. while (this._rigCameras.length > 0) {
  22531. var camera = this._rigCameras.pop();
  22532. if (camera) {
  22533. camera.dispose();
  22534. }
  22535. }
  22536. // Postprocesses
  22537. if (this._rigPostProcess) {
  22538. this._rigPostProcess.dispose(this);
  22539. this._rigPostProcess = null;
  22540. this._postProcesses = [];
  22541. }
  22542. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22543. this._rigPostProcess = null;
  22544. this._postProcesses = [];
  22545. }
  22546. else {
  22547. var i = this._postProcesses.length;
  22548. while (--i >= 0) {
  22549. var postProcess = this._postProcesses[i];
  22550. if (postProcess) {
  22551. postProcess.dispose(this);
  22552. }
  22553. }
  22554. }
  22555. // Render targets
  22556. var i = this.customRenderTargets.length;
  22557. while (--i >= 0) {
  22558. this.customRenderTargets[i].dispose();
  22559. }
  22560. this.customRenderTargets = [];
  22561. // Active Meshes
  22562. this._activeMeshes.dispose();
  22563. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22564. };
  22565. Object.defineProperty(Camera.prototype, "leftCamera", {
  22566. // ---- Camera rigs section ----
  22567. get: function () {
  22568. if (this._rigCameras.length < 1) {
  22569. return null;
  22570. }
  22571. return this._rigCameras[0];
  22572. },
  22573. enumerable: true,
  22574. configurable: true
  22575. });
  22576. Object.defineProperty(Camera.prototype, "rightCamera", {
  22577. get: function () {
  22578. if (this._rigCameras.length < 2) {
  22579. return null;
  22580. }
  22581. return this._rigCameras[1];
  22582. },
  22583. enumerable: true,
  22584. configurable: true
  22585. });
  22586. Camera.prototype.getLeftTarget = function () {
  22587. if (this._rigCameras.length < 1) {
  22588. return null;
  22589. }
  22590. return this._rigCameras[0].getTarget();
  22591. };
  22592. Camera.prototype.getRightTarget = function () {
  22593. if (this._rigCameras.length < 2) {
  22594. return null;
  22595. }
  22596. return this._rigCameras[1].getTarget();
  22597. };
  22598. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22599. if (this.cameraRigMode === mode) {
  22600. return;
  22601. }
  22602. while (this._rigCameras.length > 0) {
  22603. var camera = this._rigCameras.pop();
  22604. if (camera) {
  22605. camera.dispose();
  22606. }
  22607. }
  22608. this.cameraRigMode = mode;
  22609. this._cameraRigParams = {};
  22610. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22611. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22612. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22613. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22614. // create the rig cameras, unless none
  22615. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22616. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22617. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22618. if (leftCamera && rightCamera) {
  22619. this._rigCameras.push(leftCamera);
  22620. this._rigCameras.push(rightCamera);
  22621. }
  22622. }
  22623. switch (this.cameraRigMode) {
  22624. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22625. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22626. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22627. break;
  22628. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22629. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22630. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22631. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22632. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22633. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22634. break;
  22635. case Camera.RIG_MODE_VR:
  22636. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22637. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22638. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22639. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22640. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22641. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22642. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22643. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22644. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22645. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22646. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22647. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22648. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22649. if (metrics.compensateDistortion) {
  22650. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22651. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22652. }
  22653. break;
  22654. case Camera.RIG_MODE_WEBVR:
  22655. if (rigParams.vrDisplay) {
  22656. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22657. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22658. //Left eye
  22659. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22660. this._rigCameras[0].setCameraRigParameter("left", true);
  22661. //leaving this for future reference
  22662. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22663. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22664. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22665. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22666. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22667. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22668. this._rigCameras[0].parent = this;
  22669. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22670. //Right eye
  22671. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22672. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22673. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22674. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22675. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22676. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22677. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22678. this._rigCameras[1].parent = this;
  22679. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22680. if (Camera.UseAlternateWebVRRendering) {
  22681. this._rigCameras[1]._skipRendering = true;
  22682. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22683. }
  22684. }
  22685. break;
  22686. }
  22687. this._cascadePostProcessesToRigCams();
  22688. this.update();
  22689. };
  22690. Camera.prototype._getVRProjectionMatrix = function () {
  22691. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22692. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22693. return this._projectionMatrix;
  22694. };
  22695. Camera.prototype._updateCameraRotationMatrix = function () {
  22696. //Here for WebVR
  22697. };
  22698. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22699. //Here for WebVR
  22700. };
  22701. /**
  22702. * This function MUST be overwritten by the different WebVR cameras available.
  22703. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22704. */
  22705. Camera.prototype._getWebVRProjectionMatrix = function () {
  22706. return BABYLON.Matrix.Identity();
  22707. };
  22708. /**
  22709. * This function MUST be overwritten by the different WebVR cameras available.
  22710. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22711. */
  22712. Camera.prototype._getWebVRViewMatrix = function () {
  22713. return BABYLON.Matrix.Identity();
  22714. };
  22715. Camera.prototype.setCameraRigParameter = function (name, value) {
  22716. if (!this._cameraRigParams) {
  22717. this._cameraRigParams = {};
  22718. }
  22719. this._cameraRigParams[name] = value;
  22720. //provisionnally:
  22721. if (name === "interaxialDistance") {
  22722. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22723. }
  22724. };
  22725. /**
  22726. * needs to be overridden by children so sub has required properties to be copied
  22727. */
  22728. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22729. return null;
  22730. };
  22731. /**
  22732. * May need to be overridden by children
  22733. */
  22734. Camera.prototype._updateRigCameras = function () {
  22735. for (var i = 0; i < this._rigCameras.length; i++) {
  22736. this._rigCameras[i].minZ = this.minZ;
  22737. this._rigCameras[i].maxZ = this.maxZ;
  22738. this._rigCameras[i].fov = this.fov;
  22739. }
  22740. // only update viewport when ANAGLYPH
  22741. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22742. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22743. }
  22744. };
  22745. Camera.prototype._setupInputs = function () {
  22746. };
  22747. Camera.prototype.serialize = function () {
  22748. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22749. // Type
  22750. serializationObject.type = this.getClassName();
  22751. // Parent
  22752. if (this.parent) {
  22753. serializationObject.parentId = this.parent.id;
  22754. }
  22755. if (this.inputs) {
  22756. this.inputs.serialize(serializationObject);
  22757. }
  22758. // Animations
  22759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22760. serializationObject.ranges = this.serializeAnimationRanges();
  22761. return serializationObject;
  22762. };
  22763. Camera.prototype.clone = function (name) {
  22764. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22765. };
  22766. Camera.prototype.getDirection = function (localAxis) {
  22767. var result = BABYLON.Vector3.Zero();
  22768. this.getDirectionToRef(localAxis, result);
  22769. return result;
  22770. };
  22771. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22772. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22773. };
  22774. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22775. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22776. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22777. switch (type) {
  22778. case "ArcRotateCamera":
  22779. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22780. case "DeviceOrientationCamera":
  22781. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22782. case "FollowCamera":
  22783. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22784. case "ArcFollowCamera":
  22785. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22786. case "GamepadCamera":
  22787. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22788. case "TouchCamera":
  22789. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22790. case "VirtualJoysticksCamera":
  22791. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22792. case "WebVRFreeCamera":
  22793. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22794. case "WebVRGamepadCamera":
  22795. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22796. case "VRDeviceOrientationFreeCamera":
  22797. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22798. case "VRDeviceOrientationGamepadCamera":
  22799. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22800. case "AnaglyphArcRotateCamera":
  22801. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22802. case "AnaglyphFreeCamera":
  22803. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22804. case "AnaglyphGamepadCamera":
  22805. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22806. case "AnaglyphUniversalCamera":
  22807. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22808. case "StereoscopicArcRotateCamera":
  22809. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22810. case "StereoscopicFreeCamera":
  22811. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22812. case "StereoscopicGamepadCamera":
  22813. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22814. case "StereoscopicUniversalCamera":
  22815. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22816. case "FreeCamera": // Forcing Universal here
  22817. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22818. default: // Universal Camera is the default value
  22819. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22820. }
  22821. };
  22822. Camera.prototype.computeWorldMatrix = function () {
  22823. return this.getWorldMatrix();
  22824. };
  22825. Camera.Parse = function (parsedCamera, scene) {
  22826. var type = parsedCamera.type;
  22827. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22828. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22829. // Parent
  22830. if (parsedCamera.parentId) {
  22831. camera._waitingParentId = parsedCamera.parentId;
  22832. }
  22833. //If camera has an input manager, let it parse inputs settings
  22834. if (camera.inputs) {
  22835. camera.inputs.parse(parsedCamera);
  22836. camera._setupInputs();
  22837. }
  22838. if (camera.setPosition) { // need to force position
  22839. camera.position.copyFromFloats(0, 0, 0);
  22840. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22841. }
  22842. // Target
  22843. if (parsedCamera.target) {
  22844. if (camera.setTarget) {
  22845. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22846. }
  22847. }
  22848. // Apply 3d rig, when found
  22849. if (parsedCamera.cameraRigMode) {
  22850. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22851. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22852. }
  22853. // Animations
  22854. if (parsedCamera.animations) {
  22855. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22856. var parsedAnimation = parsedCamera.animations[animationIndex];
  22857. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22858. }
  22859. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22860. }
  22861. if (parsedCamera.autoAnimate) {
  22862. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22863. }
  22864. return camera;
  22865. };
  22866. // Statics
  22867. Camera._PERSPECTIVE_CAMERA = 0;
  22868. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22869. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22870. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22871. Camera._RIG_MODE_NONE = 0;
  22872. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22873. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22874. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22875. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22876. Camera._RIG_MODE_VR = 20;
  22877. Camera._RIG_MODE_WEBVR = 21;
  22878. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22879. Camera.UseAlternateWebVRRendering = false;
  22880. __decorate([
  22881. BABYLON.serializeAsVector3()
  22882. ], Camera.prototype, "position", void 0);
  22883. __decorate([
  22884. BABYLON.serializeAsVector3()
  22885. ], Camera.prototype, "upVector", void 0);
  22886. __decorate([
  22887. BABYLON.serialize()
  22888. ], Camera.prototype, "orthoLeft", void 0);
  22889. __decorate([
  22890. BABYLON.serialize()
  22891. ], Camera.prototype, "orthoRight", void 0);
  22892. __decorate([
  22893. BABYLON.serialize()
  22894. ], Camera.prototype, "orthoBottom", void 0);
  22895. __decorate([
  22896. BABYLON.serialize()
  22897. ], Camera.prototype, "orthoTop", void 0);
  22898. __decorate([
  22899. BABYLON.serialize()
  22900. ], Camera.prototype, "fov", void 0);
  22901. __decorate([
  22902. BABYLON.serialize()
  22903. ], Camera.prototype, "minZ", void 0);
  22904. __decorate([
  22905. BABYLON.serialize()
  22906. ], Camera.prototype, "maxZ", void 0);
  22907. __decorate([
  22908. BABYLON.serialize()
  22909. ], Camera.prototype, "inertia", void 0);
  22910. __decorate([
  22911. BABYLON.serialize()
  22912. ], Camera.prototype, "mode", void 0);
  22913. __decorate([
  22914. BABYLON.serialize()
  22915. ], Camera.prototype, "layerMask", void 0);
  22916. __decorate([
  22917. BABYLON.serialize()
  22918. ], Camera.prototype, "fovMode", void 0);
  22919. __decorate([
  22920. BABYLON.serialize()
  22921. ], Camera.prototype, "cameraRigMode", void 0);
  22922. __decorate([
  22923. BABYLON.serialize()
  22924. ], Camera.prototype, "interaxialDistance", void 0);
  22925. __decorate([
  22926. BABYLON.serialize()
  22927. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22928. return Camera;
  22929. }(BABYLON.Node));
  22930. BABYLON.Camera = Camera;
  22931. })(BABYLON || (BABYLON = {}));
  22932. //# sourceMappingURL=babylon.camera.js.map
  22933. var BABYLON;
  22934. (function (BABYLON) {
  22935. var RenderingManager = /** @class */ (function () {
  22936. function RenderingManager(scene) {
  22937. this._renderingGroups = new Array();
  22938. this._autoClearDepthStencil = {};
  22939. this._customOpaqueSortCompareFn = {};
  22940. this._customAlphaTestSortCompareFn = {};
  22941. this._customTransparentSortCompareFn = {};
  22942. this._renderinGroupInfo = null;
  22943. this._scene = scene;
  22944. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22945. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22946. }
  22947. }
  22948. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22949. if (depth === void 0) { depth = true; }
  22950. if (stencil === void 0) { stencil = true; }
  22951. if (this._depthStencilBufferAlreadyCleaned) {
  22952. return;
  22953. }
  22954. this._scene.getEngine().clear(null, false, depth, stencil);
  22955. this._depthStencilBufferAlreadyCleaned = true;
  22956. };
  22957. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22958. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22959. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22960. var info = null;
  22961. if (observable) {
  22962. if (!this._renderinGroupInfo) {
  22963. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22964. }
  22965. info = this._renderinGroupInfo;
  22966. info.scene = this._scene;
  22967. info.camera = this._scene.activeCamera;
  22968. }
  22969. // Dispatch sprites
  22970. if (renderSprites) {
  22971. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22972. var manager = this._scene.spriteManagers[index];
  22973. this.dispatchSprites(manager);
  22974. }
  22975. }
  22976. // Render
  22977. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22978. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22979. var renderingGroup = this._renderingGroups[index];
  22980. if (!renderingGroup && !observable)
  22981. continue;
  22982. var renderingGroupMask = 0;
  22983. // Fire PRECLEAR stage
  22984. if (observable && info) {
  22985. renderingGroupMask = Math.pow(2, index);
  22986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22987. info.renderingGroupId = index;
  22988. observable.notifyObservers(info, renderingGroupMask);
  22989. }
  22990. // Clear depth/stencil if needed
  22991. if (RenderingManager.AUTOCLEAR) {
  22992. var autoClear = this._autoClearDepthStencil[index];
  22993. if (autoClear && autoClear.autoClear) {
  22994. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22995. }
  22996. }
  22997. if (observable && info) {
  22998. // Fire PREOPAQUE stage
  22999. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23000. observable.notifyObservers(info, renderingGroupMask);
  23001. // Fire PRETRANSPARENT stage
  23002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23003. observable.notifyObservers(info, renderingGroupMask);
  23004. }
  23005. if (renderingGroup)
  23006. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23007. // Fire POSTTRANSPARENT stage
  23008. if (observable && info) {
  23009. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23010. observable.notifyObservers(info, renderingGroupMask);
  23011. }
  23012. }
  23013. };
  23014. RenderingManager.prototype.reset = function () {
  23015. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23016. var renderingGroup = this._renderingGroups[index];
  23017. if (renderingGroup) {
  23018. renderingGroup.prepare();
  23019. }
  23020. }
  23021. };
  23022. RenderingManager.prototype.dispose = function () {
  23023. this.freeRenderingGroups();
  23024. this._renderingGroups.length = 0;
  23025. };
  23026. /**
  23027. * Clear the info related to rendering groups preventing retention points during dispose.
  23028. */
  23029. RenderingManager.prototype.freeRenderingGroups = function () {
  23030. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23031. var renderingGroup = this._renderingGroups[index];
  23032. if (renderingGroup) {
  23033. renderingGroup.dispose();
  23034. }
  23035. }
  23036. };
  23037. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23038. if (this._renderingGroups[renderingGroupId] === undefined) {
  23039. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23040. }
  23041. };
  23042. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23043. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23044. this._prepareRenderingGroup(renderingGroupId);
  23045. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23046. };
  23047. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23048. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23049. this._prepareRenderingGroup(renderingGroupId);
  23050. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23051. };
  23052. /**
  23053. * @param subMesh The submesh to dispatch
  23054. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23055. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23056. */
  23057. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23058. if (mesh === undefined) {
  23059. mesh = subMesh.getMesh();
  23060. }
  23061. var renderingGroupId = mesh.renderingGroupId || 0;
  23062. this._prepareRenderingGroup(renderingGroupId);
  23063. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23064. };
  23065. /**
  23066. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23067. * This allowed control for front to back rendering or reversly depending of the special needs.
  23068. *
  23069. * @param renderingGroupId The rendering group id corresponding to its index
  23070. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23071. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23072. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23073. */
  23074. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23075. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23076. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23077. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23078. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23079. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23080. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23081. if (this._renderingGroups[renderingGroupId]) {
  23082. var group = this._renderingGroups[renderingGroupId];
  23083. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23084. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23085. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23086. }
  23087. };
  23088. /**
  23089. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23090. *
  23091. * @param renderingGroupId The rendering group id corresponding to its index
  23092. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23093. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23094. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23095. */
  23096. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23097. if (depth === void 0) { depth = true; }
  23098. if (stencil === void 0) { stencil = true; }
  23099. this._autoClearDepthStencil[renderingGroupId] = {
  23100. autoClear: autoClearDepthStencil,
  23101. depth: depth,
  23102. stencil: stencil
  23103. };
  23104. };
  23105. /**
  23106. * The max id used for rendering groups (not included)
  23107. */
  23108. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23109. /**
  23110. * The min id used for rendering groups (included)
  23111. */
  23112. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23113. /**
  23114. * Used to globally prevent autoclearing scenes.
  23115. */
  23116. RenderingManager.AUTOCLEAR = true;
  23117. return RenderingManager;
  23118. }());
  23119. BABYLON.RenderingManager = RenderingManager;
  23120. })(BABYLON || (BABYLON = {}));
  23121. //# sourceMappingURL=babylon.renderingManager.js.map
  23122. var BABYLON;
  23123. (function (BABYLON) {
  23124. var RenderingGroup = /** @class */ (function () {
  23125. /**
  23126. * Creates a new rendering group.
  23127. * @param index The rendering group index
  23128. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23129. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23130. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23131. */
  23132. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23133. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23134. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23135. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23136. this.index = index;
  23137. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23138. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23139. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23140. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23141. this._particleSystems = new BABYLON.SmartArray(256);
  23142. this._spriteManagers = new BABYLON.SmartArray(256);
  23143. this._edgesRenderers = new BABYLON.SmartArray(16);
  23144. this._scene = scene;
  23145. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23146. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23147. this.transparentSortCompareFn = transparentSortCompareFn;
  23148. }
  23149. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23150. /**
  23151. * Set the opaque sort comparison function.
  23152. * If null the sub meshes will be render in the order they were created
  23153. */
  23154. set: function (value) {
  23155. this._opaqueSortCompareFn = value;
  23156. if (value) {
  23157. this._renderOpaque = this.renderOpaqueSorted;
  23158. }
  23159. else {
  23160. this._renderOpaque = RenderingGroup.renderUnsorted;
  23161. }
  23162. },
  23163. enumerable: true,
  23164. configurable: true
  23165. });
  23166. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23167. /**
  23168. * Set the alpha test sort comparison function.
  23169. * If null the sub meshes will be render in the order they were created
  23170. */
  23171. set: function (value) {
  23172. this._alphaTestSortCompareFn = value;
  23173. if (value) {
  23174. this._renderAlphaTest = this.renderAlphaTestSorted;
  23175. }
  23176. else {
  23177. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23178. }
  23179. },
  23180. enumerable: true,
  23181. configurable: true
  23182. });
  23183. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23184. /**
  23185. * Set the transparent sort comparison function.
  23186. * If null the sub meshes will be render in the order they were created
  23187. */
  23188. set: function (value) {
  23189. if (value) {
  23190. this._transparentSortCompareFn = value;
  23191. }
  23192. else {
  23193. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23194. }
  23195. this._renderTransparent = this.renderTransparentSorted;
  23196. },
  23197. enumerable: true,
  23198. configurable: true
  23199. });
  23200. /**
  23201. * Render all the sub meshes contained in the group.
  23202. * @param customRenderFunction Used to override the default render behaviour of the group.
  23203. * @returns true if rendered some submeshes.
  23204. */
  23205. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23206. if (customRenderFunction) {
  23207. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23208. return;
  23209. }
  23210. var engine = this._scene.getEngine();
  23211. // Depth only
  23212. if (this._depthOnlySubMeshes.length !== 0) {
  23213. engine.setColorWrite(false);
  23214. this._renderAlphaTest(this._depthOnlySubMeshes);
  23215. engine.setColorWrite(true);
  23216. }
  23217. // Opaque
  23218. if (this._opaqueSubMeshes.length !== 0) {
  23219. this._renderOpaque(this._opaqueSubMeshes);
  23220. }
  23221. // Alpha test
  23222. if (this._alphaTestSubMeshes.length !== 0) {
  23223. this._renderAlphaTest(this._alphaTestSubMeshes);
  23224. }
  23225. var stencilState = engine.getStencilBuffer();
  23226. engine.setStencilBuffer(false);
  23227. // Sprites
  23228. if (renderSprites) {
  23229. this._renderSprites();
  23230. }
  23231. // Particles
  23232. if (renderParticles) {
  23233. this._renderParticles(activeMeshes);
  23234. }
  23235. if (this.onBeforeTransparentRendering) {
  23236. this.onBeforeTransparentRendering();
  23237. }
  23238. // Transparent
  23239. if (this._transparentSubMeshes.length !== 0) {
  23240. this._renderTransparent(this._transparentSubMeshes);
  23241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23242. }
  23243. // Set back stencil to false in case it changes before the edge renderer.
  23244. engine.setStencilBuffer(false);
  23245. // Edges
  23246. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23247. this._edgesRenderers.data[edgesRendererIndex].render();
  23248. }
  23249. // Restore Stencil state.
  23250. engine.setStencilBuffer(stencilState);
  23251. };
  23252. /**
  23253. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23254. * @param subMeshes The submeshes to render
  23255. */
  23256. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23257. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23258. };
  23259. /**
  23260. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23261. * @param subMeshes The submeshes to render
  23262. */
  23263. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23264. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23265. };
  23266. /**
  23267. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23268. * @param subMeshes The submeshes to render
  23269. */
  23270. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23271. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23272. };
  23273. /**
  23274. * Renders the submeshes in a specified order.
  23275. * @param subMeshes The submeshes to sort before render
  23276. * @param sortCompareFn The comparison function use to sort
  23277. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23278. * @param transparent Specifies to activate blending if true
  23279. */
  23280. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23281. var subIndex = 0;
  23282. var subMesh;
  23283. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23284. for (; subIndex < subMeshes.length; subIndex++) {
  23285. subMesh = subMeshes.data[subIndex];
  23286. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23287. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23288. }
  23289. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23290. if (sortCompareFn) {
  23291. sortedArray.sort(sortCompareFn);
  23292. }
  23293. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23294. subMesh = sortedArray[subIndex];
  23295. if (transparent) {
  23296. var material = subMesh.getMaterial();
  23297. if (material && material.needDepthPrePass) {
  23298. var engine = material.getScene().getEngine();
  23299. engine.setColorWrite(false);
  23300. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23301. subMesh.render(false);
  23302. engine.setColorWrite(true);
  23303. }
  23304. }
  23305. subMesh.render(transparent);
  23306. }
  23307. };
  23308. /**
  23309. * Renders the submeshes in the order they were dispatched (no sort applied).
  23310. * @param subMeshes The submeshes to render
  23311. */
  23312. RenderingGroup.renderUnsorted = function (subMeshes) {
  23313. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23314. var submesh = subMeshes.data[subIndex];
  23315. submesh.render(false);
  23316. }
  23317. };
  23318. /**
  23319. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23320. * are rendered back to front if in the same alpha index.
  23321. *
  23322. * @param a The first submesh
  23323. * @param b The second submesh
  23324. * @returns The result of the comparison
  23325. */
  23326. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23327. // Alpha index first
  23328. if (a._alphaIndex > b._alphaIndex) {
  23329. return 1;
  23330. }
  23331. if (a._alphaIndex < b._alphaIndex) {
  23332. return -1;
  23333. }
  23334. // Then distance to camera
  23335. return RenderingGroup.backToFrontSortCompare(a, b);
  23336. };
  23337. /**
  23338. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23339. * are rendered back to front.
  23340. *
  23341. * @param a The first submesh
  23342. * @param b The second submesh
  23343. * @returns The result of the comparison
  23344. */
  23345. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23346. // Then distance to camera
  23347. if (a._distanceToCamera < b._distanceToCamera) {
  23348. return 1;
  23349. }
  23350. if (a._distanceToCamera > b._distanceToCamera) {
  23351. return -1;
  23352. }
  23353. return 0;
  23354. };
  23355. /**
  23356. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23357. * are rendered front to back (prevent overdraw).
  23358. *
  23359. * @param a The first submesh
  23360. * @param b The second submesh
  23361. * @returns The result of the comparison
  23362. */
  23363. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23364. // Then distance to camera
  23365. if (a._distanceToCamera < b._distanceToCamera) {
  23366. return -1;
  23367. }
  23368. if (a._distanceToCamera > b._distanceToCamera) {
  23369. return 1;
  23370. }
  23371. return 0;
  23372. };
  23373. /**
  23374. * Resets the different lists of submeshes to prepare a new frame.
  23375. */
  23376. RenderingGroup.prototype.prepare = function () {
  23377. this._opaqueSubMeshes.reset();
  23378. this._transparentSubMeshes.reset();
  23379. this._alphaTestSubMeshes.reset();
  23380. this._depthOnlySubMeshes.reset();
  23381. this._particleSystems.reset();
  23382. this._spriteManagers.reset();
  23383. this._edgesRenderers.reset();
  23384. };
  23385. RenderingGroup.prototype.dispose = function () {
  23386. this._opaqueSubMeshes.dispose();
  23387. this._transparentSubMeshes.dispose();
  23388. this._alphaTestSubMeshes.dispose();
  23389. this._depthOnlySubMeshes.dispose();
  23390. this._particleSystems.dispose();
  23391. this._spriteManagers.dispose();
  23392. this._edgesRenderers.dispose();
  23393. };
  23394. /**
  23395. * Inserts the submesh in its correct queue depending on its material.
  23396. * @param subMesh The submesh to dispatch
  23397. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23398. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23399. */
  23400. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23401. // Get mesh and materials if not provided
  23402. if (mesh === undefined) {
  23403. mesh = subMesh.getMesh();
  23404. }
  23405. if (material === undefined) {
  23406. material = subMesh.getMaterial();
  23407. }
  23408. if (material === null || material === undefined) {
  23409. return;
  23410. }
  23411. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23412. this._transparentSubMeshes.push(subMesh);
  23413. }
  23414. else if (material.needAlphaTesting()) { // Alpha test
  23415. if (material.needDepthPrePass) {
  23416. this._depthOnlySubMeshes.push(subMesh);
  23417. }
  23418. this._alphaTestSubMeshes.push(subMesh);
  23419. }
  23420. else {
  23421. if (material.needDepthPrePass) {
  23422. this._depthOnlySubMeshes.push(subMesh);
  23423. }
  23424. this._opaqueSubMeshes.push(subMesh); // Opaque
  23425. }
  23426. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23427. this._edgesRenderers.push(mesh._edgesRenderer);
  23428. }
  23429. };
  23430. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23431. this._spriteManagers.push(spriteManager);
  23432. };
  23433. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23434. this._particleSystems.push(particleSystem);
  23435. };
  23436. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23437. if (this._particleSystems.length === 0) {
  23438. return;
  23439. }
  23440. // Particles
  23441. var activeCamera = this._scene.activeCamera;
  23442. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23443. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23444. var particleSystem = this._particleSystems.data[particleIndex];
  23445. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23446. continue;
  23447. }
  23448. var emitter = particleSystem.emitter;
  23449. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23450. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23451. }
  23452. }
  23453. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23454. };
  23455. RenderingGroup.prototype._renderSprites = function () {
  23456. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23457. return;
  23458. }
  23459. // Sprites
  23460. var activeCamera = this._scene.activeCamera;
  23461. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23462. for (var id = 0; id < this._spriteManagers.length; id++) {
  23463. var spriteManager = this._spriteManagers.data[id];
  23464. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23465. spriteManager.render();
  23466. }
  23467. }
  23468. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23469. };
  23470. return RenderingGroup;
  23471. }());
  23472. BABYLON.RenderingGroup = RenderingGroup;
  23473. })(BABYLON || (BABYLON = {}));
  23474. //# sourceMappingURL=babylon.renderingGroup.js.map
  23475. var BABYLON;
  23476. (function (BABYLON) {
  23477. /** @hidden */
  23478. var ClickInfo = /** @class */ (function () {
  23479. function ClickInfo() {
  23480. this._singleClick = false;
  23481. this._doubleClick = false;
  23482. this._hasSwiped = false;
  23483. this._ignore = false;
  23484. }
  23485. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23486. get: function () {
  23487. return this._singleClick;
  23488. },
  23489. set: function (b) {
  23490. this._singleClick = b;
  23491. },
  23492. enumerable: true,
  23493. configurable: true
  23494. });
  23495. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23496. get: function () {
  23497. return this._doubleClick;
  23498. },
  23499. set: function (b) {
  23500. this._doubleClick = b;
  23501. },
  23502. enumerable: true,
  23503. configurable: true
  23504. });
  23505. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23506. get: function () {
  23507. return this._hasSwiped;
  23508. },
  23509. set: function (b) {
  23510. this._hasSwiped = b;
  23511. },
  23512. enumerable: true,
  23513. configurable: true
  23514. });
  23515. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23516. get: function () {
  23517. return this._ignore;
  23518. },
  23519. set: function (b) {
  23520. this._ignore = b;
  23521. },
  23522. enumerable: true,
  23523. configurable: true
  23524. });
  23525. return ClickInfo;
  23526. }());
  23527. /**
  23528. * This class is used by the onRenderingGroupObservable
  23529. */
  23530. var RenderingGroupInfo = /** @class */ (function () {
  23531. function RenderingGroupInfo() {
  23532. }
  23533. /**
  23534. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23535. * This stage will be fired no matter what
  23536. */
  23537. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23538. /**
  23539. * Called before opaque object are rendered.
  23540. * This stage will be fired only if there's 3D Opaque content to render
  23541. */
  23542. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23543. /**
  23544. * Called after the opaque objects are rendered and before the transparent ones
  23545. * This stage will be fired only if there's 3D transparent content to render
  23546. */
  23547. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23548. /**
  23549. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23550. * This stage will be fired no matter what
  23551. */
  23552. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23553. return RenderingGroupInfo;
  23554. }());
  23555. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23556. /**
  23557. * Represents a scene to be rendered by the engine.
  23558. * @see http://doc.babylonjs.com/features/scene
  23559. */
  23560. var Scene = /** @class */ (function () {
  23561. /**
  23562. * Creates a new Scene
  23563. * @param engine defines the engine to use to render this scene
  23564. */
  23565. function Scene(engine) {
  23566. // Members
  23567. /**
  23568. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23569. */
  23570. this.autoClear = true;
  23571. /**
  23572. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23573. */
  23574. this.autoClearDepthAndStencil = true;
  23575. /**
  23576. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23577. */
  23578. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23579. /**
  23580. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23581. */
  23582. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23583. this._forceWireframe = false;
  23584. this._forcePointsCloud = false;
  23585. /**
  23586. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23587. */
  23588. this.forceShowBoundingBoxes = false;
  23589. /**
  23590. * Gets or sets a boolean indicating if animations are enabled
  23591. */
  23592. this.animationsEnabled = true;
  23593. this._animationPropertiesOverride = null;
  23594. /**
  23595. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23596. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23597. */
  23598. this.useConstantAnimationDeltaTime = false;
  23599. /**
  23600. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23601. * Please note that it requires to run a ray cast through the scene on every frame
  23602. */
  23603. this.constantlyUpdateMeshUnderPointer = false;
  23604. /**
  23605. * Defines the HTML cursor to use when hovering over interactive elements
  23606. */
  23607. this.hoverCursor = "pointer";
  23608. /**
  23609. * Defines the HTML default cursor to use (empty by default)
  23610. */
  23611. this.defaultCursor = "";
  23612. /**
  23613. * This is used to call preventDefault() on pointer down
  23614. * in order to block unwanted artifacts like system double clicks
  23615. */
  23616. this.preventDefaultOnPointerDown = true;
  23617. // Metadata
  23618. /**
  23619. * Gets or sets user defined metadata
  23620. */
  23621. this.metadata = null;
  23622. /**
  23623. * Use this array to add regular expressions used to disable offline support for specific urls
  23624. */
  23625. this.disableOfflineSupportExceptionRules = new Array();
  23626. /**
  23627. * An event triggered when the scene is disposed.
  23628. */
  23629. this.onDisposeObservable = new BABYLON.Observable();
  23630. this._onDisposeObserver = null;
  23631. /**
  23632. * An event triggered before rendering the scene (right after animations and physics)
  23633. */
  23634. this.onBeforeRenderObservable = new BABYLON.Observable();
  23635. this._onBeforeRenderObserver = null;
  23636. /**
  23637. * An event triggered after rendering the scene
  23638. */
  23639. this.onAfterRenderObservable = new BABYLON.Observable();
  23640. this._onAfterRenderObserver = null;
  23641. /**
  23642. * An event triggered before animating the scene
  23643. */
  23644. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23645. /**
  23646. * An event triggered after animations processing
  23647. */
  23648. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23649. /**
  23650. * An event triggered before draw calls are ready to be sent
  23651. */
  23652. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered after draw calls have been sent
  23655. */
  23656. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when physic simulation is about to be run
  23659. */
  23660. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23661. /**
  23662. * An event triggered when physic simulation has been done
  23663. */
  23664. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23665. /**
  23666. * An event triggered when the scene is ready
  23667. */
  23668. this.onReadyObservable = new BABYLON.Observable();
  23669. /**
  23670. * An event triggered before rendering a camera
  23671. */
  23672. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23673. this._onBeforeCameraRenderObserver = null;
  23674. /**
  23675. * An event triggered after rendering a camera
  23676. */
  23677. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23678. this._onAfterCameraRenderObserver = null;
  23679. /**
  23680. * An event triggered when active meshes evaluation is about to start
  23681. */
  23682. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23683. /**
  23684. * An event triggered when active meshes evaluation is done
  23685. */
  23686. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23687. /**
  23688. * An event triggered when particles rendering is about to start
  23689. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23690. */
  23691. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23692. /**
  23693. * An event triggered when particles rendering is done
  23694. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23695. */
  23696. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23697. /**
  23698. * An event triggered when sprites rendering is about to start
  23699. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23700. */
  23701. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when sprites rendering is done
  23704. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23705. */
  23706. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23709. */
  23710. this.onDataLoadedObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when a camera is created
  23713. */
  23714. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23715. /**
  23716. * An event triggered when a camera is removed
  23717. */
  23718. this.onCameraRemovedObservable = new BABYLON.Observable();
  23719. /**
  23720. * An event triggered when a light is created
  23721. */
  23722. this.onNewLightAddedObservable = new BABYLON.Observable();
  23723. /**
  23724. * An event triggered when a light is removed
  23725. */
  23726. this.onLightRemovedObservable = new BABYLON.Observable();
  23727. /**
  23728. * An event triggered when a geometry is created
  23729. */
  23730. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23731. /**
  23732. * An event triggered when a geometry is removed
  23733. */
  23734. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23735. /**
  23736. * An event triggered when a transform node is created
  23737. */
  23738. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23739. /**
  23740. * An event triggered when a transform node is removed
  23741. */
  23742. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23743. /**
  23744. * An event triggered when a mesh is created
  23745. */
  23746. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23747. /**
  23748. * An event triggered when a mesh is removed
  23749. */
  23750. this.onMeshRemovedObservable = new BABYLON.Observable();
  23751. /**
  23752. * An event triggered when render targets are about to be rendered
  23753. * Can happen multiple times per frame.
  23754. */
  23755. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when render targets were rendered.
  23758. * Can happen multiple times per frame.
  23759. */
  23760. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23761. /**
  23762. * An event triggered before calculating deterministic simulation step
  23763. */
  23764. this.onBeforeStepObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered after calculating deterministic simulation step
  23767. */
  23768. this.onAfterStepObservable = new BABYLON.Observable();
  23769. /**
  23770. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23771. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23772. * 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)
  23773. */
  23774. this.onRenderingGroupObservable = new BABYLON.Observable();
  23775. // Animations
  23776. /**
  23777. * Gets a list of Animations associated with the scene
  23778. */
  23779. this.animations = [];
  23780. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23781. /**
  23782. * 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).
  23783. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23784. */
  23785. this.onPrePointerObservable = new BABYLON.Observable();
  23786. /**
  23787. * Observable event triggered each time an input event is received from the rendering canvas
  23788. */
  23789. this.onPointerObservable = new BABYLON.Observable();
  23790. this._meshPickProceed = false;
  23791. this._currentPickResult = null;
  23792. this._previousPickResult = null;
  23793. this._totalPointersPressed = 0;
  23794. this._doubleClickOccured = false;
  23795. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23796. this.cameraToUseForPointers = null;
  23797. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23798. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23799. this._startingPointerTime = 0;
  23800. this._previousStartingPointerTime = 0;
  23801. this._pointerCaptures = {};
  23802. // Deterministic lockstep
  23803. this._timeAccumulator = 0;
  23804. this._currentStepId = 0;
  23805. this._currentInternalStep = 0;
  23806. // Keyboard
  23807. /**
  23808. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23809. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23810. */
  23811. this.onPreKeyboardObservable = new BABYLON.Observable();
  23812. /**
  23813. * Observable event triggered each time an keyboard event is received from the hosting window
  23814. */
  23815. this.onKeyboardObservable = new BABYLON.Observable();
  23816. // Coordinates system
  23817. this._useRightHandedSystem = false;
  23818. // Fog
  23819. this._fogEnabled = true;
  23820. this._fogMode = Scene.FOGMODE_NONE;
  23821. /**
  23822. * Gets or sets the fog color to use
  23823. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23824. */
  23825. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23826. /**
  23827. * Gets or sets the fog density to use
  23828. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23829. */
  23830. this.fogDensity = 0.1;
  23831. /**
  23832. * Gets or sets the fog start distance to use
  23833. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23834. */
  23835. this.fogStart = 0;
  23836. /**
  23837. * Gets or sets the fog end distance to use
  23838. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23839. */
  23840. this.fogEnd = 1000.0;
  23841. // Lights
  23842. this._shadowsEnabled = true;
  23843. this._lightsEnabled = true;
  23844. /**
  23845. * All of the lights added to this scene
  23846. * @see http://doc.babylonjs.com/babylon101/lights
  23847. */
  23848. this.lights = new Array();
  23849. // Cameras
  23850. /** All of the cameras added to this scene.
  23851. * @see http://doc.babylonjs.com/babylon101/cameras
  23852. */
  23853. this.cameras = new Array();
  23854. /** All of the active cameras added to this scene. */
  23855. this.activeCameras = new Array();
  23856. // Meshes
  23857. /**
  23858. * All of the tranform nodes added to this scene
  23859. * @see http://doc.babylonjs.com/how_to/transformnode
  23860. */
  23861. this.transformNodes = new Array();
  23862. /**
  23863. * All of the (abstract) meshes added to this scene
  23864. */
  23865. this.meshes = new Array();
  23866. /**
  23867. * All of the animation groups added to this scene
  23868. * @see http://doc.babylonjs.com/how_to/group
  23869. */
  23870. this.animationGroups = new Array();
  23871. // Geometries
  23872. this._geometries = new Array();
  23873. /**
  23874. * All of the materials added to this scene
  23875. * @see http://doc.babylonjs.com/babylon101/materials
  23876. */
  23877. this.materials = new Array();
  23878. /**
  23879. * All of the multi-materials added to this scene
  23880. * @see http://doc.babylonjs.com/how_to/multi_materials
  23881. */
  23882. this.multiMaterials = new Array();
  23883. // Textures
  23884. this._texturesEnabled = true;
  23885. /**
  23886. * All of the textures added to this scene
  23887. */
  23888. this.textures = new Array();
  23889. // Particles
  23890. /**
  23891. * Gets or sets a boolean indicating if particles are enabled on this scene
  23892. */
  23893. this.particlesEnabled = true;
  23894. /**
  23895. * All of the particle systems added to this scene
  23896. * @see http://doc.babylonjs.com/babylon101/particles
  23897. */
  23898. this.particleSystems = new Array();
  23899. // Sprites
  23900. /**
  23901. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23902. */
  23903. this.spritesEnabled = true;
  23904. /**
  23905. * All of the sprite managers added to this scene
  23906. * @see http://doc.babylonjs.com/babylon101/sprites
  23907. */
  23908. this.spriteManagers = new Array();
  23909. /**
  23910. * The list of layers (background and foreground) of the scene
  23911. */
  23912. this.layers = new Array();
  23913. /**
  23914. * The list of effect layers (highlights/glow) added to the scene
  23915. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23916. * @see http://doc.babylonjs.com/how_to/glow_layer
  23917. */
  23918. this.effectLayers = new Array();
  23919. // Skeletons
  23920. this._skeletonsEnabled = true;
  23921. /**
  23922. * The list of skeletons added to the scene
  23923. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23924. */
  23925. this.skeletons = new Array();
  23926. // Morph targets
  23927. /**
  23928. * The list of morph target managers added to the scene
  23929. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23930. */
  23931. this.morphTargetManagers = new Array();
  23932. // Lens flares
  23933. /**
  23934. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23935. */
  23936. this.lensFlaresEnabled = true;
  23937. /**
  23938. * The list of lens flare system added to the scene
  23939. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23940. */
  23941. this.lensFlareSystems = new Array();
  23942. // Collisions
  23943. /**
  23944. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23945. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23946. */
  23947. this.collisionsEnabled = true;
  23948. /**
  23949. * Defines the gravity applied to this scene (used only for collisions)
  23950. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23951. */
  23952. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23953. // Postprocesses
  23954. /**
  23955. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23956. */
  23957. this.postProcessesEnabled = true;
  23958. /**
  23959. * The list of postprocesses added to the scene
  23960. */
  23961. this.postProcesses = new Array();
  23962. // Customs render targets
  23963. /**
  23964. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23965. */
  23966. this.renderTargetsEnabled = true;
  23967. /**
  23968. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23969. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23970. */
  23971. this.dumpNextRenderTargets = false;
  23972. /**
  23973. * The list of user defined render targets added to the scene
  23974. */
  23975. this.customRenderTargets = new Array();
  23976. /**
  23977. * Gets the list of meshes imported to the scene through SceneLoader
  23978. */
  23979. this.importedMeshesFiles = new Array();
  23980. // Probes
  23981. /**
  23982. * Gets or sets a boolean indicating if probes are enabled on this scene
  23983. */
  23984. this.probesEnabled = true;
  23985. /**
  23986. * The list of reflection probes added to the scene
  23987. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23988. */
  23989. this.reflectionProbes = new Array();
  23990. /** @hidden */
  23991. this._actionManagers = new Array();
  23992. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23993. // Procedural textures
  23994. /**
  23995. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23996. */
  23997. this.proceduralTexturesEnabled = true;
  23998. /**
  23999. * The list of procedural textures added to the scene
  24000. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24001. */
  24002. this.proceduralTextures = new Array();
  24003. /**
  24004. * The list of sound tracks added to the scene
  24005. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24006. */
  24007. this.soundTracks = new Array();
  24008. this._audioEnabled = true;
  24009. this._headphone = false;
  24010. // Performance counters
  24011. this._totalVertices = new BABYLON.PerfCounter();
  24012. /** @hidden */
  24013. this._activeIndices = new BABYLON.PerfCounter();
  24014. /** @hidden */
  24015. this._activeParticles = new BABYLON.PerfCounter();
  24016. /** @hidden */
  24017. this._activeBones = new BABYLON.PerfCounter();
  24018. this._animationTime = 0;
  24019. /**
  24020. * Gets or sets a general scale for animation speed
  24021. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24022. */
  24023. this.animationTimeScale = 1;
  24024. this._renderId = 0;
  24025. this._executeWhenReadyTimeoutId = -1;
  24026. this._intermediateRendering = false;
  24027. this._viewUpdateFlag = -1;
  24028. this._projectionUpdateFlag = -1;
  24029. this._alternateViewUpdateFlag = -1;
  24030. this._alternateProjectionUpdateFlag = -1;
  24031. /** @hidden */
  24032. this._toBeDisposed = new BABYLON.SmartArray(256);
  24033. this._activeRequests = new Array();
  24034. this._pendingData = new Array();
  24035. this._isDisposed = false;
  24036. /**
  24037. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24038. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24039. */
  24040. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24041. this._activeMeshes = new BABYLON.SmartArray(256);
  24042. this._processedMaterials = new BABYLON.SmartArray(256);
  24043. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24044. /** @hidden */
  24045. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24046. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24047. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24048. /** @hidden */
  24049. this._activeAnimatables = new Array();
  24050. this._transformMatrix = BABYLON.Matrix.Zero();
  24051. this._useAlternateCameraConfiguration = false;
  24052. this._alternateRendering = false;
  24053. /**
  24054. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24055. * This is useful if there are more lights that the maximum simulteanous authorized
  24056. */
  24057. this.requireLightSorting = false;
  24058. this._depthRenderer = {};
  24059. this._activeMeshesFrozen = false;
  24060. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24061. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24062. this._engine.scenes.push(this);
  24063. this._uid = null;
  24064. this._renderingManager = new BABYLON.RenderingManager(this);
  24065. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24066. if (BABYLON.OutlineRenderer) {
  24067. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24068. }
  24069. if (BABYLON.Tools.IsWindowObjectExist()) {
  24070. this.attachControl();
  24071. }
  24072. //simplification queue
  24073. if (BABYLON.SimplificationQueue) {
  24074. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24075. }
  24076. //collision coordinator initialization. For now legacy per default.
  24077. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24078. // Uniform Buffer
  24079. this._createUbo();
  24080. // Default Image processing definition.
  24081. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24082. }
  24083. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24084. /** The fog is deactivated */
  24085. get: function () {
  24086. return Scene._FOGMODE_NONE;
  24087. },
  24088. enumerable: true,
  24089. configurable: true
  24090. });
  24091. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24092. /** The fog density is following an exponential function */
  24093. get: function () {
  24094. return Scene._FOGMODE_EXP;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24100. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24101. get: function () {
  24102. return Scene._FOGMODE_EXP2;
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24108. /** The fog density is following a linear function. */
  24109. get: function () {
  24110. return Scene._FOGMODE_LINEAR;
  24111. },
  24112. enumerable: true,
  24113. configurable: true
  24114. });
  24115. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24116. /**
  24117. * Texture used in all pbr material as the reflection texture.
  24118. * As in the majority of the scene they are the same (exception for multi room and so on),
  24119. * this is easier to reference from here than from all the materials.
  24120. */
  24121. get: function () {
  24122. return this._environmentTexture;
  24123. },
  24124. /**
  24125. * Texture used in all pbr material as the reflection texture.
  24126. * As in the majority of the scene they are the same (exception for multi room and so on),
  24127. * this is easier to set here than in all the materials.
  24128. */
  24129. set: function (value) {
  24130. if (this._environmentTexture === value) {
  24131. return;
  24132. }
  24133. this._environmentTexture = value;
  24134. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24135. },
  24136. enumerable: true,
  24137. configurable: true
  24138. });
  24139. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24140. /**
  24141. * Default image processing configuration used either in the rendering
  24142. * Forward main pass or through the imageProcessingPostProcess if present.
  24143. * As in the majority of the scene they are the same (exception for multi camera),
  24144. * this is easier to reference from here than from all the materials and post process.
  24145. *
  24146. * No setter as we it is a shared configuration, you can set the values instead.
  24147. */
  24148. get: function () {
  24149. return this._imageProcessingConfiguration;
  24150. },
  24151. enumerable: true,
  24152. configurable: true
  24153. });
  24154. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24155. get: function () {
  24156. return this._forceWireframe;
  24157. },
  24158. /**
  24159. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24160. */
  24161. set: function (value) {
  24162. if (this._forceWireframe === value) {
  24163. return;
  24164. }
  24165. this._forceWireframe = value;
  24166. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24167. },
  24168. enumerable: true,
  24169. configurable: true
  24170. });
  24171. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24172. get: function () {
  24173. return this._forcePointsCloud;
  24174. },
  24175. /**
  24176. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24177. */
  24178. set: function (value) {
  24179. if (this._forcePointsCloud === value) {
  24180. return;
  24181. }
  24182. this._forcePointsCloud = value;
  24183. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24184. },
  24185. enumerable: true,
  24186. configurable: true
  24187. });
  24188. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24189. /**
  24190. * Gets or sets the animation properties override
  24191. */
  24192. get: function () {
  24193. return this._animationPropertiesOverride;
  24194. },
  24195. set: function (value) {
  24196. this._animationPropertiesOverride = value;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(Scene.prototype, "onDispose", {
  24202. /** Sets a function to be executed when this scene is disposed. */
  24203. set: function (callback) {
  24204. if (this._onDisposeObserver) {
  24205. this.onDisposeObservable.remove(this._onDisposeObserver);
  24206. }
  24207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(Scene.prototype, "beforeRender", {
  24213. /** Sets a function to be executed before rendering this scene */
  24214. set: function (callback) {
  24215. if (this._onBeforeRenderObserver) {
  24216. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24217. }
  24218. if (callback) {
  24219. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24220. }
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "afterRender", {
  24226. /** Sets a function to be executed after rendering this scene */
  24227. set: function (callback) {
  24228. if (this._onAfterRenderObserver) {
  24229. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24230. }
  24231. if (callback) {
  24232. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24233. }
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24239. /** Sets a function to be executed before rendering a camera*/
  24240. set: function (callback) {
  24241. if (this._onBeforeCameraRenderObserver) {
  24242. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24243. }
  24244. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24250. /** Sets a function to be executed after rendering a camera*/
  24251. set: function (callback) {
  24252. if (this._onAfterCameraRenderObserver) {
  24253. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24254. }
  24255. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24256. },
  24257. enumerable: true,
  24258. configurable: true
  24259. });
  24260. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24261. /**
  24262. * Gets the gamepad manager associated with the scene
  24263. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24264. */
  24265. get: function () {
  24266. if (!this._gamepadManager) {
  24267. this._gamepadManager = new BABYLON.GamepadManager(this);
  24268. }
  24269. return this._gamepadManager;
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24275. /**
  24276. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24277. */
  24278. get: function () {
  24279. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24285. get: function () {
  24286. return this._useRightHandedSystem;
  24287. },
  24288. /**
  24289. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24290. */
  24291. set: function (value) {
  24292. if (this._useRightHandedSystem === value) {
  24293. return;
  24294. }
  24295. this._useRightHandedSystem = value;
  24296. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24297. },
  24298. enumerable: true,
  24299. configurable: true
  24300. });
  24301. /**
  24302. * Sets the step Id used by deterministic lock step
  24303. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24304. * @param newStepId defines the step Id
  24305. */
  24306. Scene.prototype.setStepId = function (newStepId) {
  24307. this._currentStepId = newStepId;
  24308. };
  24309. ;
  24310. /**
  24311. * Gets the step Id used by deterministic lock step
  24312. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24313. * @returns the step Id
  24314. */
  24315. Scene.prototype.getStepId = function () {
  24316. return this._currentStepId;
  24317. };
  24318. ;
  24319. /**
  24320. * Gets the internal step used by deterministic lock step
  24321. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24322. * @returns the internal step
  24323. */
  24324. Scene.prototype.getInternalStep = function () {
  24325. return this._currentInternalStep;
  24326. };
  24327. ;
  24328. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24329. get: function () {
  24330. return this._fogEnabled;
  24331. },
  24332. /**
  24333. * Gets or sets a boolean indicating if fog is enabled on this scene
  24334. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24335. */
  24336. set: function (value) {
  24337. if (this._fogEnabled === value) {
  24338. return;
  24339. }
  24340. this._fogEnabled = value;
  24341. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Scene.prototype, "fogMode", {
  24347. get: function () {
  24348. return this._fogMode;
  24349. },
  24350. /**
  24351. * Gets or sets the fog mode to use
  24352. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24353. */
  24354. set: function (value) {
  24355. if (this._fogMode === value) {
  24356. return;
  24357. }
  24358. this._fogMode = value;
  24359. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24360. },
  24361. enumerable: true,
  24362. configurable: true
  24363. });
  24364. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24365. get: function () {
  24366. return this._shadowsEnabled;
  24367. },
  24368. /**
  24369. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24370. */
  24371. set: function (value) {
  24372. if (this._shadowsEnabled === value) {
  24373. return;
  24374. }
  24375. this._shadowsEnabled = value;
  24376. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24377. },
  24378. enumerable: true,
  24379. configurable: true
  24380. });
  24381. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24382. get: function () {
  24383. return this._lightsEnabled;
  24384. },
  24385. /**
  24386. * Gets or sets a boolean indicating if lights are enabled on this scene
  24387. */
  24388. set: function (value) {
  24389. if (this._lightsEnabled === value) {
  24390. return;
  24391. }
  24392. this._lightsEnabled = value;
  24393. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24394. },
  24395. enumerable: true,
  24396. configurable: true
  24397. });
  24398. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24399. /** The default material used on meshes when no material is affected */
  24400. get: function () {
  24401. if (!this._defaultMaterial) {
  24402. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24403. }
  24404. return this._defaultMaterial;
  24405. },
  24406. /** The default material used on meshes when no material is affected */
  24407. set: function (value) {
  24408. this._defaultMaterial = value;
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24414. get: function () {
  24415. return this._texturesEnabled;
  24416. },
  24417. /**
  24418. * Gets or sets a boolean indicating if textures are enabled on this scene
  24419. */
  24420. set: function (value) {
  24421. if (this._texturesEnabled === value) {
  24422. return;
  24423. }
  24424. this._texturesEnabled = value;
  24425. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24431. get: function () {
  24432. return this._skeletonsEnabled;
  24433. },
  24434. /**
  24435. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24436. */
  24437. set: function (value) {
  24438. if (this._skeletonsEnabled === value) {
  24439. return;
  24440. }
  24441. this._skeletonsEnabled = value;
  24442. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24448. /**
  24449. * Gets the postprocess render pipeline manager
  24450. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24451. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24452. */
  24453. get: function () {
  24454. if (!this._postProcessRenderPipelineManager) {
  24455. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24456. }
  24457. return this._postProcessRenderPipelineManager;
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24463. /**
  24464. * Gets the main soundtrack associated with the scene
  24465. */
  24466. get: function () {
  24467. if (!this._mainSoundTrack) {
  24468. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24469. }
  24470. return this._mainSoundTrack;
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24476. /** @hidden */
  24477. get: function () {
  24478. return this._alternateRendering;
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24484. /**
  24485. * Gets the list of frustum planes (built from the active camera)
  24486. */
  24487. get: function () {
  24488. return this._frustumPlanes;
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24494. /**
  24495. * Gets the current geometry buffer associated to the scene.
  24496. */
  24497. get: function () {
  24498. return this._geometryBufferRenderer;
  24499. },
  24500. /**
  24501. * Sets the current geometry buffer for the scene.
  24502. */
  24503. set: function (geometryBufferRenderer) {
  24504. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24505. this._geometryBufferRenderer = geometryBufferRenderer;
  24506. }
  24507. },
  24508. enumerable: true,
  24509. configurable: true
  24510. });
  24511. Object.defineProperty(Scene.prototype, "debugLayer", {
  24512. /**
  24513. * Gets the debug layer associated with the scene
  24514. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24515. */
  24516. get: function () {
  24517. if (!this._debugLayer) {
  24518. this._debugLayer = new BABYLON.DebugLayer(this);
  24519. }
  24520. return this._debugLayer;
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24526. /**
  24527. * Gets a boolean indicating if collisions are processed on a web worker
  24528. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24529. */
  24530. get: function () {
  24531. return this._workerCollisions;
  24532. },
  24533. set: function (enabled) {
  24534. if (!BABYLON.CollisionCoordinatorLegacy) {
  24535. return;
  24536. }
  24537. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24538. this._workerCollisions = enabled;
  24539. if (this.collisionCoordinator) {
  24540. this.collisionCoordinator.destroy();
  24541. }
  24542. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24543. this.collisionCoordinator.init(this);
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24549. /**
  24550. * Gets the octree used to boost mesh selection (picking)
  24551. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24552. */
  24553. get: function () {
  24554. return this._selectionOctree;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24560. /**
  24561. * Gets the mesh that is currently under the pointer
  24562. */
  24563. get: function () {
  24564. return this._pointerOverMesh;
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "pointerX", {
  24570. /**
  24571. * Gets the current on-screen X position of the pointer
  24572. */
  24573. get: function () {
  24574. return this._pointerX;
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "pointerY", {
  24580. /**
  24581. * Gets the current on-screen Y position of the pointer
  24582. */
  24583. get: function () {
  24584. return this._pointerY;
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. /**
  24590. * Gets the cached material (ie. the latest rendered one)
  24591. * @returns the cached material
  24592. */
  24593. Scene.prototype.getCachedMaterial = function () {
  24594. return this._cachedMaterial;
  24595. };
  24596. /**
  24597. * Gets the cached effect (ie. the latest rendered one)
  24598. * @returns the cached effect
  24599. */
  24600. Scene.prototype.getCachedEffect = function () {
  24601. return this._cachedEffect;
  24602. };
  24603. /**
  24604. * Gets the cached visibility state (ie. the latest rendered one)
  24605. * @returns the cached visibility state
  24606. */
  24607. Scene.prototype.getCachedVisibility = function () {
  24608. return this._cachedVisibility;
  24609. };
  24610. /**
  24611. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24612. * @param material defines the current material
  24613. * @param effect defines the current effect
  24614. * @param visibility defines the current visibility state
  24615. * @returns true if one parameter is not cached
  24616. */
  24617. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24618. if (visibility === void 0) { visibility = 1; }
  24619. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24620. };
  24621. /**
  24622. * Gets the bounding box renderer associated with the scene
  24623. * @returns a BoundingBoxRenderer
  24624. */
  24625. Scene.prototype.getBoundingBoxRenderer = function () {
  24626. if (!this._boundingBoxRenderer) {
  24627. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24628. }
  24629. return this._boundingBoxRenderer;
  24630. };
  24631. /**
  24632. * Gets the outline renderer associated with the scene
  24633. * @returns a OutlineRenderer
  24634. */
  24635. Scene.prototype.getOutlineRenderer = function () {
  24636. return this._outlineRenderer;
  24637. };
  24638. /**
  24639. * Gets the engine associated with the scene
  24640. * @returns an Engine
  24641. */
  24642. Scene.prototype.getEngine = function () {
  24643. return this._engine;
  24644. };
  24645. /**
  24646. * Gets the total number of vertices rendered per frame
  24647. * @returns the total number of vertices rendered per frame
  24648. */
  24649. Scene.prototype.getTotalVertices = function () {
  24650. return this._totalVertices.current;
  24651. };
  24652. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24653. /**
  24654. * Gets the performance counter for total vertices
  24655. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24656. */
  24657. get: function () {
  24658. return this._totalVertices;
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. /**
  24664. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24665. * @returns the total number of active indices rendered per frame
  24666. */
  24667. Scene.prototype.getActiveIndices = function () {
  24668. return this._activeIndices.current;
  24669. };
  24670. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24671. /**
  24672. * Gets the performance counter for active indices
  24673. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24674. */
  24675. get: function () {
  24676. return this._activeIndices;
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. /**
  24682. * Gets the total number of active particles rendered per frame
  24683. * @returns the total number of active particles rendered per frame
  24684. */
  24685. Scene.prototype.getActiveParticles = function () {
  24686. return this._activeParticles.current;
  24687. };
  24688. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24689. /**
  24690. * Gets the performance counter for active particles
  24691. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24692. */
  24693. get: function () {
  24694. return this._activeParticles;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. /**
  24700. * Gets the total number of active bones rendered per frame
  24701. * @returns the total number of active bones rendered per frame
  24702. */
  24703. Scene.prototype.getActiveBones = function () {
  24704. return this._activeBones.current;
  24705. };
  24706. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24707. /**
  24708. * Gets the performance counter for active bones
  24709. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24710. */
  24711. get: function () {
  24712. return this._activeBones;
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. /** @hidden */
  24718. Scene.prototype.getInterFramePerfCounter = function () {
  24719. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24720. return 0;
  24721. };
  24722. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24723. /** @hidden */
  24724. get: function () {
  24725. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24726. return null;
  24727. },
  24728. enumerable: true,
  24729. configurable: true
  24730. });
  24731. /** @hidden */
  24732. Scene.prototype.getLastFrameDuration = function () {
  24733. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24734. return 0;
  24735. };
  24736. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24737. /** @hidden */
  24738. get: function () {
  24739. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24740. return null;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. /** @hidden */
  24746. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24747. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24748. return 0;
  24749. };
  24750. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24751. /** @hidden */
  24752. get: function () {
  24753. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24754. return null;
  24755. },
  24756. enumerable: true,
  24757. configurable: true
  24758. });
  24759. /**
  24760. * Gets the array of active meshes
  24761. * @returns an array of AbstractMesh
  24762. */
  24763. Scene.prototype.getActiveMeshes = function () {
  24764. return this._activeMeshes;
  24765. };
  24766. /** @hidden */
  24767. Scene.prototype.getRenderTargetsDuration = function () {
  24768. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24769. return 0;
  24770. };
  24771. /** @hidden */
  24772. Scene.prototype.getRenderDuration = function () {
  24773. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24774. return 0;
  24775. };
  24776. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24777. /** @hidden */
  24778. get: function () {
  24779. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24780. return null;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. /** @hidden */
  24786. Scene.prototype.getParticlesDuration = function () {
  24787. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24788. return 0;
  24789. };
  24790. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24791. /** @hidden */
  24792. get: function () {
  24793. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24794. return null;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. /** @hidden */
  24800. Scene.prototype.getSpritesDuration = function () {
  24801. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24802. return 0;
  24803. };
  24804. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24805. /** @hidden */
  24806. get: function () {
  24807. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24808. return null;
  24809. },
  24810. enumerable: true,
  24811. configurable: true
  24812. });
  24813. /**
  24814. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24815. * @returns a number
  24816. */
  24817. Scene.prototype.getAnimationRatio = function () {
  24818. return this._animationRatio;
  24819. };
  24820. /**
  24821. * Gets an unique Id for the current frame
  24822. * @returns a number
  24823. */
  24824. Scene.prototype.getRenderId = function () {
  24825. return this._renderId;
  24826. };
  24827. /** Call this function if you want to manually increment the render Id*/
  24828. Scene.prototype.incrementRenderId = function () {
  24829. this._renderId++;
  24830. };
  24831. Scene.prototype._updatePointerPosition = function (evt) {
  24832. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24833. if (!canvasRect) {
  24834. return;
  24835. }
  24836. this._pointerX = evt.clientX - canvasRect.left;
  24837. this._pointerY = evt.clientY - canvasRect.top;
  24838. this._unTranslatedPointerX = this._pointerX;
  24839. this._unTranslatedPointerY = this._pointerY;
  24840. };
  24841. Scene.prototype._createUbo = function () {
  24842. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24843. this._sceneUbo.addUniform("viewProjection", 16);
  24844. this._sceneUbo.addUniform("view", 16);
  24845. };
  24846. Scene.prototype._createAlternateUbo = function () {
  24847. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24848. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24849. this._alternateSceneUbo.addUniform("view", 16);
  24850. };
  24851. // Pointers handling
  24852. /**
  24853. * Use this method to simulate a pointer move on a mesh
  24854. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24855. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24856. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24857. * @returns the current scene
  24858. */
  24859. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24860. var evt = new PointerEvent("pointermove", pointerEventInit);
  24861. return this._processPointerMove(pickResult, evt);
  24862. };
  24863. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24864. var canvas = this._engine.getRenderingCanvas();
  24865. if (!canvas) {
  24866. return this;
  24867. }
  24868. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24869. this.setPointerOverSprite(null);
  24870. this.setPointerOverMesh(pickResult.pickedMesh);
  24871. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24872. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24873. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24874. }
  24875. else {
  24876. canvas.style.cursor = this.hoverCursor;
  24877. }
  24878. }
  24879. else {
  24880. canvas.style.cursor = this.defaultCursor;
  24881. }
  24882. }
  24883. else {
  24884. this.setPointerOverMesh(null);
  24885. // Sprites
  24886. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24887. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24888. this.setPointerOverSprite(pickResult.pickedSprite);
  24889. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24890. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24891. }
  24892. else {
  24893. canvas.style.cursor = this.hoverCursor;
  24894. }
  24895. }
  24896. else {
  24897. this.setPointerOverSprite(null);
  24898. // Restore pointer
  24899. canvas.style.cursor = this.defaultCursor;
  24900. }
  24901. }
  24902. if (pickResult) {
  24903. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24904. if (this.onPointerMove) {
  24905. this.onPointerMove(evt, pickResult, type);
  24906. }
  24907. if (this.onPointerObservable.hasObservers()) {
  24908. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24909. this.onPointerObservable.notifyObservers(pi, type);
  24910. }
  24911. }
  24912. return this;
  24913. };
  24914. /**
  24915. * Use this method to simulate a pointer down on a mesh
  24916. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24917. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24918. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24919. * @returns the current scene
  24920. */
  24921. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24922. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24923. return this._processPointerDown(pickResult, evt);
  24924. };
  24925. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24926. var _this = this;
  24927. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24928. this._pickedDownMesh = pickResult.pickedMesh;
  24929. var actionManager = pickResult.pickedMesh.actionManager;
  24930. if (actionManager) {
  24931. if (actionManager.hasPickTriggers) {
  24932. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24933. switch (evt.button) {
  24934. case 0:
  24935. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24936. break;
  24937. case 1:
  24938. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24939. break;
  24940. case 2:
  24941. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24942. break;
  24943. }
  24944. }
  24945. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24946. window.setTimeout(function () {
  24947. 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);
  24948. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24949. if (_this._totalPointersPressed !== 0 &&
  24950. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24951. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24952. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24953. _this._startingPointerTime = 0;
  24954. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24955. }
  24956. }
  24957. }, Scene.LongPressDelay);
  24958. }
  24959. }
  24960. }
  24961. if (pickResult) {
  24962. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24963. if (this.onPointerDown) {
  24964. this.onPointerDown(evt, pickResult, type);
  24965. }
  24966. if (this.onPointerObservable.hasObservers()) {
  24967. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24968. this.onPointerObservable.notifyObservers(pi, type);
  24969. }
  24970. }
  24971. return this;
  24972. };
  24973. /**
  24974. * Use this method to simulate a pointer up on a mesh
  24975. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24976. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24977. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24978. * @returns the current scene
  24979. */
  24980. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24981. var evt = new PointerEvent("pointerup", pointerEventInit);
  24982. var clickInfo = new ClickInfo();
  24983. clickInfo.singleClick = true;
  24984. clickInfo.ignore = true;
  24985. return this._processPointerUp(pickResult, evt, clickInfo);
  24986. };
  24987. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24988. if (pickResult && pickResult && pickResult.pickedMesh) {
  24989. this._pickedUpMesh = pickResult.pickedMesh;
  24990. if (this._pickedDownMesh === this._pickedUpMesh) {
  24991. if (this.onPointerPick) {
  24992. this.onPointerPick(evt, pickResult);
  24993. }
  24994. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24995. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24996. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24997. this.onPointerObservable.notifyObservers(pi, type_1);
  24998. }
  24999. }
  25000. if (pickResult.pickedMesh.actionManager) {
  25001. if (clickInfo.ignore) {
  25002. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25003. }
  25004. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25005. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25006. }
  25007. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25008. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25009. }
  25010. }
  25011. }
  25012. if (this._pickedDownMesh &&
  25013. this._pickedDownMesh.actionManager &&
  25014. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25015. this._pickedDownMesh !== this._pickedUpMesh) {
  25016. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25017. }
  25018. var type = BABYLON.PointerEventTypes.POINTERUP;
  25019. if (this.onPointerObservable.hasObservers()) {
  25020. if (!clickInfo.ignore) {
  25021. if (!clickInfo.hasSwiped) {
  25022. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25023. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25024. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25025. this.onPointerObservable.notifyObservers(pi, type_2);
  25026. }
  25027. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25028. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25029. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25030. this.onPointerObservable.notifyObservers(pi, type_3);
  25031. }
  25032. }
  25033. }
  25034. else {
  25035. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25036. this.onPointerObservable.notifyObservers(pi, type);
  25037. }
  25038. }
  25039. if (this.onPointerUp) {
  25040. this.onPointerUp(evt, pickResult, type);
  25041. }
  25042. return this;
  25043. };
  25044. /**
  25045. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25046. * @param attachUp defines if you want to attach events to pointerup
  25047. * @param attachDown defines if you want to attach events to pointerdown
  25048. * @param attachMove defines if you want to attach events to pointermove
  25049. */
  25050. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25051. var _this = this;
  25052. if (attachUp === void 0) { attachUp = true; }
  25053. if (attachDown === void 0) { attachDown = true; }
  25054. if (attachMove === void 0) { attachMove = true; }
  25055. this._initActionManager = function (act, clickInfo) {
  25056. if (!_this._meshPickProceed) {
  25057. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25058. _this._currentPickResult = pickResult;
  25059. if (pickResult) {
  25060. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25061. }
  25062. _this._meshPickProceed = true;
  25063. }
  25064. return act;
  25065. };
  25066. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25067. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25068. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25069. btn !== _this._previousButtonPressed) {
  25070. _this._doubleClickOccured = false;
  25071. clickInfo.singleClick = true;
  25072. clickInfo.ignore = false;
  25073. cb(clickInfo, _this._currentPickResult);
  25074. }
  25075. };
  25076. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25077. var clickInfo = new ClickInfo();
  25078. _this._currentPickResult = null;
  25079. var act = null;
  25080. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25081. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25082. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25083. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25084. act = _this._initActionManager(act, clickInfo);
  25085. if (act)
  25086. checkPicking = act.hasPickTriggers;
  25087. }
  25088. if (checkPicking) {
  25089. var btn = evt.button;
  25090. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25091. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25092. if (!clickInfo.hasSwiped) {
  25093. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25094. if (!checkSingleClickImmediately) {
  25095. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25096. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25097. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25098. act = _this._initActionManager(act, clickInfo);
  25099. if (act)
  25100. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25101. }
  25102. }
  25103. if (checkSingleClickImmediately) {
  25104. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25105. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25106. btn !== _this._previousButtonPressed) {
  25107. clickInfo.singleClick = true;
  25108. cb(clickInfo, _this._currentPickResult);
  25109. }
  25110. }
  25111. // at least one double click is required to be check and exclusive double click is enabled
  25112. else {
  25113. // wait that no double click has been raised during the double click delay
  25114. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25115. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25116. }
  25117. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25118. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25119. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25120. act = _this._initActionManager(act, clickInfo);
  25121. if (act)
  25122. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25123. }
  25124. if (checkDoubleClick) {
  25125. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25126. if (btn === _this._previousButtonPressed &&
  25127. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25128. !_this._doubleClickOccured) {
  25129. // pointer has not moved for 2 clicks, it's a double click
  25130. if (!clickInfo.hasSwiped &&
  25131. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25132. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25133. _this._previousStartingPointerTime = 0;
  25134. _this._doubleClickOccured = true;
  25135. clickInfo.doubleClick = true;
  25136. clickInfo.ignore = false;
  25137. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25138. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25139. }
  25140. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25141. cb(clickInfo, _this._currentPickResult);
  25142. }
  25143. // if the two successive clicks are too far, it's just two simple clicks
  25144. else {
  25145. _this._doubleClickOccured = false;
  25146. _this._previousStartingPointerTime = _this._startingPointerTime;
  25147. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25148. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25149. _this._previousButtonPressed = btn;
  25150. if (Scene.ExclusiveDoubleClickMode) {
  25151. if (_this._previousDelayedSimpleClickTimeout) {
  25152. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25153. }
  25154. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25155. cb(clickInfo, _this._previousPickResult);
  25156. }
  25157. else {
  25158. cb(clickInfo, _this._currentPickResult);
  25159. }
  25160. }
  25161. }
  25162. // just the first click of the double has been raised
  25163. else {
  25164. _this._doubleClickOccured = false;
  25165. _this._previousStartingPointerTime = _this._startingPointerTime;
  25166. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25167. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25168. _this._previousButtonPressed = btn;
  25169. }
  25170. }
  25171. }
  25172. }
  25173. clickInfo.ignore = true;
  25174. cb(clickInfo, _this._currentPickResult);
  25175. };
  25176. this._spritePredicate = function (sprite) {
  25177. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25178. };
  25179. this._onPointerMove = function (evt) {
  25180. _this._updatePointerPosition(evt);
  25181. // PreObservable support
  25182. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25183. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25184. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25185. _this.onPrePointerObservable.notifyObservers(pi, type);
  25186. if (pi.skipOnPointerObservable) {
  25187. return;
  25188. }
  25189. }
  25190. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25191. return;
  25192. }
  25193. if (!_this.pointerMovePredicate) {
  25194. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25195. }
  25196. // Meshes
  25197. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25198. _this._processPointerMove(pickResult, evt);
  25199. };
  25200. this._onPointerDown = function (evt) {
  25201. _this._totalPointersPressed++;
  25202. _this._pickedDownMesh = null;
  25203. _this._meshPickProceed = false;
  25204. _this._updatePointerPosition(evt);
  25205. if (_this.preventDefaultOnPointerDown && canvas) {
  25206. evt.preventDefault();
  25207. canvas.focus();
  25208. }
  25209. // PreObservable support
  25210. if (_this.onPrePointerObservable.hasObservers()) {
  25211. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25212. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25213. _this.onPrePointerObservable.notifyObservers(pi, type);
  25214. if (pi.skipOnPointerObservable) {
  25215. return;
  25216. }
  25217. }
  25218. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25219. return;
  25220. }
  25221. _this._pointerCaptures[evt.pointerId] = true;
  25222. _this._startingPointerPosition.x = _this._pointerX;
  25223. _this._startingPointerPosition.y = _this._pointerY;
  25224. _this._startingPointerTime = Date.now();
  25225. if (!_this.pointerDownPredicate) {
  25226. _this.pointerDownPredicate = function (mesh) {
  25227. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25228. };
  25229. }
  25230. // Meshes
  25231. _this._pickedDownMesh = null;
  25232. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25233. _this._processPointerDown(pickResult, evt);
  25234. // Sprites
  25235. _this._pickedDownSprite = null;
  25236. if (_this.spriteManagers.length > 0) {
  25237. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25238. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25239. if (pickResult.pickedSprite.actionManager) {
  25240. _this._pickedDownSprite = pickResult.pickedSprite;
  25241. switch (evt.button) {
  25242. case 0:
  25243. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25244. break;
  25245. case 1:
  25246. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25247. break;
  25248. case 2:
  25249. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25250. break;
  25251. }
  25252. if (pickResult.pickedSprite.actionManager) {
  25253. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25254. }
  25255. }
  25256. }
  25257. }
  25258. };
  25259. this._onPointerUp = function (evt) {
  25260. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25261. return; // So we need to test it the pointer down was pressed before.
  25262. }
  25263. _this._totalPointersPressed--;
  25264. _this._pickedUpMesh = null;
  25265. _this._meshPickProceed = false;
  25266. _this._updatePointerPosition(evt);
  25267. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25268. // PreObservable support
  25269. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25270. if (!clickInfo.ignore) {
  25271. if (!clickInfo.hasSwiped) {
  25272. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25273. var type = BABYLON.PointerEventTypes.POINTERTAP;
  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 (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25281. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25282. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25283. _this.onPrePointerObservable.notifyObservers(pi, type);
  25284. if (pi.skipOnPointerObservable) {
  25285. return;
  25286. }
  25287. }
  25288. }
  25289. }
  25290. else {
  25291. var type = BABYLON.PointerEventTypes.POINTERUP;
  25292. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25293. _this.onPrePointerObservable.notifyObservers(pi, type);
  25294. if (pi.skipOnPointerObservable) {
  25295. return;
  25296. }
  25297. }
  25298. }
  25299. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25300. return;
  25301. }
  25302. _this._pointerCaptures[evt.pointerId] = false;
  25303. if (!_this.pointerUpPredicate) {
  25304. _this.pointerUpPredicate = function (mesh) {
  25305. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25306. };
  25307. }
  25308. // Meshes
  25309. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25310. _this._initActionManager(null, clickInfo);
  25311. }
  25312. if (!pickResult) {
  25313. pickResult = _this._currentPickResult;
  25314. }
  25315. _this._processPointerUp(pickResult, evt, clickInfo);
  25316. // Sprites
  25317. if (!clickInfo.ignore) {
  25318. if (_this.spriteManagers.length > 0) {
  25319. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25320. if (spritePickResult) {
  25321. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25322. if (spritePickResult.pickedSprite.actionManager) {
  25323. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25324. if (spritePickResult.pickedSprite.actionManager) {
  25325. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25326. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25327. }
  25328. }
  25329. }
  25330. }
  25331. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25332. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25333. }
  25334. }
  25335. }
  25336. }
  25337. _this._previousPickResult = _this._currentPickResult;
  25338. });
  25339. };
  25340. this._onKeyDown = function (evt) {
  25341. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25342. if (_this.onPreKeyboardObservable.hasObservers()) {
  25343. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25344. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25345. if (pi.skipOnPointerObservable) {
  25346. return;
  25347. }
  25348. }
  25349. if (_this.onKeyboardObservable.hasObservers()) {
  25350. var pi = new BABYLON.KeyboardInfo(type, evt);
  25351. _this.onKeyboardObservable.notifyObservers(pi, type);
  25352. }
  25353. if (_this.actionManager) {
  25354. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25355. }
  25356. };
  25357. this._onKeyUp = function (evt) {
  25358. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25359. if (_this.onPreKeyboardObservable.hasObservers()) {
  25360. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25361. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25362. if (pi.skipOnPointerObservable) {
  25363. return;
  25364. }
  25365. }
  25366. if (_this.onKeyboardObservable.hasObservers()) {
  25367. var pi = new BABYLON.KeyboardInfo(type, evt);
  25368. _this.onKeyboardObservable.notifyObservers(pi, type);
  25369. }
  25370. if (_this.actionManager) {
  25371. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25372. }
  25373. };
  25374. var engine = this.getEngine();
  25375. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25376. if (!canvas) {
  25377. return;
  25378. }
  25379. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25380. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25381. });
  25382. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25383. if (!canvas) {
  25384. return;
  25385. }
  25386. canvas.removeEventListener("keydown", _this._onKeyDown);
  25387. canvas.removeEventListener("keyup", _this._onKeyUp);
  25388. });
  25389. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25390. var canvas = this._engine.getRenderingCanvas();
  25391. if (!canvas) {
  25392. return;
  25393. }
  25394. if (attachMove) {
  25395. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25396. // Wheel
  25397. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25398. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25399. }
  25400. if (attachDown) {
  25401. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25402. }
  25403. if (attachUp) {
  25404. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25405. }
  25406. canvas.tabIndex = 1;
  25407. };
  25408. /** Detaches all event handlers*/
  25409. Scene.prototype.detachControl = function () {
  25410. var engine = this.getEngine();
  25411. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25412. var canvas = engine.getRenderingCanvas();
  25413. if (!canvas) {
  25414. return;
  25415. }
  25416. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25417. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25418. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25419. if (this._onCanvasBlurObserver) {
  25420. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25421. }
  25422. if (this._onCanvasFocusObserver) {
  25423. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25424. }
  25425. // Wheel
  25426. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25427. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25428. // Keyboard
  25429. canvas.removeEventListener("keydown", this._onKeyDown);
  25430. canvas.removeEventListener("keyup", this._onKeyUp);
  25431. // Observables
  25432. this.onKeyboardObservable.clear();
  25433. this.onPreKeyboardObservable.clear();
  25434. this.onPointerObservable.clear();
  25435. this.onPrePointerObservable.clear();
  25436. };
  25437. /**
  25438. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25439. * Delay loaded resources are not taking in account
  25440. * @return true if all required resources are ready
  25441. */
  25442. Scene.prototype.isReady = function () {
  25443. if (this._isDisposed) {
  25444. return false;
  25445. }
  25446. if (this._pendingData.length > 0) {
  25447. return false;
  25448. }
  25449. var index;
  25450. var engine = this.getEngine();
  25451. // Geometries
  25452. for (index = 0; index < this._geometries.length; index++) {
  25453. var geometry = this._geometries[index];
  25454. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25455. return false;
  25456. }
  25457. }
  25458. // Meshes
  25459. for (index = 0; index < this.meshes.length; index++) {
  25460. var mesh = this.meshes[index];
  25461. if (!mesh.isEnabled()) {
  25462. continue;
  25463. }
  25464. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25465. continue;
  25466. }
  25467. if (!mesh.isReady(true)) {
  25468. return false;
  25469. }
  25470. // Effect layers
  25471. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25472. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25473. var layer = _a[_i];
  25474. if (!layer.hasMesh(mesh)) {
  25475. continue;
  25476. }
  25477. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25478. var subMesh = _c[_b];
  25479. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25480. return false;
  25481. }
  25482. }
  25483. }
  25484. }
  25485. // Post-processes
  25486. if (this.activeCameras && this.activeCameras.length > 0) {
  25487. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25488. var camera = _e[_d];
  25489. if (!camera.isReady(true)) {
  25490. return false;
  25491. }
  25492. }
  25493. }
  25494. else if (this.activeCamera) {
  25495. if (!this.activeCamera.isReady(true)) {
  25496. return false;
  25497. }
  25498. }
  25499. // Particles
  25500. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25501. var particleSystem = _g[_f];
  25502. if (!particleSystem.isReady()) {
  25503. return false;
  25504. }
  25505. }
  25506. return true;
  25507. };
  25508. /** Resets all cached information relative to material (including effect and visibility) */
  25509. Scene.prototype.resetCachedMaterial = function () {
  25510. this._cachedMaterial = null;
  25511. this._cachedEffect = null;
  25512. this._cachedVisibility = null;
  25513. };
  25514. /**
  25515. * Registers a function to be called before every frame render
  25516. * @param func defines the function to register
  25517. */
  25518. Scene.prototype.registerBeforeRender = function (func) {
  25519. this.onBeforeRenderObservable.add(func);
  25520. };
  25521. /**
  25522. * Unregisters a function called before every frame render
  25523. * @param func defines the function to unregister
  25524. */
  25525. Scene.prototype.unregisterBeforeRender = function (func) {
  25526. this.onBeforeRenderObservable.removeCallback(func);
  25527. };
  25528. /**
  25529. * Registers a function to be called after every frame render
  25530. * @param func defines the function to register
  25531. */
  25532. Scene.prototype.registerAfterRender = function (func) {
  25533. this.onAfterRenderObservable.add(func);
  25534. };
  25535. /**
  25536. * Unregisters a function called after every frame render
  25537. * @param func defines the function to unregister
  25538. */
  25539. Scene.prototype.unregisterAfterRender = function (func) {
  25540. this.onAfterRenderObservable.removeCallback(func);
  25541. };
  25542. Scene.prototype._executeOnceBeforeRender = function (func) {
  25543. var _this = this;
  25544. var execFunc = function () {
  25545. func();
  25546. setTimeout(function () {
  25547. _this.unregisterBeforeRender(execFunc);
  25548. });
  25549. };
  25550. this.registerBeforeRender(execFunc);
  25551. };
  25552. /**
  25553. * The provided function will run before render once and will be disposed afterwards.
  25554. * A timeout delay can be provided so that the function will be executed in N ms.
  25555. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25556. * @param func The function to be executed.
  25557. * @param timeout optional delay in ms
  25558. */
  25559. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25560. var _this = this;
  25561. if (timeout !== undefined) {
  25562. setTimeout(function () {
  25563. _this._executeOnceBeforeRender(func);
  25564. }, timeout);
  25565. }
  25566. else {
  25567. this._executeOnceBeforeRender(func);
  25568. }
  25569. };
  25570. /** @hidden */
  25571. Scene.prototype._addPendingData = function (data) {
  25572. this._pendingData.push(data);
  25573. };
  25574. /** @hidden */
  25575. Scene.prototype._removePendingData = function (data) {
  25576. var wasLoading = this.isLoading;
  25577. var index = this._pendingData.indexOf(data);
  25578. if (index !== -1) {
  25579. this._pendingData.splice(index, 1);
  25580. }
  25581. if (wasLoading && !this.isLoading) {
  25582. this.onDataLoadedObservable.notifyObservers(this);
  25583. }
  25584. };
  25585. /**
  25586. * Returns the number of items waiting to be loaded
  25587. * @returns the number of items waiting to be loaded
  25588. */
  25589. Scene.prototype.getWaitingItemsCount = function () {
  25590. return this._pendingData.length;
  25591. };
  25592. Object.defineProperty(Scene.prototype, "isLoading", {
  25593. /**
  25594. * Returns a boolean indicating if the scene is still loading data
  25595. */
  25596. get: function () {
  25597. return this._pendingData.length > 0;
  25598. },
  25599. enumerable: true,
  25600. configurable: true
  25601. });
  25602. /**
  25603. * Registers a function to be executed when the scene is ready
  25604. * @param {Function} func - the function to be executed
  25605. */
  25606. Scene.prototype.executeWhenReady = function (func) {
  25607. var _this = this;
  25608. this.onReadyObservable.add(func);
  25609. if (this._executeWhenReadyTimeoutId !== -1) {
  25610. return;
  25611. }
  25612. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25613. _this._checkIsReady();
  25614. }, 150);
  25615. };
  25616. /**
  25617. * Returns a promise that resolves when the scene is ready
  25618. * @returns A promise that resolves when the scene is ready
  25619. */
  25620. Scene.prototype.whenReadyAsync = function () {
  25621. var _this = this;
  25622. return new Promise(function (resolve) {
  25623. _this.executeWhenReady(function () {
  25624. resolve();
  25625. });
  25626. });
  25627. };
  25628. /** @hidden */
  25629. Scene.prototype._checkIsReady = function () {
  25630. var _this = this;
  25631. if (this.isReady()) {
  25632. this.onReadyObservable.notifyObservers(this);
  25633. this.onReadyObservable.clear();
  25634. this._executeWhenReadyTimeoutId = -1;
  25635. return;
  25636. }
  25637. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25638. _this._checkIsReady();
  25639. }, 150);
  25640. };
  25641. // Animations
  25642. /**
  25643. * Will start the animation sequence of a given target
  25644. * @param target defines the target
  25645. * @param from defines from which frame should animation start
  25646. * @param to defines until which frame should animation run.
  25647. * @param weight defines the weight to apply to the animation (1.0 by default)
  25648. * @param loop defines if the animation loops
  25649. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25650. * @param onAnimationEnd defines the function to be executed when the animation ends
  25651. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25652. * @returns the animatable object created for this animation
  25653. */
  25654. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25655. if (weight === void 0) { weight = 1.0; }
  25656. if (speedRatio === void 0) { speedRatio = 1.0; }
  25657. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25658. returnedAnimatable.weight = weight;
  25659. return returnedAnimatable;
  25660. };
  25661. /**
  25662. * Will start the animation sequence of a given target
  25663. * @param target defines the target
  25664. * @param from defines from which frame should animation start
  25665. * @param to defines until which frame should animation run.
  25666. * @param loop defines if the animation loops
  25667. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25668. * @param onAnimationEnd defines the function to be executed when the animation ends
  25669. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25670. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25671. * @returns the animatable object created for this animation
  25672. */
  25673. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25674. if (speedRatio === void 0) { speedRatio = 1.0; }
  25675. if (stopCurrent === void 0) { stopCurrent = true; }
  25676. if (from > to && speedRatio > 0) {
  25677. speedRatio *= -1;
  25678. }
  25679. if (stopCurrent) {
  25680. this.stopAnimation(target);
  25681. }
  25682. if (!animatable) {
  25683. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25684. }
  25685. // Local animations
  25686. if (target.animations) {
  25687. animatable.appendAnimations(target, target.animations);
  25688. }
  25689. // Children animations
  25690. if (target.getAnimatables) {
  25691. var animatables = target.getAnimatables();
  25692. for (var index = 0; index < animatables.length; index++) {
  25693. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25694. }
  25695. }
  25696. animatable.reset();
  25697. return animatable;
  25698. };
  25699. /**
  25700. * Begin a new animation on a given node
  25701. * @param target defines the target where the animation will take place
  25702. * @param animations defines the list of animations to start
  25703. * @param from defines the initial value
  25704. * @param to defines the final value
  25705. * @param loop defines if you want animation to loop (off by default)
  25706. * @param speedRatio defines the speed ratio to apply to all animations
  25707. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25708. * @returns the list of created animatables
  25709. */
  25710. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25711. if (speedRatio === undefined) {
  25712. speedRatio = 1.0;
  25713. }
  25714. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25715. return animatable;
  25716. };
  25717. /**
  25718. * Begin a new animation on a given node and its hierarchy
  25719. * @param target defines the root node where the animation will take place
  25720. * @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.
  25721. * @param animations defines the list of animations to start
  25722. * @param from defines the initial value
  25723. * @param to defines the final value
  25724. * @param loop defines if you want animation to loop (off by default)
  25725. * @param speedRatio defines the speed ratio to apply to all animations
  25726. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25727. * @returns the list of animatables created for all nodes
  25728. */
  25729. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25730. var children = target.getDescendants(directDescendantsOnly);
  25731. var result = [];
  25732. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25733. var child = children_1[_i];
  25734. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25735. }
  25736. return result;
  25737. };
  25738. /**
  25739. * Gets the animatable associated with a specific target
  25740. * @param target defines the target of the animatable
  25741. * @returns the required animatable if found
  25742. */
  25743. Scene.prototype.getAnimatableByTarget = function (target) {
  25744. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25745. if (this._activeAnimatables[index].target === target) {
  25746. return this._activeAnimatables[index];
  25747. }
  25748. }
  25749. return null;
  25750. };
  25751. /**
  25752. * Gets all animatables associated with a given target
  25753. * @param target defines the target to look animatables for
  25754. * @returns an array of Animatables
  25755. */
  25756. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25757. var result = [];
  25758. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25759. if (this._activeAnimatables[index].target === target) {
  25760. result.push(this._activeAnimatables[index]);
  25761. }
  25762. }
  25763. return result;
  25764. };
  25765. Object.defineProperty(Scene.prototype, "animatables", {
  25766. /**
  25767. * Gets all animatable attached to the scene
  25768. */
  25769. get: function () {
  25770. return this._activeAnimatables;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. /**
  25776. * Will stop the animation of the given target
  25777. * @param target - the target
  25778. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25779. */
  25780. Scene.prototype.stopAnimation = function (target, animationName) {
  25781. var animatables = this.getAllAnimatablesByTarget(target);
  25782. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25783. var animatable = animatables_1[_i];
  25784. animatable.stop(animationName);
  25785. }
  25786. };
  25787. /**
  25788. * Stops and removes all animations that have been applied to the scene
  25789. */
  25790. Scene.prototype.stopAllAnimations = function () {
  25791. if (this._activeAnimatables) {
  25792. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25793. this._activeAnimatables[i].stop();
  25794. }
  25795. this._activeAnimatables = [];
  25796. }
  25797. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25798. var group = _a[_i];
  25799. group.stop();
  25800. }
  25801. };
  25802. Scene.prototype._animate = function () {
  25803. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25804. return;
  25805. }
  25806. // Getting time
  25807. var now = BABYLON.Tools.Now;
  25808. if (!this._animationTimeLast) {
  25809. if (this._pendingData.length > 0) {
  25810. return;
  25811. }
  25812. this._animationTimeLast = now;
  25813. }
  25814. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25815. this._animationTime += deltaTime;
  25816. this._animationTimeLast = now;
  25817. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25818. this._activeAnimatables[index]._animate(this._animationTime);
  25819. }
  25820. // Late animation bindings
  25821. this._processLateAnimationBindings();
  25822. };
  25823. /** @hidden */
  25824. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25825. var target = runtimeAnimation.target;
  25826. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25827. if (!target._lateAnimationHolders) {
  25828. target._lateAnimationHolders = {};
  25829. }
  25830. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25831. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25832. totalWeight: 0,
  25833. animations: [],
  25834. originalValue: originalValue
  25835. };
  25836. }
  25837. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25838. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25839. };
  25840. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25841. var normalizer = 1.0;
  25842. var finalPosition = BABYLON.Tmp.Vector3[0];
  25843. var finalScaling = BABYLON.Tmp.Vector3[1];
  25844. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25845. var startIndex = 0;
  25846. var originalAnimation = holder.animations[0];
  25847. var originalValue = holder.originalValue;
  25848. var scale = 1;
  25849. if (holder.totalWeight < 1.0) {
  25850. // We need to mix the original value in
  25851. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25852. scale = 1.0 - holder.totalWeight;
  25853. }
  25854. else {
  25855. startIndex = 1;
  25856. // We need to normalize the weights
  25857. normalizer = holder.totalWeight;
  25858. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25859. scale = originalAnimation.weight / normalizer;
  25860. if (scale == 1) {
  25861. return originalAnimation.currentValue;
  25862. }
  25863. }
  25864. finalScaling.scaleInPlace(scale);
  25865. finalPosition.scaleInPlace(scale);
  25866. finalQuaternion.scaleInPlace(scale);
  25867. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25868. var runtimeAnimation = holder.animations[animIndex];
  25869. var scale = runtimeAnimation.weight / normalizer;
  25870. var currentPosition = BABYLON.Tmp.Vector3[2];
  25871. var currentScaling = BABYLON.Tmp.Vector3[3];
  25872. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25873. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25874. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25875. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25876. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25877. }
  25878. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25879. return originalAnimation._workValue;
  25880. };
  25881. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25882. var originalAnimation = holder.animations[0];
  25883. var originalValue = holder.originalValue;
  25884. if (holder.animations.length === 1) {
  25885. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25886. }
  25887. var normalizer = 1.0;
  25888. var quaternions;
  25889. var weights;
  25890. if (holder.totalWeight < 1.0) {
  25891. var scale = 1.0 - holder.totalWeight;
  25892. quaternions = [];
  25893. weights = [];
  25894. quaternions.push(originalValue);
  25895. weights.push(scale);
  25896. }
  25897. else {
  25898. if (holder.animations.length === 2) { // Slerp as soon as we can
  25899. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25900. }
  25901. quaternions = [];
  25902. weights = [];
  25903. normalizer = holder.totalWeight;
  25904. }
  25905. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25906. var runtimeAnimation = holder.animations[animIndex];
  25907. quaternions.push(runtimeAnimation.currentValue);
  25908. weights.push(runtimeAnimation.weight / normalizer);
  25909. }
  25910. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25911. var cumulativeAmount = 0;
  25912. var cumulativeQuaternion = null;
  25913. for (var index = 0; index < quaternions.length;) {
  25914. if (!cumulativeQuaternion) {
  25915. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25916. cumulativeAmount = weights[index] + weights[index + 1];
  25917. index += 2;
  25918. continue;
  25919. }
  25920. cumulativeAmount += weights[index];
  25921. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25922. index++;
  25923. }
  25924. return cumulativeQuaternion;
  25925. };
  25926. Scene.prototype._processLateAnimationBindings = function () {
  25927. if (!this._registeredForLateAnimationBindings.length) {
  25928. return;
  25929. }
  25930. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25931. var target = this._registeredForLateAnimationBindings.data[index];
  25932. for (var path in target._lateAnimationHolders) {
  25933. var holder = target._lateAnimationHolders[path];
  25934. var originalAnimation = holder.animations[0];
  25935. var originalValue = holder.originalValue;
  25936. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25937. var finalValue = void 0;
  25938. if (matrixDecomposeMode) {
  25939. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25940. }
  25941. else {
  25942. var quaternionMode = originalValue.w !== undefined;
  25943. if (quaternionMode) {
  25944. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25945. }
  25946. else {
  25947. var startIndex = 0;
  25948. var normalizer = 1.0;
  25949. if (holder.totalWeight < 1.0) {
  25950. // We need to mix the original value in
  25951. if (originalValue.scale) {
  25952. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25953. }
  25954. else {
  25955. finalValue = originalValue * (1.0 - holder.totalWeight);
  25956. }
  25957. }
  25958. else {
  25959. // We need to normalize the weights
  25960. normalizer = holder.totalWeight;
  25961. var scale_1 = originalAnimation.weight / normalizer;
  25962. if (scale_1 !== 1) {
  25963. if (originalAnimation.currentValue.scale) {
  25964. finalValue = originalAnimation.currentValue.scale(scale_1);
  25965. }
  25966. else {
  25967. finalValue = originalAnimation.currentValue * scale_1;
  25968. }
  25969. }
  25970. else {
  25971. finalValue = originalAnimation.currentValue;
  25972. }
  25973. startIndex = 1;
  25974. }
  25975. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25976. var runtimeAnimation = holder.animations[animIndex];
  25977. var scale = runtimeAnimation.weight / normalizer;
  25978. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25979. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25980. }
  25981. else {
  25982. finalValue += runtimeAnimation.currentValue * scale;
  25983. }
  25984. }
  25985. }
  25986. }
  25987. target[path] = finalValue;
  25988. }
  25989. target._lateAnimationHolders = {};
  25990. }
  25991. this._registeredForLateAnimationBindings.reset();
  25992. };
  25993. // Matrix
  25994. /** @hidden */
  25995. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25996. this._useAlternateCameraConfiguration = active;
  25997. };
  25998. /**
  25999. * Gets the current view matrix
  26000. * @returns a Matrix
  26001. */
  26002. Scene.prototype.getViewMatrix = function () {
  26003. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26004. };
  26005. /**
  26006. * Gets the current projection matrix
  26007. * @returns a Matrix
  26008. */
  26009. Scene.prototype.getProjectionMatrix = function () {
  26010. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26011. };
  26012. /**
  26013. * Gets the current transform matrix
  26014. * @returns a Matrix made of View * Projection
  26015. */
  26016. Scene.prototype.getTransformMatrix = function () {
  26017. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26018. };
  26019. /**
  26020. * Sets the current transform matrix
  26021. * @param view defines the View matrix to use
  26022. * @param projection defines the Projection matrix to use
  26023. */
  26024. Scene.prototype.setTransformMatrix = function (view, projection) {
  26025. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26026. return;
  26027. }
  26028. this._viewUpdateFlag = view.updateFlag;
  26029. this._projectionUpdateFlag = projection.updateFlag;
  26030. this._viewMatrix = view;
  26031. this._projectionMatrix = projection;
  26032. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26033. // Update frustum
  26034. if (!this._frustumPlanes) {
  26035. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26036. }
  26037. else {
  26038. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26039. }
  26040. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26041. var otherCamera = this.activeCamera._alternateCamera;
  26042. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26043. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26044. }
  26045. if (this._sceneUbo.useUbo) {
  26046. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26047. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26048. this._sceneUbo.update();
  26049. }
  26050. };
  26051. /** @hidden */
  26052. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26053. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26054. return;
  26055. }
  26056. this._alternateViewUpdateFlag = view.updateFlag;
  26057. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26058. this._alternateViewMatrix = view;
  26059. this._alternateProjectionMatrix = projection;
  26060. if (!this._alternateTransformMatrix) {
  26061. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26062. }
  26063. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26064. if (!this._alternateSceneUbo) {
  26065. this._createAlternateUbo();
  26066. }
  26067. if (this._alternateSceneUbo.useUbo) {
  26068. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26069. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26070. this._alternateSceneUbo.update();
  26071. }
  26072. };
  26073. /**
  26074. * Gets the uniform buffer used to store scene data
  26075. * @returns a UniformBuffer
  26076. */
  26077. Scene.prototype.getSceneUniformBuffer = function () {
  26078. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26079. };
  26080. /**
  26081. * Gets an unique (relatively to the current scene) Id
  26082. * @returns an unique number for the scene
  26083. */
  26084. Scene.prototype.getUniqueId = function () {
  26085. var result = Scene._uniqueIdCounter;
  26086. Scene._uniqueIdCounter++;
  26087. return result;
  26088. };
  26089. /**
  26090. * Add a mesh to the list of scene's meshes
  26091. * @param newMesh defines the mesh to add
  26092. */
  26093. Scene.prototype.addMesh = function (newMesh) {
  26094. this.meshes.push(newMesh);
  26095. //notify the collision coordinator
  26096. if (this.collisionCoordinator) {
  26097. this.collisionCoordinator.onMeshAdded(newMesh);
  26098. }
  26099. newMesh._resyncLightSources();
  26100. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26101. };
  26102. /**
  26103. * Remove a mesh for the list of scene's meshes
  26104. * @param toRemove defines the mesh to remove
  26105. * @param recursive if all child meshes should also be removed from the scene
  26106. * @returns the index where the mesh was in the mesh list
  26107. */
  26108. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26109. var _this = this;
  26110. if (recursive === void 0) { recursive = false; }
  26111. var index = this.meshes.indexOf(toRemove);
  26112. if (index !== -1) {
  26113. // Remove from the scene if mesh found
  26114. this.meshes.splice(index, 1);
  26115. }
  26116. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26117. if (recursive) {
  26118. toRemove.getChildMeshes().forEach(function (m) {
  26119. _this.removeMesh(m);
  26120. });
  26121. }
  26122. return index;
  26123. };
  26124. /**
  26125. * Add a transform node to the list of scene's transform nodes
  26126. * @param newTransformNode defines the transform node to add
  26127. */
  26128. Scene.prototype.addTransformNode = function (newTransformNode) {
  26129. this.transformNodes.push(newTransformNode);
  26130. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26131. };
  26132. /**
  26133. * Remove a transform node for the list of scene's transform nodes
  26134. * @param toRemove defines the transform node to remove
  26135. * @returns the index where the transform node was in the transform node list
  26136. */
  26137. Scene.prototype.removeTransformNode = function (toRemove) {
  26138. var index = this.transformNodes.indexOf(toRemove);
  26139. if (index !== -1) {
  26140. // Remove from the scene if found
  26141. this.transformNodes.splice(index, 1);
  26142. }
  26143. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26144. return index;
  26145. };
  26146. /**
  26147. * Remove a skeleton for the list of scene's skeletons
  26148. * @param toRemove defines the skeleton to remove
  26149. * @returns the index where the skeleton was in the skeleton list
  26150. */
  26151. Scene.prototype.removeSkeleton = function (toRemove) {
  26152. var index = this.skeletons.indexOf(toRemove);
  26153. if (index !== -1) {
  26154. // Remove from the scene if found
  26155. this.skeletons.splice(index, 1);
  26156. }
  26157. return index;
  26158. };
  26159. /**
  26160. * Remove a morph target for the list of scene's morph targets
  26161. * @param toRemove defines the morph target to remove
  26162. * @returns the index where the morph target was in the morph target list
  26163. */
  26164. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26165. var index = this.morphTargetManagers.indexOf(toRemove);
  26166. if (index !== -1) {
  26167. // Remove from the scene if found
  26168. this.morphTargetManagers.splice(index, 1);
  26169. }
  26170. return index;
  26171. };
  26172. /**
  26173. * Remove a light for the list of scene's lights
  26174. * @param toRemove defines the light to remove
  26175. * @returns the index where the light was in the light list
  26176. */
  26177. Scene.prototype.removeLight = function (toRemove) {
  26178. var index = this.lights.indexOf(toRemove);
  26179. if (index !== -1) {
  26180. // Remove from meshes
  26181. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26182. var mesh = _a[_i];
  26183. mesh._removeLightSource(toRemove);
  26184. }
  26185. // Remove from the scene if mesh found
  26186. this.lights.splice(index, 1);
  26187. this.sortLightsByPriority();
  26188. }
  26189. this.onLightRemovedObservable.notifyObservers(toRemove);
  26190. return index;
  26191. };
  26192. /**
  26193. * Remove a camera for the list of scene's cameras
  26194. * @param toRemove defines the camera to remove
  26195. * @returns the index where the camera was in the camera list
  26196. */
  26197. Scene.prototype.removeCamera = function (toRemove) {
  26198. var index = this.cameras.indexOf(toRemove);
  26199. if (index !== -1) {
  26200. // Remove from the scene if mesh found
  26201. this.cameras.splice(index, 1);
  26202. }
  26203. // Remove from activeCameras
  26204. var index2 = this.activeCameras.indexOf(toRemove);
  26205. if (index2 !== -1) {
  26206. // Remove from the scene if mesh found
  26207. this.activeCameras.splice(index2, 1);
  26208. }
  26209. // Reset the activeCamera
  26210. if (this.activeCamera === toRemove) {
  26211. if (this.cameras.length > 0) {
  26212. this.activeCamera = this.cameras[0];
  26213. }
  26214. else {
  26215. this.activeCamera = null;
  26216. }
  26217. }
  26218. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26219. return index;
  26220. };
  26221. /**
  26222. * Remove a particle system for the list of scene's particle systems
  26223. * @param toRemove defines the particle system to remove
  26224. * @returns the index where the particle system was in the particle system list
  26225. */
  26226. Scene.prototype.removeParticleSystem = function (toRemove) {
  26227. var index = this.particleSystems.indexOf(toRemove);
  26228. if (index !== -1) {
  26229. this.particleSystems.splice(index, 1);
  26230. }
  26231. return index;
  26232. };
  26233. /**
  26234. * Remove a animation for the list of scene's animations
  26235. * @param toRemove defines the animation to remove
  26236. * @returns the index where the animation was in the animation list
  26237. */
  26238. Scene.prototype.removeAnimation = function (toRemove) {
  26239. var index = this.animations.indexOf(toRemove);
  26240. if (index !== -1) {
  26241. this.animations.splice(index, 1);
  26242. }
  26243. return index;
  26244. };
  26245. /**
  26246. * Removes the given animation group from this scene.
  26247. * @param toRemove The animation group to remove
  26248. * @returns The index of the removed animation group
  26249. */
  26250. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26251. var index = this.animationGroups.indexOf(toRemove);
  26252. if (index !== -1) {
  26253. this.animationGroups.splice(index, 1);
  26254. }
  26255. return index;
  26256. };
  26257. /**
  26258. * Removes the given multi-material from this scene.
  26259. * @param toRemove The multi-material to remove
  26260. * @returns The index of the removed multi-material
  26261. */
  26262. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26263. var index = this.multiMaterials.indexOf(toRemove);
  26264. if (index !== -1) {
  26265. this.multiMaterials.splice(index, 1);
  26266. }
  26267. return index;
  26268. };
  26269. /**
  26270. * Removes the given material from this scene.
  26271. * @param toRemove The material to remove
  26272. * @returns The index of the removed material
  26273. */
  26274. Scene.prototype.removeMaterial = function (toRemove) {
  26275. var index = this.materials.indexOf(toRemove);
  26276. if (index !== -1) {
  26277. this.materials.splice(index, 1);
  26278. }
  26279. return index;
  26280. };
  26281. /**
  26282. * Removes the given lens flare system from this scene.
  26283. * @param toRemove The lens flare system to remove
  26284. * @returns The index of the removed lens flare system
  26285. */
  26286. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26287. var index = this.lensFlareSystems.indexOf(toRemove);
  26288. if (index !== -1) {
  26289. this.lensFlareSystems.splice(index, 1);
  26290. }
  26291. return index;
  26292. };
  26293. /**
  26294. * Removes the given action manager from this scene.
  26295. * @param toRemove The action manager to remove
  26296. * @returns The index of the removed action manager
  26297. */
  26298. Scene.prototype.removeActionManager = function (toRemove) {
  26299. var index = this._actionManagers.indexOf(toRemove);
  26300. if (index !== -1) {
  26301. this._actionManagers.splice(index, 1);
  26302. }
  26303. return index;
  26304. };
  26305. /**
  26306. * Removes the given effect layer from this scene.
  26307. * @param toRemove defines the effect layer to remove
  26308. * @returns the index of the removed effect layer
  26309. */
  26310. Scene.prototype.removeEffectLayer = function (toRemove) {
  26311. var index = this.effectLayers.indexOf(toRemove);
  26312. if (index !== -1) {
  26313. this.effectLayers.splice(index, 1);
  26314. }
  26315. return index;
  26316. };
  26317. /**
  26318. * Removes the given texture from this scene.
  26319. * @param toRemove The texture to remove
  26320. * @returns The index of the removed texture
  26321. */
  26322. Scene.prototype.removeTexture = function (toRemove) {
  26323. var index = this.textures.indexOf(toRemove);
  26324. if (index !== -1) {
  26325. this.textures.splice(index, 1);
  26326. }
  26327. return index;
  26328. };
  26329. /**
  26330. * Adds the given light to this scene
  26331. * @param newLight The light to add
  26332. */
  26333. Scene.prototype.addLight = function (newLight) {
  26334. this.lights.push(newLight);
  26335. this.sortLightsByPriority();
  26336. // Add light to all meshes (To support if the light is removed and then readded)
  26337. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26338. var mesh = _a[_i];
  26339. if (mesh._lightSources.indexOf(newLight) === -1) {
  26340. mesh._lightSources.push(newLight);
  26341. mesh._resyncLightSources();
  26342. }
  26343. }
  26344. this.onNewLightAddedObservable.notifyObservers(newLight);
  26345. };
  26346. /**
  26347. * Sorts the list list based on light priorities
  26348. */
  26349. Scene.prototype.sortLightsByPriority = function () {
  26350. if (this.requireLightSorting) {
  26351. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26352. }
  26353. };
  26354. /**
  26355. * Adds the given camera to this scene
  26356. * @param newCamera The camera to add
  26357. */
  26358. Scene.prototype.addCamera = function (newCamera) {
  26359. this.cameras.push(newCamera);
  26360. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26361. };
  26362. /**
  26363. * Adds the given skeleton to this scene
  26364. * @param newSkeleton The skeleton to add
  26365. */
  26366. Scene.prototype.addSkeleton = function (newSkeleton) {
  26367. this.skeletons.push(newSkeleton);
  26368. };
  26369. /**
  26370. * Adds the given particle system to this scene
  26371. * @param newParticleSystem The particle system to add
  26372. */
  26373. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26374. this.particleSystems.push(newParticleSystem);
  26375. };
  26376. /**
  26377. * Adds the given animation to this scene
  26378. * @param newAnimation The animation to add
  26379. */
  26380. Scene.prototype.addAnimation = function (newAnimation) {
  26381. this.animations.push(newAnimation);
  26382. };
  26383. /**
  26384. * Adds the given animation group to this scene.
  26385. * @param newAnimationGroup The animation group to add
  26386. */
  26387. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26388. this.animationGroups.push(newAnimationGroup);
  26389. };
  26390. /**
  26391. * Adds the given multi-material to this scene
  26392. * @param newMultiMaterial The multi-material to add
  26393. */
  26394. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26395. this.multiMaterials.push(newMultiMaterial);
  26396. };
  26397. /**
  26398. * Adds the given material to this scene
  26399. * @param newMaterial The material to add
  26400. */
  26401. Scene.prototype.addMaterial = function (newMaterial) {
  26402. this.materials.push(newMaterial);
  26403. };
  26404. /**
  26405. * Adds the given morph target to this scene
  26406. * @param newMorphTargetManager The morph target to add
  26407. */
  26408. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26409. this.morphTargetManagers.push(newMorphTargetManager);
  26410. };
  26411. /**
  26412. * Adds the given geometry to this scene
  26413. * @param newGeometry The geometry to add
  26414. */
  26415. Scene.prototype.addGeometry = function (newGeometry) {
  26416. this._geometries.push(newGeometry);
  26417. };
  26418. /**
  26419. * Adds the given lens flare system to this scene
  26420. * @param newLensFlareSystem The lens flare system to add
  26421. */
  26422. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26423. this.lensFlareSystems.push(newLensFlareSystem);
  26424. };
  26425. /**
  26426. * Adds the given effect layer to this scene
  26427. * @param newEffectLayer defines the effect layer to add
  26428. */
  26429. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26430. this.effectLayers.push(newEffectLayer);
  26431. };
  26432. /**
  26433. * Adds the given action manager to this scene
  26434. * @param newActionManager The action manager to add
  26435. */
  26436. Scene.prototype.addActionManager = function (newActionManager) {
  26437. this._actionManagers.push(newActionManager);
  26438. };
  26439. /**
  26440. * Adds the given texture to this scene.
  26441. * @param newTexture The texture to add
  26442. */
  26443. Scene.prototype.addTexture = function (newTexture) {
  26444. this.textures.push(newTexture);
  26445. };
  26446. /**
  26447. * Switch active camera
  26448. * @param newCamera defines the new active camera
  26449. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26450. */
  26451. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26452. if (attachControl === void 0) { attachControl = true; }
  26453. var canvas = this._engine.getRenderingCanvas();
  26454. if (!canvas) {
  26455. return;
  26456. }
  26457. if (this.activeCamera) {
  26458. this.activeCamera.detachControl(canvas);
  26459. }
  26460. this.activeCamera = newCamera;
  26461. if (attachControl) {
  26462. newCamera.attachControl(canvas);
  26463. }
  26464. };
  26465. /**
  26466. * sets the active camera of the scene using its ID
  26467. * @param id defines the camera's ID
  26468. * @return the new active camera or null if none found.
  26469. */
  26470. Scene.prototype.setActiveCameraByID = function (id) {
  26471. var camera = this.getCameraByID(id);
  26472. if (camera) {
  26473. this.activeCamera = camera;
  26474. return camera;
  26475. }
  26476. return null;
  26477. };
  26478. /**
  26479. * sets the active camera of the scene using its name
  26480. * @param name defines the camera's name
  26481. * @returns the new active camera or null if none found.
  26482. */
  26483. Scene.prototype.setActiveCameraByName = function (name) {
  26484. var camera = this.getCameraByName(name);
  26485. if (camera) {
  26486. this.activeCamera = camera;
  26487. return camera;
  26488. }
  26489. return null;
  26490. };
  26491. /**
  26492. * get an animation group using its name
  26493. * @param name defines the material's name
  26494. * @return the animation group or null if none found.
  26495. */
  26496. Scene.prototype.getAnimationGroupByName = function (name) {
  26497. for (var index = 0; index < this.animationGroups.length; index++) {
  26498. if (this.animationGroups[index].name === name) {
  26499. return this.animationGroups[index];
  26500. }
  26501. }
  26502. return null;
  26503. };
  26504. /**
  26505. * get a material using its id
  26506. * @param id defines the material's ID
  26507. * @return the material or null if none found.
  26508. */
  26509. Scene.prototype.getMaterialByID = function (id) {
  26510. for (var index = 0; index < this.materials.length; index++) {
  26511. if (this.materials[index].id === id) {
  26512. return this.materials[index];
  26513. }
  26514. }
  26515. return null;
  26516. };
  26517. /**
  26518. * Gets a material using its name
  26519. * @param name defines the material's name
  26520. * @return the material or null if none found.
  26521. */
  26522. Scene.prototype.getMaterialByName = function (name) {
  26523. for (var index = 0; index < this.materials.length; index++) {
  26524. if (this.materials[index].name === name) {
  26525. return this.materials[index];
  26526. }
  26527. }
  26528. return null;
  26529. };
  26530. /**
  26531. * Gets a lens flare system using its name
  26532. * @param name defines the name to look for
  26533. * @returns the lens flare system or null if not found
  26534. */
  26535. Scene.prototype.getLensFlareSystemByName = function (name) {
  26536. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26537. if (this.lensFlareSystems[index].name === name) {
  26538. return this.lensFlareSystems[index];
  26539. }
  26540. }
  26541. return null;
  26542. };
  26543. /**
  26544. * Gets a lens flare system using its id
  26545. * @param id defines the id to look for
  26546. * @returns the lens flare system or null if not found
  26547. */
  26548. Scene.prototype.getLensFlareSystemByID = function (id) {
  26549. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26550. if (this.lensFlareSystems[index].id === id) {
  26551. return this.lensFlareSystems[index];
  26552. }
  26553. }
  26554. return null;
  26555. };
  26556. /**
  26557. * Gets a camera using its id
  26558. * @param id defines the id to look for
  26559. * @returns the camera or null if not found
  26560. */
  26561. Scene.prototype.getCameraByID = function (id) {
  26562. for (var index = 0; index < this.cameras.length; index++) {
  26563. if (this.cameras[index].id === id) {
  26564. return this.cameras[index];
  26565. }
  26566. }
  26567. return null;
  26568. };
  26569. /**
  26570. * Gets a camera using its unique id
  26571. * @param uniqueId defines the unique id to look for
  26572. * @returns the camera or null if not found
  26573. */
  26574. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26575. for (var index = 0; index < this.cameras.length; index++) {
  26576. if (this.cameras[index].uniqueId === uniqueId) {
  26577. return this.cameras[index];
  26578. }
  26579. }
  26580. return null;
  26581. };
  26582. /**
  26583. * Gets a camera using its name
  26584. * @param name defines the camera's name
  26585. * @return the camera or null if none found.
  26586. */
  26587. Scene.prototype.getCameraByName = function (name) {
  26588. for (var index = 0; index < this.cameras.length; index++) {
  26589. if (this.cameras[index].name === name) {
  26590. return this.cameras[index];
  26591. }
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * Gets a bone using its id
  26597. * @param id defines the bone's id
  26598. * @return the bone or null if not found
  26599. */
  26600. Scene.prototype.getBoneByID = function (id) {
  26601. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26602. var skeleton = this.skeletons[skeletonIndex];
  26603. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26604. if (skeleton.bones[boneIndex].id === id) {
  26605. return skeleton.bones[boneIndex];
  26606. }
  26607. }
  26608. }
  26609. return null;
  26610. };
  26611. /**
  26612. * Gets a bone using its id
  26613. * @param name defines the bone's name
  26614. * @return the bone or null if not found
  26615. */
  26616. Scene.prototype.getBoneByName = function (name) {
  26617. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26618. var skeleton = this.skeletons[skeletonIndex];
  26619. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26620. if (skeleton.bones[boneIndex].name === name) {
  26621. return skeleton.bones[boneIndex];
  26622. }
  26623. }
  26624. }
  26625. return null;
  26626. };
  26627. /**
  26628. * Gets a light node using its name
  26629. * @param name defines the the light's name
  26630. * @return the light or null if none found.
  26631. */
  26632. Scene.prototype.getLightByName = function (name) {
  26633. for (var index = 0; index < this.lights.length; index++) {
  26634. if (this.lights[index].name === name) {
  26635. return this.lights[index];
  26636. }
  26637. }
  26638. return null;
  26639. };
  26640. /**
  26641. * Gets a light node using its id
  26642. * @param id defines the light's id
  26643. * @return the light or null if none found.
  26644. */
  26645. Scene.prototype.getLightByID = function (id) {
  26646. for (var index = 0; index < this.lights.length; index++) {
  26647. if (this.lights[index].id === id) {
  26648. return this.lights[index];
  26649. }
  26650. }
  26651. return null;
  26652. };
  26653. /**
  26654. * Gets a light node using its scene-generated unique ID
  26655. * @param uniqueId defines the light's unique id
  26656. * @return the light or null if none found.
  26657. */
  26658. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26659. for (var index = 0; index < this.lights.length; index++) {
  26660. if (this.lights[index].uniqueId === uniqueId) {
  26661. return this.lights[index];
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. /**
  26667. * Gets a particle system by id
  26668. * @param id defines the particle system id
  26669. * @return the corresponding system or null if none found
  26670. */
  26671. Scene.prototype.getParticleSystemByID = function (id) {
  26672. for (var index = 0; index < this.particleSystems.length; index++) {
  26673. if (this.particleSystems[index].id === id) {
  26674. return this.particleSystems[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Gets a geometry using its ID
  26681. * @param id defines the geometry's id
  26682. * @return the geometry or null if none found.
  26683. */
  26684. Scene.prototype.getGeometryByID = function (id) {
  26685. for (var index = 0; index < this._geometries.length; index++) {
  26686. if (this._geometries[index].id === id) {
  26687. return this._geometries[index];
  26688. }
  26689. }
  26690. return null;
  26691. };
  26692. /**
  26693. * Add a new geometry to this scene
  26694. * @param geometry defines the geometry to be added to the scene.
  26695. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26696. * @return a boolean defining if the geometry was added or not
  26697. */
  26698. Scene.prototype.pushGeometry = function (geometry, force) {
  26699. if (!force && this.getGeometryByID(geometry.id)) {
  26700. return false;
  26701. }
  26702. this._geometries.push(geometry);
  26703. //notify the collision coordinator
  26704. if (this.collisionCoordinator) {
  26705. this.collisionCoordinator.onGeometryAdded(geometry);
  26706. }
  26707. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26708. return true;
  26709. };
  26710. /**
  26711. * Removes an existing geometry
  26712. * @param geometry defines the geometry to be removed from the scene
  26713. * @return a boolean defining if the geometry was removed or not
  26714. */
  26715. Scene.prototype.removeGeometry = function (geometry) {
  26716. var index = this._geometries.indexOf(geometry);
  26717. if (index > -1) {
  26718. this._geometries.splice(index, 1);
  26719. //notify the collision coordinator
  26720. if (this.collisionCoordinator) {
  26721. this.collisionCoordinator.onGeometryDeleted(geometry);
  26722. }
  26723. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26724. return true;
  26725. }
  26726. return false;
  26727. };
  26728. /**
  26729. * Gets the list of geometries attached to the scene
  26730. * @returns an array of Geometry
  26731. */
  26732. Scene.prototype.getGeometries = function () {
  26733. return this._geometries;
  26734. };
  26735. /**
  26736. * Gets the first added mesh found of a given ID
  26737. * @param id defines the id to search for
  26738. * @return the mesh found or null if not found at all
  26739. */
  26740. Scene.prototype.getMeshByID = function (id) {
  26741. for (var index = 0; index < this.meshes.length; index++) {
  26742. if (this.meshes[index].id === id) {
  26743. return this.meshes[index];
  26744. }
  26745. }
  26746. return null;
  26747. };
  26748. /**
  26749. * Gets a list of meshes using their id
  26750. * @param id defines the id to search for
  26751. * @returns a list of meshes
  26752. */
  26753. Scene.prototype.getMeshesByID = function (id) {
  26754. return this.meshes.filter(function (m) {
  26755. return m.id === id;
  26756. });
  26757. };
  26758. /**
  26759. * Gets the first added transform node found of a given ID
  26760. * @param id defines the id to search for
  26761. * @return the found transform node or null if not found at all.
  26762. */
  26763. Scene.prototype.getTransformNodeByID = function (id) {
  26764. for (var index = 0; index < this.transformNodes.length; index++) {
  26765. if (this.transformNodes[index].id === id) {
  26766. return this.transformNodes[index];
  26767. }
  26768. }
  26769. return null;
  26770. };
  26771. /**
  26772. * Gets a list of transform nodes using their id
  26773. * @param id defines the id to search for
  26774. * @returns a list of transform nodes
  26775. */
  26776. Scene.prototype.getTransformNodesByID = function (id) {
  26777. return this.transformNodes.filter(function (m) {
  26778. return m.id === id;
  26779. });
  26780. };
  26781. /**
  26782. * Gets a mesh with its auto-generated unique id
  26783. * @param uniqueId defines the unique id to search for
  26784. * @return the found mesh or null if not found at all.
  26785. */
  26786. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26787. for (var index = 0; index < this.meshes.length; index++) {
  26788. if (this.meshes[index].uniqueId === uniqueId) {
  26789. return this.meshes[index];
  26790. }
  26791. }
  26792. return null;
  26793. };
  26794. /**
  26795. * Gets a the last added mesh using a given id
  26796. * @param id defines the id to search for
  26797. * @return the found mesh or null if not found at all.
  26798. */
  26799. Scene.prototype.getLastMeshByID = function (id) {
  26800. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26801. if (this.meshes[index].id === id) {
  26802. return this.meshes[index];
  26803. }
  26804. }
  26805. return null;
  26806. };
  26807. /**
  26808. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26809. * @param id defines the id to search for
  26810. * @return the found node or null if not found at all
  26811. */
  26812. Scene.prototype.getLastEntryByID = function (id) {
  26813. var index;
  26814. for (index = this.meshes.length - 1; index >= 0; index--) {
  26815. if (this.meshes[index].id === id) {
  26816. return this.meshes[index];
  26817. }
  26818. }
  26819. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26820. if (this.transformNodes[index].id === id) {
  26821. return this.transformNodes[index];
  26822. }
  26823. }
  26824. for (index = this.cameras.length - 1; index >= 0; index--) {
  26825. if (this.cameras[index].id === id) {
  26826. return this.cameras[index];
  26827. }
  26828. }
  26829. for (index = this.lights.length - 1; index >= 0; index--) {
  26830. if (this.lights[index].id === id) {
  26831. return this.lights[index];
  26832. }
  26833. }
  26834. return null;
  26835. };
  26836. /**
  26837. * Gets a node (Mesh, Camera, Light) using a given id
  26838. * @param id defines the id to search for
  26839. * @return the found node or null if not found at all
  26840. */
  26841. Scene.prototype.getNodeByID = function (id) {
  26842. var mesh = this.getMeshByID(id);
  26843. if (mesh) {
  26844. return mesh;
  26845. }
  26846. var light = this.getLightByID(id);
  26847. if (light) {
  26848. return light;
  26849. }
  26850. var camera = this.getCameraByID(id);
  26851. if (camera) {
  26852. return camera;
  26853. }
  26854. var bone = this.getBoneByID(id);
  26855. return bone;
  26856. };
  26857. /**
  26858. * Gets a node (Mesh, Camera, Light) using a given name
  26859. * @param name defines the name to search for
  26860. * @return the found node or null if not found at all.
  26861. */
  26862. Scene.prototype.getNodeByName = function (name) {
  26863. var mesh = this.getMeshByName(name);
  26864. if (mesh) {
  26865. return mesh;
  26866. }
  26867. var light = this.getLightByName(name);
  26868. if (light) {
  26869. return light;
  26870. }
  26871. var camera = this.getCameraByName(name);
  26872. if (camera) {
  26873. return camera;
  26874. }
  26875. var bone = this.getBoneByName(name);
  26876. return bone;
  26877. };
  26878. /**
  26879. * Gets a mesh using a given name
  26880. * @param name defines the name to search for
  26881. * @return the found mesh or null if not found at all.
  26882. */
  26883. Scene.prototype.getMeshByName = function (name) {
  26884. for (var index = 0; index < this.meshes.length; index++) {
  26885. if (this.meshes[index].name === name) {
  26886. return this.meshes[index];
  26887. }
  26888. }
  26889. return null;
  26890. };
  26891. /**
  26892. * Gets a transform node using a given name
  26893. * @param name defines the name to search for
  26894. * @return the found transform node or null if not found at all.
  26895. */
  26896. Scene.prototype.getTransformNodeByName = function (name) {
  26897. for (var index = 0; index < this.transformNodes.length; index++) {
  26898. if (this.transformNodes[index].name === name) {
  26899. return this.transformNodes[index];
  26900. }
  26901. }
  26902. return null;
  26903. };
  26904. /**
  26905. * Gets a sound using a given name
  26906. * @param name defines the name to search for
  26907. * @return the found sound or null if not found at all.
  26908. */
  26909. Scene.prototype.getSoundByName = function (name) {
  26910. var index;
  26911. if (BABYLON.AudioEngine) {
  26912. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26913. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26914. return this.mainSoundTrack.soundCollection[index];
  26915. }
  26916. }
  26917. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26918. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26919. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26920. return this.soundTracks[sdIndex].soundCollection[index];
  26921. }
  26922. }
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26929. * @param id defines the id to search for
  26930. * @return the found skeleton or null if not found at all.
  26931. */
  26932. Scene.prototype.getLastSkeletonByID = function (id) {
  26933. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26934. if (this.skeletons[index].id === id) {
  26935. return this.skeletons[index];
  26936. }
  26937. }
  26938. return null;
  26939. };
  26940. /**
  26941. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26942. * @param id defines the id to search for
  26943. * @return the found skeleton or null if not found at all.
  26944. */
  26945. Scene.prototype.getSkeletonById = function (id) {
  26946. for (var index = 0; index < this.skeletons.length; index++) {
  26947. if (this.skeletons[index].id === id) {
  26948. return this.skeletons[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a skeleton using a given name
  26955. * @param name defines the name to search for
  26956. * @return the found skeleton or null if not found at all.
  26957. */
  26958. Scene.prototype.getSkeletonByName = function (name) {
  26959. for (var index = 0; index < this.skeletons.length; index++) {
  26960. if (this.skeletons[index].name === name) {
  26961. return this.skeletons[index];
  26962. }
  26963. }
  26964. return null;
  26965. };
  26966. /**
  26967. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26968. * @param id defines the id to search for
  26969. * @return the found morph target manager or null if not found at all.
  26970. */
  26971. Scene.prototype.getMorphTargetManagerById = function (id) {
  26972. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26973. if (this.morphTargetManagers[index].uniqueId === id) {
  26974. return this.morphTargetManagers[index];
  26975. }
  26976. }
  26977. return null;
  26978. };
  26979. /**
  26980. * Gets a boolean indicating if the given mesh is active
  26981. * @param mesh defines the mesh to look for
  26982. * @returns true if the mesh is in the active list
  26983. */
  26984. Scene.prototype.isActiveMesh = function (mesh) {
  26985. return (this._activeMeshes.indexOf(mesh) !== -1);
  26986. };
  26987. /**
  26988. * Return a the first highlight layer of the scene with a given name.
  26989. * @param name The name of the highlight layer to look for.
  26990. * @return The highlight layer if found otherwise null.
  26991. */
  26992. Scene.prototype.getHighlightLayerByName = function (name) {
  26993. for (var index = 0; index < this.effectLayers.length; index++) {
  26994. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26995. return this.effectLayers[index];
  26996. }
  26997. }
  26998. return null;
  26999. };
  27000. /**
  27001. * Return a the first highlight layer of the scene with a given name.
  27002. * @param name The name of the highlight layer to look for.
  27003. * @return The highlight layer if found otherwise null.
  27004. */
  27005. Scene.prototype.getGlowLayerByName = function (name) {
  27006. for (var index = 0; index < this.effectLayers.length; index++) {
  27007. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27008. return this.effectLayers[index];
  27009. }
  27010. }
  27011. return null;
  27012. };
  27013. Object.defineProperty(Scene.prototype, "uid", {
  27014. /**
  27015. * Return a unique id as a string which can serve as an identifier for the scene
  27016. */
  27017. get: function () {
  27018. if (!this._uid) {
  27019. this._uid = BABYLON.Tools.RandomId();
  27020. }
  27021. return this._uid;
  27022. },
  27023. enumerable: true,
  27024. configurable: true
  27025. });
  27026. /**
  27027. * Add an externaly attached data from its key.
  27028. * This method call will fail and return false, if such key already exists.
  27029. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27030. * @param key the unique key that identifies the data
  27031. * @param data the data object to associate to the key for this Engine instance
  27032. * @return true if no such key were already present and the data was added successfully, false otherwise
  27033. */
  27034. Scene.prototype.addExternalData = function (key, data) {
  27035. if (!this._externalData) {
  27036. this._externalData = new BABYLON.StringDictionary();
  27037. }
  27038. return this._externalData.add(key, data);
  27039. };
  27040. /**
  27041. * Get an externaly attached data from its key
  27042. * @param key the unique key that identifies the data
  27043. * @return the associated data, if present (can be null), or undefined if not present
  27044. */
  27045. Scene.prototype.getExternalData = function (key) {
  27046. if (!this._externalData) {
  27047. return null;
  27048. }
  27049. return this._externalData.get(key);
  27050. };
  27051. /**
  27052. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27053. * @param key the unique key that identifies the data
  27054. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27055. * @return the associated data, can be null if the factory returned null.
  27056. */
  27057. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27058. if (!this._externalData) {
  27059. this._externalData = new BABYLON.StringDictionary();
  27060. }
  27061. return this._externalData.getOrAddWithFactory(key, factory);
  27062. };
  27063. /**
  27064. * Remove an externaly attached data from the Engine instance
  27065. * @param key the unique key that identifies the data
  27066. * @return true if the data was successfully removed, false if it doesn't exist
  27067. */
  27068. Scene.prototype.removeExternalData = function (key) {
  27069. return this._externalData.remove(key);
  27070. };
  27071. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27072. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27073. if (mesh.showSubMeshesBoundingBox) {
  27074. var boundingInfo = subMesh.getBoundingInfo();
  27075. if (boundingInfo !== null && boundingInfo !== undefined) {
  27076. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27077. }
  27078. }
  27079. var material = subMesh.getMaterial();
  27080. if (material !== null && material !== undefined) {
  27081. // Render targets
  27082. if (material.getRenderTargetTextures !== undefined) {
  27083. if (this._processedMaterials.indexOf(material) === -1) {
  27084. this._processedMaterials.push(material);
  27085. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27086. }
  27087. }
  27088. // Dispatch
  27089. this._activeIndices.addCount(subMesh.indexCount, false);
  27090. this._renderingManager.dispatch(subMesh, mesh, material);
  27091. }
  27092. }
  27093. };
  27094. /**
  27095. * Clear the processed materials smart array preventing retention point in material dispose.
  27096. */
  27097. Scene.prototype.freeProcessedMaterials = function () {
  27098. this._processedMaterials.dispose();
  27099. };
  27100. /**
  27101. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27102. */
  27103. Scene.prototype.freeActiveMeshes = function () {
  27104. this._activeMeshes.dispose();
  27105. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27106. this.activeCamera._activeMeshes.dispose();
  27107. }
  27108. if (this.activeCameras) {
  27109. for (var i = 0; i < this.activeCameras.length; i++) {
  27110. var activeCamera = this.activeCameras[i];
  27111. if (activeCamera && activeCamera._activeMeshes) {
  27112. activeCamera._activeMeshes.dispose();
  27113. }
  27114. }
  27115. }
  27116. };
  27117. /**
  27118. * Clear the info related to rendering groups preventing retention points during dispose.
  27119. */
  27120. Scene.prototype.freeRenderingGroups = function () {
  27121. if (this._renderingManager) {
  27122. this._renderingManager.freeRenderingGroups();
  27123. }
  27124. if (this.textures) {
  27125. for (var i = 0; i < this.textures.length; i++) {
  27126. var texture = this.textures[i];
  27127. if (texture && texture.renderList) {
  27128. texture.freeRenderingGroups();
  27129. }
  27130. }
  27131. }
  27132. };
  27133. /** @hidden */
  27134. Scene.prototype._isInIntermediateRendering = function () {
  27135. return this._intermediateRendering;
  27136. };
  27137. /**
  27138. * Defines the current active mesh candidate provider
  27139. * @param provider defines the provider to use
  27140. */
  27141. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27142. this._activeMeshCandidateProvider = provider;
  27143. };
  27144. /**
  27145. * Gets the current active mesh candidate provider
  27146. * @returns the current active mesh candidate provider
  27147. */
  27148. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27149. return this._activeMeshCandidateProvider;
  27150. };
  27151. /**
  27152. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27153. * @returns the current scene
  27154. */
  27155. Scene.prototype.freezeActiveMeshes = function () {
  27156. if (!this.activeCamera) {
  27157. return this;
  27158. }
  27159. if (!this._frustumPlanes) {
  27160. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27161. }
  27162. this._evaluateActiveMeshes();
  27163. this._activeMeshesFrozen = true;
  27164. return this;
  27165. };
  27166. /**
  27167. * Use this function to restart evaluating active meshes on every frame
  27168. * @returns the current scene
  27169. */
  27170. Scene.prototype.unfreezeActiveMeshes = function () {
  27171. this._activeMeshesFrozen = false;
  27172. return this;
  27173. };
  27174. Scene.prototype._evaluateActiveMeshes = function () {
  27175. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27176. return;
  27177. }
  27178. if (!this.activeCamera) {
  27179. return;
  27180. }
  27181. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27182. this.activeCamera._activeMeshes.reset();
  27183. this._activeMeshes.reset();
  27184. this._renderingManager.reset();
  27185. this._processedMaterials.reset();
  27186. this._activeParticleSystems.reset();
  27187. this._activeSkeletons.reset();
  27188. this._softwareSkinnedMeshes.reset();
  27189. if (this._boundingBoxRenderer) {
  27190. this._boundingBoxRenderer.reset();
  27191. }
  27192. // Meshes
  27193. var meshes;
  27194. var len;
  27195. var checkIsEnabled = true;
  27196. // Determine mesh candidates
  27197. if (this._activeMeshCandidateProvider !== undefined) {
  27198. // Use _activeMeshCandidateProvider
  27199. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27200. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27201. if (meshes !== undefined) {
  27202. len = meshes.length;
  27203. }
  27204. else {
  27205. len = 0;
  27206. }
  27207. }
  27208. else if (this._selectionOctree !== undefined) {
  27209. // Octree
  27210. var selection = this._selectionOctree.select(this._frustumPlanes);
  27211. meshes = selection.data;
  27212. len = selection.length;
  27213. }
  27214. else {
  27215. // Full scene traversal
  27216. len = this.meshes.length;
  27217. meshes = this.meshes;
  27218. }
  27219. // Check each mesh
  27220. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27221. mesh = meshes[meshIndex];
  27222. if (mesh.isBlocked) {
  27223. continue;
  27224. }
  27225. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27226. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27227. continue;
  27228. }
  27229. mesh.computeWorldMatrix();
  27230. // Intersections
  27231. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27232. this._meshesForIntersections.pushNoDuplicate(mesh);
  27233. }
  27234. // Switch to current LOD
  27235. meshLOD = mesh.getLOD(this.activeCamera);
  27236. if (meshLOD === undefined || meshLOD === null) {
  27237. continue;
  27238. }
  27239. mesh._preActivate();
  27240. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27241. this._activeMeshes.push(mesh);
  27242. this.activeCamera._activeMeshes.push(mesh);
  27243. mesh._activate(this._renderId);
  27244. if (meshLOD !== mesh) {
  27245. meshLOD._activate(this._renderId);
  27246. }
  27247. this._activeMesh(mesh, meshLOD);
  27248. }
  27249. }
  27250. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27251. // Particle systems
  27252. if (this.particlesEnabled) {
  27253. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27254. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27255. var particleSystem = this.particleSystems[particleIndex];
  27256. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27257. continue;
  27258. }
  27259. var emitter = particleSystem.emitter;
  27260. if (!emitter.position || emitter.isEnabled()) {
  27261. this._activeParticleSystems.push(particleSystem);
  27262. particleSystem.animate();
  27263. this._renderingManager.dispatchParticles(particleSystem);
  27264. }
  27265. }
  27266. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27267. }
  27268. };
  27269. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27270. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27271. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27272. mesh.skeleton.prepare();
  27273. }
  27274. if (!mesh.computeBonesUsingShaders) {
  27275. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27276. }
  27277. }
  27278. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27279. var boundingInfo = sourceMesh.getBoundingInfo();
  27280. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27281. }
  27282. if (mesh !== undefined && mesh !== null
  27283. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27284. // Submeshes Octrees
  27285. var len;
  27286. var subMeshes;
  27287. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27288. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27289. len = intersections.length;
  27290. subMeshes = intersections.data;
  27291. }
  27292. else {
  27293. subMeshes = mesh.subMeshes;
  27294. len = subMeshes.length;
  27295. }
  27296. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27297. subMesh = subMeshes[subIndex];
  27298. this._evaluateSubMesh(subMesh, mesh);
  27299. }
  27300. }
  27301. };
  27302. /**
  27303. * Update the transform matrix to update from the current active camera
  27304. * @param force defines a boolean used to force the update even if cache is up to date
  27305. */
  27306. Scene.prototype.updateTransformMatrix = function (force) {
  27307. if (!this.activeCamera) {
  27308. return;
  27309. }
  27310. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27311. };
  27312. /**
  27313. * 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)
  27314. * @param alternateCamera defines the camera to use
  27315. */
  27316. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27317. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27318. };
  27319. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27320. if (camera && camera._skipRendering) {
  27321. return;
  27322. }
  27323. var engine = this._engine;
  27324. this.activeCamera = camera;
  27325. if (!this.activeCamera)
  27326. throw new Error("Active camera not set");
  27327. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27328. // Viewport
  27329. engine.setViewport(this.activeCamera.viewport);
  27330. // Camera
  27331. this.resetCachedMaterial();
  27332. this._renderId++;
  27333. this.updateTransformMatrix();
  27334. if (camera._alternateCamera) {
  27335. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27336. this._alternateRendering = true;
  27337. }
  27338. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27339. // Meshes
  27340. this._evaluateActiveMeshes();
  27341. // Software skinning
  27342. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27343. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27344. mesh.applySkeleton(mesh.skeleton);
  27345. }
  27346. // Render targets
  27347. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27348. var needsRestoreFrameBuffer = false;
  27349. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27350. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27351. }
  27352. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27353. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27354. }
  27355. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27356. this._intermediateRendering = true;
  27357. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27358. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27359. var renderTarget = this._renderTargets.data[renderIndex];
  27360. if (renderTarget._shouldRender()) {
  27361. this._renderId++;
  27362. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27363. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27364. }
  27365. }
  27366. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27367. this._intermediateRendering = false;
  27368. this._renderId++;
  27369. needsRestoreFrameBuffer = true; // Restore back buffer
  27370. }
  27371. // Render EffecttLayer Texture
  27372. var stencilState = this._engine.getStencilBuffer();
  27373. var renderEffects = false;
  27374. var needStencil = false;
  27375. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27376. this._intermediateRendering = true;
  27377. for (var i = 0; i < this.effectLayers.length; i++) {
  27378. var effectLayer = this.effectLayers[i];
  27379. if (effectLayer.shouldRender() &&
  27380. (!effectLayer.camera ||
  27381. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27382. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27383. renderEffects = true;
  27384. needStencil = needStencil || effectLayer.needStencil();
  27385. var renderTarget = effectLayer._mainTexture;
  27386. if (renderTarget._shouldRender()) {
  27387. this._renderId++;
  27388. renderTarget.render(false, false);
  27389. needsRestoreFrameBuffer = true;
  27390. }
  27391. }
  27392. }
  27393. this._intermediateRendering = false;
  27394. this._renderId++;
  27395. }
  27396. if (needsRestoreFrameBuffer) {
  27397. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27398. }
  27399. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27400. // Prepare Frame
  27401. this.postProcessManager._prepareFrame();
  27402. // Backgrounds
  27403. var layerIndex;
  27404. var layer;
  27405. if (this.layers.length) {
  27406. engine.setDepthBuffer(false);
  27407. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27408. layer = this.layers[layerIndex];
  27409. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27410. layer.render();
  27411. }
  27412. }
  27413. engine.setDepthBuffer(true);
  27414. }
  27415. // Activate effect Layer stencil
  27416. if (needStencil) {
  27417. this._engine.setStencilBuffer(true);
  27418. }
  27419. // Render
  27420. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27421. this._renderingManager.render(null, null, true, true);
  27422. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27423. // Restore effect Layer stencil
  27424. if (needStencil) {
  27425. this._engine.setStencilBuffer(stencilState);
  27426. }
  27427. // Bounding boxes
  27428. if (this._boundingBoxRenderer) {
  27429. this._boundingBoxRenderer.render();
  27430. }
  27431. // Lens flares
  27432. if (this.lensFlaresEnabled) {
  27433. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27434. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27435. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27436. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27437. lensFlareSystem.render();
  27438. }
  27439. }
  27440. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27441. }
  27442. // Effect Layer
  27443. if (renderEffects) {
  27444. engine.setDepthBuffer(false);
  27445. for (var i = 0; i < this.effectLayers.length; i++) {
  27446. if (this.effectLayers[i].shouldRender()) {
  27447. this.effectLayers[i].render();
  27448. }
  27449. }
  27450. engine.setDepthBuffer(true);
  27451. }
  27452. // Foregrounds
  27453. if (this.layers.length) {
  27454. engine.setDepthBuffer(false);
  27455. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27456. layer = this.layers[layerIndex];
  27457. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27458. layer.render();
  27459. }
  27460. }
  27461. engine.setDepthBuffer(true);
  27462. }
  27463. // Finalize frame
  27464. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27465. // Reset some special arrays
  27466. this._renderTargets.reset();
  27467. this._alternateRendering = false;
  27468. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27469. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27470. };
  27471. Scene.prototype._processSubCameras = function (camera) {
  27472. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27473. this._renderForCamera(camera);
  27474. return;
  27475. }
  27476. // rig cameras
  27477. for (var index = 0; index < camera._rigCameras.length; index++) {
  27478. this._renderForCamera(camera._rigCameras[index], camera);
  27479. }
  27480. this.activeCamera = camera;
  27481. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27482. };
  27483. Scene.prototype._checkIntersections = function () {
  27484. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27485. var sourceMesh = this._meshesForIntersections.data[index];
  27486. if (!sourceMesh.actionManager) {
  27487. continue;
  27488. }
  27489. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27490. var action = sourceMesh.actionManager.actions[actionIndex];
  27491. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27492. var parameters = action.getTriggerParameter();
  27493. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27494. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27495. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27496. if (areIntersecting && currentIntersectionInProgress === -1) {
  27497. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27498. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27499. sourceMesh._intersectionsInProgress.push(otherMesh);
  27500. }
  27501. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27502. sourceMesh._intersectionsInProgress.push(otherMesh);
  27503. }
  27504. }
  27505. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27506. //They intersected, and now they don't.
  27507. //is this trigger an exit trigger? execute an event.
  27508. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27509. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27510. }
  27511. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27512. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27513. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27514. return otherMesh === parameterMesh;
  27515. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27516. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27517. }
  27518. }
  27519. }
  27520. }
  27521. }
  27522. };
  27523. /**
  27524. * Render the scene
  27525. */
  27526. Scene.prototype.render = function () {
  27527. if (this.isDisposed) {
  27528. return;
  27529. }
  27530. this._activeParticles.fetchNewFrame();
  27531. this._totalVertices.fetchNewFrame();
  27532. this._activeIndices.fetchNewFrame();
  27533. this._activeBones.fetchNewFrame();
  27534. this._meshesForIntersections.reset();
  27535. this.resetCachedMaterial();
  27536. this.onBeforeAnimationsObservable.notifyObservers(this);
  27537. // Actions
  27538. if (this.actionManager) {
  27539. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27540. }
  27541. //Simplification Queue
  27542. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27543. this.simplificationQueue.executeNext();
  27544. }
  27545. if (this._engine.isDeterministicLockStep()) {
  27546. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27547. var defaultFPS = (60.0 / 1000.0);
  27548. var defaultFrameTime = 1000 / 60; // frame time in MS
  27549. if (this._physicsEngine) {
  27550. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27551. }
  27552. var stepsTaken = 0;
  27553. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27554. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27555. internalSteps = Math.min(internalSteps, maxSubSteps);
  27556. do {
  27557. this.onBeforeStepObservable.notifyObservers(this);
  27558. // Animations
  27559. this._animationRatio = defaultFrameTime * defaultFPS;
  27560. this._animate();
  27561. this.onAfterAnimationsObservable.notifyObservers(this);
  27562. // Physics
  27563. if (this._physicsEngine) {
  27564. this.onBeforePhysicsObservable.notifyObservers(this);
  27565. this._physicsEngine._step(defaultFrameTime / 1000);
  27566. this.onAfterPhysicsObservable.notifyObservers(this);
  27567. }
  27568. this.onAfterStepObservable.notifyObservers(this);
  27569. this._currentStepId++;
  27570. stepsTaken++;
  27571. deltaTime -= defaultFrameTime;
  27572. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27573. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27574. }
  27575. else {
  27576. // Animations
  27577. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27578. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27579. this._animate();
  27580. this.onAfterAnimationsObservable.notifyObservers(this);
  27581. // Physics
  27582. if (this._physicsEngine) {
  27583. this.onBeforePhysicsObservable.notifyObservers(this);
  27584. this._physicsEngine._step(deltaTime / 1000.0);
  27585. this.onAfterPhysicsObservable.notifyObservers(this);
  27586. }
  27587. }
  27588. // update gamepad manager
  27589. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27590. this._gamepadManager._checkGamepadsStatus();
  27591. }
  27592. // Update Cameras
  27593. if (this.activeCameras.length > 0) {
  27594. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27595. var camera = this.activeCameras[cameraIndex];
  27596. camera.update();
  27597. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27598. // rig cameras
  27599. for (var index = 0; index < camera._rigCameras.length; index++) {
  27600. camera._rigCameras[index].update();
  27601. }
  27602. }
  27603. }
  27604. }
  27605. else if (this.activeCamera) {
  27606. this.activeCamera.update();
  27607. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27608. // rig cameras
  27609. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27610. this.activeCamera._rigCameras[index].update();
  27611. }
  27612. }
  27613. }
  27614. // Before render
  27615. this.onBeforeRenderObservable.notifyObservers(this);
  27616. // Customs render targets
  27617. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27618. var engine = this.getEngine();
  27619. var currentActiveCamera = this.activeCamera;
  27620. if (this.renderTargetsEnabled) {
  27621. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27622. this._intermediateRendering = true;
  27623. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27624. var renderTarget = this.customRenderTargets[customIndex];
  27625. if (renderTarget._shouldRender()) {
  27626. this._renderId++;
  27627. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27628. if (!this.activeCamera)
  27629. throw new Error("Active camera not set");
  27630. // Viewport
  27631. engine.setViewport(this.activeCamera.viewport);
  27632. // Camera
  27633. this.updateTransformMatrix();
  27634. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27635. }
  27636. }
  27637. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27638. this._intermediateRendering = false;
  27639. this._renderId++;
  27640. }
  27641. // Restore back buffer
  27642. if (this.customRenderTargets.length > 0) {
  27643. engine.restoreDefaultFramebuffer();
  27644. }
  27645. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27646. this.activeCamera = currentActiveCamera;
  27647. // Procedural textures
  27648. if (this.proceduralTexturesEnabled) {
  27649. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27650. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27651. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27652. if (proceduralTexture._shouldRender()) {
  27653. proceduralTexture.render();
  27654. }
  27655. }
  27656. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27657. }
  27658. // Clear
  27659. if (this.autoClearDepthAndStencil || this.autoClear) {
  27660. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27661. }
  27662. // Shadows
  27663. if (this.shadowsEnabled) {
  27664. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27665. var light = this.lights[lightIndex];
  27666. var shadowGenerator = light.getShadowGenerator();
  27667. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27668. var shadowMap = (shadowGenerator.getShadowMap());
  27669. if (this.textures.indexOf(shadowMap) !== -1) {
  27670. this._renderTargets.push(shadowMap);
  27671. }
  27672. }
  27673. }
  27674. }
  27675. // Depth renderer
  27676. for (var key in this._depthRenderer) {
  27677. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27678. }
  27679. // Geometry renderer
  27680. if (this._geometryBufferRenderer) {
  27681. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27682. }
  27683. // RenderPipeline
  27684. if (this._postProcessRenderPipelineManager) {
  27685. this._postProcessRenderPipelineManager.update();
  27686. }
  27687. // Multi-cameras?
  27688. if (this.activeCameras.length > 0) {
  27689. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27690. if (cameraIndex > 0) {
  27691. this._engine.clear(null, false, true, true);
  27692. }
  27693. this._processSubCameras(this.activeCameras[cameraIndex]);
  27694. }
  27695. }
  27696. else {
  27697. if (!this.activeCamera) {
  27698. throw new Error("No camera defined");
  27699. }
  27700. this._processSubCameras(this.activeCamera);
  27701. }
  27702. // Intersection checks
  27703. this._checkIntersections();
  27704. // Update the audio listener attached to the camera
  27705. if (BABYLON.AudioEngine) {
  27706. this._updateAudioParameters();
  27707. }
  27708. // After render
  27709. if (this.afterRender) {
  27710. this.afterRender();
  27711. }
  27712. this.onAfterRenderObservable.notifyObservers(this);
  27713. // Cleaning
  27714. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27715. var data = this._toBeDisposed.data[index];
  27716. if (data) {
  27717. data.dispose();
  27718. }
  27719. this._toBeDisposed[index] = null;
  27720. }
  27721. this._toBeDisposed.reset();
  27722. if (this.dumpNextRenderTargets) {
  27723. this.dumpNextRenderTargets = false;
  27724. }
  27725. this._activeBones.addCount(0, true);
  27726. this._activeIndices.addCount(0, true);
  27727. this._activeParticles.addCount(0, true);
  27728. };
  27729. Scene.prototype._updateAudioParameters = function () {
  27730. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27731. return;
  27732. }
  27733. var listeningCamera;
  27734. var audioEngine = BABYLON.Engine.audioEngine;
  27735. if (this.activeCameras.length > 0) {
  27736. listeningCamera = this.activeCameras[0];
  27737. }
  27738. else {
  27739. listeningCamera = this.activeCamera;
  27740. }
  27741. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27742. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27743. // for VR cameras
  27744. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27745. listeningCamera = listeningCamera.rigCameras[0];
  27746. }
  27747. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27748. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27749. cameraDirection.normalize();
  27750. // To avoid some errors on GearVR
  27751. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27752. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27753. }
  27754. var i;
  27755. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27756. var sound = this.mainSoundTrack.soundCollection[i];
  27757. if (sound.useCustomAttenuation) {
  27758. sound.updateDistanceFromListener();
  27759. }
  27760. }
  27761. for (i = 0; i < this.soundTracks.length; i++) {
  27762. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27763. sound = this.soundTracks[i].soundCollection[j];
  27764. if (sound.useCustomAttenuation) {
  27765. sound.updateDistanceFromListener();
  27766. }
  27767. }
  27768. }
  27769. }
  27770. };
  27771. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27772. // Audio
  27773. /**
  27774. * Gets or sets if audio support is enabled
  27775. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27776. */
  27777. get: function () {
  27778. return this._audioEnabled;
  27779. },
  27780. set: function (value) {
  27781. this._audioEnabled = value;
  27782. if (BABYLON.AudioEngine) {
  27783. if (this._audioEnabled) {
  27784. this._enableAudio();
  27785. }
  27786. else {
  27787. this._disableAudio();
  27788. }
  27789. }
  27790. },
  27791. enumerable: true,
  27792. configurable: true
  27793. });
  27794. Scene.prototype._disableAudio = function () {
  27795. var i;
  27796. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27797. this.mainSoundTrack.soundCollection[i].pause();
  27798. }
  27799. for (i = 0; i < this.soundTracks.length; i++) {
  27800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27801. this.soundTracks[i].soundCollection[j].pause();
  27802. }
  27803. }
  27804. };
  27805. Scene.prototype._enableAudio = function () {
  27806. var i;
  27807. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27808. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27809. this.mainSoundTrack.soundCollection[i].play();
  27810. }
  27811. }
  27812. for (i = 0; i < this.soundTracks.length; i++) {
  27813. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27814. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27815. this.soundTracks[i].soundCollection[j].play();
  27816. }
  27817. }
  27818. }
  27819. };
  27820. Object.defineProperty(Scene.prototype, "headphone", {
  27821. /**
  27822. * Gets or sets if audio will be output to headphones
  27823. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27824. */
  27825. get: function () {
  27826. return this._headphone;
  27827. },
  27828. set: function (value) {
  27829. this._headphone = value;
  27830. if (BABYLON.AudioEngine) {
  27831. if (this._headphone) {
  27832. this._switchAudioModeForHeadphones();
  27833. }
  27834. else {
  27835. this._switchAudioModeForNormalSpeakers();
  27836. }
  27837. }
  27838. },
  27839. enumerable: true,
  27840. configurable: true
  27841. });
  27842. Scene.prototype._switchAudioModeForHeadphones = function () {
  27843. this.mainSoundTrack.switchPanningModelToHRTF();
  27844. for (var i = 0; i < this.soundTracks.length; i++) {
  27845. this.soundTracks[i].switchPanningModelToHRTF();
  27846. }
  27847. };
  27848. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27849. this.mainSoundTrack.switchPanningModelToEqualPower();
  27850. for (var i = 0; i < this.soundTracks.length; i++) {
  27851. this.soundTracks[i].switchPanningModelToEqualPower();
  27852. }
  27853. };
  27854. /**
  27855. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27856. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27857. * @returns the created depth renderer
  27858. */
  27859. Scene.prototype.enableDepthRenderer = function (camera) {
  27860. camera = camera || this.activeCamera;
  27861. if (!camera) {
  27862. throw "No camera available to enable depth renderer";
  27863. }
  27864. if (!this._depthRenderer[camera.id]) {
  27865. var textureType = 0;
  27866. if (this._engine.getCaps().textureHalfFloatRender) {
  27867. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27868. }
  27869. else if (this._engine.getCaps().textureFloatRender) {
  27870. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27871. }
  27872. else {
  27873. throw "Depth renderer does not support int texture type";
  27874. }
  27875. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27876. }
  27877. return this._depthRenderer[camera.id];
  27878. };
  27879. /**
  27880. * Disables a depth renderer for a given camera
  27881. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27882. */
  27883. Scene.prototype.disableDepthRenderer = function (camera) {
  27884. camera = camera || this.activeCamera;
  27885. if (!camera || !this._depthRenderer[camera.id]) {
  27886. return;
  27887. }
  27888. this._depthRenderer[camera.id].dispose();
  27889. delete this._depthRenderer[camera.id];
  27890. };
  27891. /**
  27892. * Enables a GeometryBufferRender and associates it with the scene
  27893. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27894. * @returns the GeometryBufferRenderer
  27895. */
  27896. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27897. if (ratio === void 0) { ratio = 1; }
  27898. if (this._geometryBufferRenderer) {
  27899. return this._geometryBufferRenderer;
  27900. }
  27901. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27902. if (!this._geometryBufferRenderer.isSupported) {
  27903. this._geometryBufferRenderer = null;
  27904. }
  27905. return this._geometryBufferRenderer;
  27906. };
  27907. /**
  27908. * Disables the GeometryBufferRender associated with the scene
  27909. */
  27910. Scene.prototype.disableGeometryBufferRenderer = function () {
  27911. if (!this._geometryBufferRenderer) {
  27912. return;
  27913. }
  27914. this._geometryBufferRenderer.dispose();
  27915. this._geometryBufferRenderer = null;
  27916. };
  27917. /**
  27918. * Freeze all materials
  27919. * A frozen material will not be updatable but should be faster to render
  27920. */
  27921. Scene.prototype.freezeMaterials = function () {
  27922. for (var i = 0; i < this.materials.length; i++) {
  27923. this.materials[i].freeze();
  27924. }
  27925. };
  27926. /**
  27927. * Unfreeze all materials
  27928. * A frozen material will not be updatable but should be faster to render
  27929. */
  27930. Scene.prototype.unfreezeMaterials = function () {
  27931. for (var i = 0; i < this.materials.length; i++) {
  27932. this.materials[i].unfreeze();
  27933. }
  27934. };
  27935. /**
  27936. * Releases all held ressources
  27937. */
  27938. Scene.prototype.dispose = function () {
  27939. this.beforeRender = null;
  27940. this.afterRender = null;
  27941. this.skeletons = [];
  27942. this.morphTargetManagers = [];
  27943. this.importedMeshesFiles = new Array();
  27944. this.stopAllAnimations();
  27945. this.resetCachedMaterial();
  27946. for (var key in this._depthRenderer) {
  27947. this._depthRenderer[key].dispose();
  27948. }
  27949. if (this._gamepadManager) {
  27950. this._gamepadManager.dispose();
  27951. this._gamepadManager = null;
  27952. }
  27953. // Smart arrays
  27954. if (this.activeCamera) {
  27955. this.activeCamera._activeMeshes.dispose();
  27956. this.activeCamera = null;
  27957. }
  27958. this._activeMeshes.dispose();
  27959. this._renderingManager.dispose();
  27960. this._processedMaterials.dispose();
  27961. this._activeParticleSystems.dispose();
  27962. this._activeSkeletons.dispose();
  27963. this._softwareSkinnedMeshes.dispose();
  27964. this._renderTargets.dispose();
  27965. this._registeredForLateAnimationBindings.dispose();
  27966. if (this._boundingBoxRenderer) {
  27967. this._boundingBoxRenderer.dispose();
  27968. }
  27969. this._meshesForIntersections.dispose();
  27970. this._toBeDisposed.dispose();
  27971. // Abort active requests
  27972. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27973. var request = _a[_i];
  27974. request.abort();
  27975. }
  27976. // Debug layer
  27977. if (this._debugLayer) {
  27978. this._debugLayer.hide();
  27979. }
  27980. // Events
  27981. this.onDisposeObservable.notifyObservers(this);
  27982. this.onDisposeObservable.clear();
  27983. this.onBeforeRenderObservable.clear();
  27984. this.onAfterRenderObservable.clear();
  27985. this.onBeforeRenderTargetsRenderObservable.clear();
  27986. this.onAfterRenderTargetsRenderObservable.clear();
  27987. this.onAfterStepObservable.clear();
  27988. this.onBeforeStepObservable.clear();
  27989. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27990. this.onAfterActiveMeshesEvaluationObservable.clear();
  27991. this.onBeforeParticlesRenderingObservable.clear();
  27992. this.onAfterParticlesRenderingObservable.clear();
  27993. this.onBeforeSpritesRenderingObservable.clear();
  27994. this.onAfterSpritesRenderingObservable.clear();
  27995. this.onBeforeDrawPhaseObservable.clear();
  27996. this.onAfterDrawPhaseObservable.clear();
  27997. this.onBeforePhysicsObservable.clear();
  27998. this.onAfterPhysicsObservable.clear();
  27999. this.onBeforeAnimationsObservable.clear();
  28000. this.onAfterAnimationsObservable.clear();
  28001. this.onDataLoadedObservable.clear();
  28002. this.detachControl();
  28003. // Release sounds & sounds tracks
  28004. if (BABYLON.AudioEngine) {
  28005. this.disposeSounds();
  28006. }
  28007. // VR Helper
  28008. if (this.VRHelper) {
  28009. this.VRHelper.dispose();
  28010. }
  28011. // Detach cameras
  28012. var canvas = this._engine.getRenderingCanvas();
  28013. if (canvas) {
  28014. var index;
  28015. for (index = 0; index < this.cameras.length; index++) {
  28016. this.cameras[index].detachControl(canvas);
  28017. }
  28018. }
  28019. // Release animation groups
  28020. while (this.animationGroups.length) {
  28021. this.animationGroups[0].dispose();
  28022. }
  28023. // Release lights
  28024. while (this.lights.length) {
  28025. this.lights[0].dispose();
  28026. }
  28027. // Release meshes
  28028. while (this.meshes.length) {
  28029. this.meshes[0].dispose(true);
  28030. }
  28031. while (this.transformNodes.length) {
  28032. this.removeTransformNode(this.transformNodes[0]);
  28033. }
  28034. // Release cameras
  28035. while (this.cameras.length) {
  28036. this.cameras[0].dispose();
  28037. }
  28038. // Release materials
  28039. if (this.defaultMaterial) {
  28040. this.defaultMaterial.dispose();
  28041. }
  28042. while (this.multiMaterials.length) {
  28043. this.multiMaterials[0].dispose();
  28044. }
  28045. while (this.materials.length) {
  28046. this.materials[0].dispose();
  28047. }
  28048. // Release particles
  28049. while (this.particleSystems.length) {
  28050. this.particleSystems[0].dispose();
  28051. }
  28052. // Release sprites
  28053. while (this.spriteManagers.length) {
  28054. this.spriteManagers[0].dispose();
  28055. }
  28056. // Release postProcesses
  28057. while (this.postProcesses.length) {
  28058. this.postProcesses[0].dispose();
  28059. }
  28060. // Release layers
  28061. while (this.layers.length) {
  28062. this.layers[0].dispose();
  28063. }
  28064. while (this.effectLayers.length) {
  28065. this.effectLayers[0].dispose();
  28066. }
  28067. // Release textures
  28068. while (this.textures.length) {
  28069. this.textures[0].dispose();
  28070. }
  28071. // Release UBO
  28072. this._sceneUbo.dispose();
  28073. if (this._alternateSceneUbo) {
  28074. this._alternateSceneUbo.dispose();
  28075. }
  28076. // Post-processes
  28077. this.postProcessManager.dispose();
  28078. if (this._postProcessRenderPipelineManager) {
  28079. this._postProcessRenderPipelineManager.dispose();
  28080. }
  28081. // Physics
  28082. if (this._physicsEngine) {
  28083. this.disablePhysicsEngine();
  28084. }
  28085. // Remove from engine
  28086. index = this._engine.scenes.indexOf(this);
  28087. if (index > -1) {
  28088. this._engine.scenes.splice(index, 1);
  28089. }
  28090. this._engine.wipeCaches(true);
  28091. this._isDisposed = true;
  28092. };
  28093. Object.defineProperty(Scene.prototype, "isDisposed", {
  28094. /**
  28095. * Gets if the scene is already disposed
  28096. */
  28097. get: function () {
  28098. return this._isDisposed;
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. /**
  28104. * Releases sounds & soundtracks
  28105. */
  28106. Scene.prototype.disposeSounds = function () {
  28107. if (!this._mainSoundTrack) {
  28108. return;
  28109. }
  28110. this.mainSoundTrack.dispose();
  28111. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28112. this.soundTracks[scIndex].dispose();
  28113. }
  28114. };
  28115. // Octrees
  28116. /**
  28117. * Get the world extend vectors with an optional filter
  28118. *
  28119. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28120. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28121. */
  28122. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28123. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28124. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28125. filterPredicate = filterPredicate || (function () { return true; });
  28126. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28127. mesh.computeWorldMatrix(true);
  28128. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28129. return;
  28130. }
  28131. var boundingInfo = mesh.getBoundingInfo();
  28132. var minBox = boundingInfo.boundingBox.minimumWorld;
  28133. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28134. BABYLON.Tools.CheckExtends(minBox, min, max);
  28135. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28136. });
  28137. return {
  28138. min: min,
  28139. max: max
  28140. };
  28141. };
  28142. /**
  28143. * Creates or updates the octree used to boost selection (picking)
  28144. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28145. * @param maxCapacity defines the maximum capacity per leaf
  28146. * @param maxDepth defines the maximum depth of the octree
  28147. * @returns an octree of AbstractMesh
  28148. */
  28149. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28150. if (maxCapacity === void 0) { maxCapacity = 64; }
  28151. if (maxDepth === void 0) { maxDepth = 2; }
  28152. if (!this._selectionOctree) {
  28153. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28154. }
  28155. var worldExtends = this.getWorldExtends();
  28156. // Update octree
  28157. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28158. return this._selectionOctree;
  28159. };
  28160. // Picking
  28161. /**
  28162. * Creates a ray that can be used to pick in the scene
  28163. * @param x defines the x coordinate of the origin (on-screen)
  28164. * @param y defines the y coordinate of the origin (on-screen)
  28165. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28166. * @param camera defines the camera to use for the picking
  28167. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28168. * @returns a Ray
  28169. */
  28170. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28171. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28172. var result = BABYLON.Ray.Zero();
  28173. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28174. return result;
  28175. };
  28176. /**
  28177. * Creates a ray that can be used to pick in the scene
  28178. * @param x defines the x coordinate of the origin (on-screen)
  28179. * @param y defines the y coordinate of the origin (on-screen)
  28180. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28181. * @param result defines the ray where to store the picking ray
  28182. * @param camera defines the camera to use for the picking
  28183. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28184. * @returns the current scene
  28185. */
  28186. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28187. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28188. var engine = this._engine;
  28189. if (!camera) {
  28190. if (!this.activeCamera)
  28191. throw new Error("Active camera not set");
  28192. camera = this.activeCamera;
  28193. }
  28194. var cameraViewport = camera.viewport;
  28195. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28196. // Moving coordinates to local viewport world
  28197. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28198. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28199. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28200. return this;
  28201. };
  28202. /**
  28203. * Creates a ray that can be used to pick in the scene
  28204. * @param x defines the x coordinate of the origin (on-screen)
  28205. * @param y defines the y coordinate of the origin (on-screen)
  28206. * @param camera defines the camera to use for the picking
  28207. * @returns a Ray
  28208. */
  28209. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28210. var result = BABYLON.Ray.Zero();
  28211. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28212. return result;
  28213. };
  28214. /**
  28215. * Creates a ray that can be used to pick in the scene
  28216. * @param x defines the x coordinate of the origin (on-screen)
  28217. * @param y defines the y coordinate of the origin (on-screen)
  28218. * @param result defines the ray where to store the picking ray
  28219. * @param camera defines the camera to use for the picking
  28220. * @returns the current scene
  28221. */
  28222. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28223. if (!BABYLON.PickingInfo) {
  28224. return this;
  28225. }
  28226. var engine = this._engine;
  28227. if (!camera) {
  28228. if (!this.activeCamera)
  28229. throw new Error("Active camera not set");
  28230. camera = this.activeCamera;
  28231. }
  28232. var cameraViewport = camera.viewport;
  28233. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28234. var identity = BABYLON.Matrix.Identity();
  28235. // Moving coordinates to local viewport world
  28236. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28237. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28238. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28239. return this;
  28240. };
  28241. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28242. if (!BABYLON.PickingInfo) {
  28243. return null;
  28244. }
  28245. var pickingInfo = null;
  28246. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28247. var mesh = this.meshes[meshIndex];
  28248. if (predicate) {
  28249. if (!predicate(mesh)) {
  28250. continue;
  28251. }
  28252. }
  28253. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28254. continue;
  28255. }
  28256. var world = mesh.getWorldMatrix();
  28257. var ray = rayFunction(world);
  28258. var result = mesh.intersects(ray, fastCheck);
  28259. if (!result || !result.hit)
  28260. continue;
  28261. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28262. continue;
  28263. pickingInfo = result;
  28264. if (fastCheck) {
  28265. break;
  28266. }
  28267. }
  28268. return pickingInfo || new BABYLON.PickingInfo();
  28269. };
  28270. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28271. if (!BABYLON.PickingInfo) {
  28272. return null;
  28273. }
  28274. var pickingInfos = new Array();
  28275. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28276. var mesh = this.meshes[meshIndex];
  28277. if (predicate) {
  28278. if (!predicate(mesh)) {
  28279. continue;
  28280. }
  28281. }
  28282. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28283. continue;
  28284. }
  28285. var world = mesh.getWorldMatrix();
  28286. var ray = rayFunction(world);
  28287. var result = mesh.intersects(ray, false);
  28288. if (!result || !result.hit)
  28289. continue;
  28290. pickingInfos.push(result);
  28291. }
  28292. return pickingInfos;
  28293. };
  28294. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28295. if (!BABYLON.PickingInfo) {
  28296. return null;
  28297. }
  28298. var pickingInfo = null;
  28299. if (!camera) {
  28300. if (!this.activeCamera) {
  28301. return null;
  28302. }
  28303. camera = this.activeCamera;
  28304. }
  28305. if (this.spriteManagers.length > 0) {
  28306. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28307. var spriteManager = this.spriteManagers[spriteIndex];
  28308. if (!spriteManager.isPickable) {
  28309. continue;
  28310. }
  28311. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28312. if (!result || !result.hit)
  28313. continue;
  28314. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28315. continue;
  28316. pickingInfo = result;
  28317. if (fastCheck) {
  28318. break;
  28319. }
  28320. }
  28321. }
  28322. return pickingInfo || new BABYLON.PickingInfo();
  28323. };
  28324. /** Launch a ray to try to pick a mesh in the scene
  28325. * @param x position on screen
  28326. * @param y position on screen
  28327. * @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
  28328. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28329. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28330. * @returns a PickingInfo
  28331. */
  28332. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28333. var _this = this;
  28334. if (!BABYLON.PickingInfo) {
  28335. return null;
  28336. }
  28337. return this._internalPick(function (world) {
  28338. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28339. return _this._tempPickingRay;
  28340. }, predicate, fastCheck);
  28341. };
  28342. /** Launch a ray to try to pick a sprite in the scene
  28343. * @param x position on screen
  28344. * @param y position on screen
  28345. * @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
  28346. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28347. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28348. * @returns a PickingInfo
  28349. */
  28350. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28351. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28352. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28353. };
  28354. /** Use the given ray to pick a mesh in the scene
  28355. * @param ray The ray to use to pick meshes
  28356. * @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
  28357. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28358. * @returns a PickingInfo
  28359. */
  28360. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28361. var _this = this;
  28362. return this._internalPick(function (world) {
  28363. if (!_this._pickWithRayInverseMatrix) {
  28364. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28365. }
  28366. world.invertToRef(_this._pickWithRayInverseMatrix);
  28367. if (!_this._cachedRayForTransform) {
  28368. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28369. }
  28370. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28371. return _this._cachedRayForTransform;
  28372. }, predicate, fastCheck);
  28373. };
  28374. /**
  28375. * Launch a ray to try to pick a mesh in the scene
  28376. * @param x X position on screen
  28377. * @param y Y position on screen
  28378. * @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
  28379. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28380. * @returns an array of PickingInfo
  28381. */
  28382. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28383. var _this = this;
  28384. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28385. };
  28386. /**
  28387. * Launch a ray to try to pick a mesh in the scene
  28388. * @param ray Ray to use
  28389. * @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
  28390. * @returns an array of PickingInfo
  28391. */
  28392. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28393. var _this = this;
  28394. return this._internalMultiPick(function (world) {
  28395. if (!_this._pickWithRayInverseMatrix) {
  28396. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28397. }
  28398. world.invertToRef(_this._pickWithRayInverseMatrix);
  28399. if (!_this._cachedRayForTransform) {
  28400. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28401. }
  28402. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28403. return _this._cachedRayForTransform;
  28404. }, predicate);
  28405. };
  28406. /**
  28407. * Force the value of meshUnderPointer
  28408. * @param mesh defines the mesh to use
  28409. */
  28410. Scene.prototype.setPointerOverMesh = function (mesh) {
  28411. if (this._pointerOverMesh === mesh) {
  28412. return;
  28413. }
  28414. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28415. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28416. }
  28417. this._pointerOverMesh = mesh;
  28418. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28419. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28420. }
  28421. };
  28422. /**
  28423. * Gets the mesh under the pointer
  28424. * @returns a Mesh or null if no mesh is under the pointer
  28425. */
  28426. Scene.prototype.getPointerOverMesh = function () {
  28427. return this._pointerOverMesh;
  28428. };
  28429. /**
  28430. * Force the sprite under the pointer
  28431. * @param sprite defines the sprite to use
  28432. */
  28433. Scene.prototype.setPointerOverSprite = function (sprite) {
  28434. if (this._pointerOverSprite === sprite) {
  28435. return;
  28436. }
  28437. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28438. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28439. }
  28440. this._pointerOverSprite = sprite;
  28441. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28442. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28443. }
  28444. };
  28445. /**
  28446. * Gets the sprite under the pointer
  28447. * @returns a Sprite or null if no sprite is under the pointer
  28448. */
  28449. Scene.prototype.getPointerOverSprite = function () {
  28450. return this._pointerOverSprite;
  28451. };
  28452. // Physics
  28453. /**
  28454. * Gets the current physics engine
  28455. * @returns a PhysicsEngine or null if none attached
  28456. */
  28457. Scene.prototype.getPhysicsEngine = function () {
  28458. return this._physicsEngine;
  28459. };
  28460. /**
  28461. * Enables physics to the current scene
  28462. * @param gravity defines the scene's gravity for the physics engine
  28463. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28464. * @return a boolean indicating if the physics engine was initialized
  28465. */
  28466. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28467. if (gravity === void 0) { gravity = null; }
  28468. if (this._physicsEngine) {
  28469. return true;
  28470. }
  28471. try {
  28472. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28473. return true;
  28474. }
  28475. catch (e) {
  28476. BABYLON.Tools.Error(e.message);
  28477. return false;
  28478. }
  28479. };
  28480. /**
  28481. * Disables and disposes the physics engine associated with the scene
  28482. */
  28483. Scene.prototype.disablePhysicsEngine = function () {
  28484. if (!this._physicsEngine) {
  28485. return;
  28486. }
  28487. this._physicsEngine.dispose();
  28488. this._physicsEngine = null;
  28489. };
  28490. /**
  28491. * Gets a boolean indicating if there is an active physics engine
  28492. * @returns a boolean indicating if there is an active physics engine
  28493. */
  28494. Scene.prototype.isPhysicsEnabled = function () {
  28495. return this._physicsEngine !== undefined;
  28496. };
  28497. /**
  28498. * Deletes a physics compound impostor
  28499. * @param compound defines the compound to delete
  28500. */
  28501. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28502. var mesh = compound.parts[0].mesh;
  28503. if (mesh.physicsImpostor) {
  28504. mesh.physicsImpostor.dispose( /*true*/);
  28505. mesh.physicsImpostor = null;
  28506. }
  28507. };
  28508. // Misc.
  28509. /** @hidden */
  28510. Scene.prototype._rebuildGeometries = function () {
  28511. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28512. var geometry = _a[_i];
  28513. geometry._rebuild();
  28514. }
  28515. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28516. var mesh = _c[_b];
  28517. mesh._rebuild();
  28518. }
  28519. if (this.postProcessManager) {
  28520. this.postProcessManager._rebuild();
  28521. }
  28522. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28523. var layer = _e[_d];
  28524. layer._rebuild();
  28525. }
  28526. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28527. var effectLayer = _g[_f];
  28528. effectLayer._rebuild();
  28529. }
  28530. if (this._boundingBoxRenderer) {
  28531. this._boundingBoxRenderer._rebuild();
  28532. }
  28533. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28534. var system = _j[_h];
  28535. system.rebuild();
  28536. }
  28537. if (this._postProcessRenderPipelineManager) {
  28538. this._postProcessRenderPipelineManager._rebuild();
  28539. }
  28540. };
  28541. /** @hidden */
  28542. Scene.prototype._rebuildTextures = function () {
  28543. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28544. var texture = _a[_i];
  28545. texture._rebuild();
  28546. }
  28547. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28548. };
  28549. /**
  28550. * Creates a default light for the scene.
  28551. * @param replace Whether to replace the existing lights in the scene.
  28552. */
  28553. Scene.prototype.createDefaultLight = function (replace) {
  28554. if (replace === void 0) { replace = false; }
  28555. // Dispose existing light in replace mode.
  28556. if (replace) {
  28557. if (this.lights) {
  28558. for (var i = 0; i < this.lights.length; i++) {
  28559. this.lights[i].dispose();
  28560. }
  28561. }
  28562. }
  28563. // Light
  28564. if (this.lights.length === 0) {
  28565. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28566. }
  28567. };
  28568. /**
  28569. * Creates a default camera for the scene.
  28570. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28571. * @param replace Whether to replace the existing active camera in the scene.
  28572. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28573. */
  28574. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28575. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28576. if (replace === void 0) { replace = false; }
  28577. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28578. // Dispose existing camera in replace mode.
  28579. if (replace) {
  28580. if (this.activeCamera) {
  28581. this.activeCamera.dispose();
  28582. this.activeCamera = null;
  28583. }
  28584. }
  28585. // Camera
  28586. if (!this.activeCamera) {
  28587. var worldExtends = this.getWorldExtends();
  28588. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28589. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28590. var camera;
  28591. var radius = worldSize.length() * 1.5;
  28592. // empty scene scenario!
  28593. if (!isFinite(radius)) {
  28594. radius = 1;
  28595. worldCenter.copyFromFloats(0, 0, 0);
  28596. }
  28597. if (createArcRotateCamera) {
  28598. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28599. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28600. arcRotateCamera.wheelPrecision = 100 / radius;
  28601. camera = arcRotateCamera;
  28602. }
  28603. else {
  28604. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28605. freeCamera.setTarget(worldCenter);
  28606. camera = freeCamera;
  28607. }
  28608. camera.minZ = radius * 0.01;
  28609. camera.maxZ = radius * 1000;
  28610. camera.speed = radius * 0.2;
  28611. this.activeCamera = camera;
  28612. var canvas = this.getEngine().getRenderingCanvas();
  28613. if (attachCameraControls && canvas) {
  28614. camera.attachControl(canvas);
  28615. }
  28616. }
  28617. };
  28618. /**
  28619. * Creates a default camera and a default light
  28620. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28621. * @param replace defines if the camera and/or light will replace the existing ones
  28622. * @param attachCameraControls defines if attachControl will be called on the new camera
  28623. */
  28624. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28625. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28626. if (replace === void 0) { replace = false; }
  28627. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28628. this.createDefaultLight(replace);
  28629. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28630. };
  28631. /**
  28632. * Creates a new sky box
  28633. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28634. * @param environmentTexture defines the texture to use as environment texture
  28635. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28636. * @param scale defines the overall scale of the skybox
  28637. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28638. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28639. * @returns a new mesh holding the sky box
  28640. */
  28641. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28642. if (pbr === void 0) { pbr = false; }
  28643. if (scale === void 0) { scale = 1000; }
  28644. if (blur === void 0) { blur = 0; }
  28645. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28646. if (!environmentTexture) {
  28647. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28648. return null;
  28649. }
  28650. if (setGlobalEnvTexture) {
  28651. if (environmentTexture) {
  28652. this.environmentTexture = environmentTexture;
  28653. }
  28654. }
  28655. // Skybox
  28656. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28657. if (pbr) {
  28658. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28659. hdrSkyboxMaterial.backFaceCulling = false;
  28660. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28661. if (hdrSkyboxMaterial.reflectionTexture) {
  28662. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28663. }
  28664. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28665. hdrSkyboxMaterial.disableLighting = true;
  28666. hdrSkyboxMaterial.twoSidedLighting = true;
  28667. hdrSkybox.infiniteDistance = true;
  28668. hdrSkybox.material = hdrSkyboxMaterial;
  28669. }
  28670. else {
  28671. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28672. skyboxMaterial.backFaceCulling = false;
  28673. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28674. if (skyboxMaterial.reflectionTexture) {
  28675. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28676. }
  28677. skyboxMaterial.disableLighting = true;
  28678. hdrSkybox.infiniteDistance = true;
  28679. hdrSkybox.material = skyboxMaterial;
  28680. }
  28681. return hdrSkybox;
  28682. };
  28683. /**
  28684. * Creates a new environment
  28685. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28686. * @param options defines the options you can use to configure the environment
  28687. * @returns the new EnvironmentHelper
  28688. */
  28689. Scene.prototype.createDefaultEnvironment = function (options) {
  28690. if (BABYLON.EnvironmentHelper) {
  28691. return new BABYLON.EnvironmentHelper(options, this);
  28692. }
  28693. return null;
  28694. };
  28695. /**
  28696. * Creates a new VREXperienceHelper
  28697. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28698. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28699. * @returns a new VREXperienceHelper
  28700. */
  28701. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28702. if (webVROptions === void 0) { webVROptions = {}; }
  28703. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28704. };
  28705. // Tags
  28706. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28707. if (tagsQuery === undefined) {
  28708. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28709. return list;
  28710. }
  28711. var listByTags = [];
  28712. forEach = forEach || (function (item) { return; });
  28713. for (var i in list) {
  28714. var item = list[i];
  28715. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28716. listByTags.push(item);
  28717. forEach(item);
  28718. }
  28719. }
  28720. return listByTags;
  28721. };
  28722. /**
  28723. * Get a list of meshes by tags
  28724. * @param tagsQuery defines the tags query to use
  28725. * @param forEach defines a predicate used to filter results
  28726. * @returns an array of Mesh
  28727. */
  28728. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28729. return this._getByTags(this.meshes, tagsQuery, forEach);
  28730. };
  28731. /**
  28732. * Get a list of cameras by tags
  28733. * @param tagsQuery defines the tags query to use
  28734. * @param forEach defines a predicate used to filter results
  28735. * @returns an array of Camera
  28736. */
  28737. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28738. return this._getByTags(this.cameras, tagsQuery, forEach);
  28739. };
  28740. /**
  28741. * Get a list of lights by tags
  28742. * @param tagsQuery defines the tags query to use
  28743. * @param forEach defines a predicate used to filter results
  28744. * @returns an array of Light
  28745. */
  28746. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28747. return this._getByTags(this.lights, tagsQuery, forEach);
  28748. };
  28749. /**
  28750. * Get a list of materials by tags
  28751. * @param tagsQuery defines the tags query to use
  28752. * @param forEach defines a predicate used to filter results
  28753. * @returns an array of Material
  28754. */
  28755. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28756. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28757. };
  28758. /**
  28759. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28760. * This allowed control for front to back rendering or reversly depending of the special needs.
  28761. *
  28762. * @param renderingGroupId The rendering group id corresponding to its index
  28763. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28764. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28765. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28766. */
  28767. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28768. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28769. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28770. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28771. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28772. };
  28773. /**
  28774. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28775. *
  28776. * @param renderingGroupId The rendering group id corresponding to its index
  28777. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28778. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28779. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28780. */
  28781. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28782. if (depth === void 0) { depth = true; }
  28783. if (stencil === void 0) { stencil = true; }
  28784. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28785. };
  28786. /**
  28787. * Will flag all materials as dirty to trigger new shader compilation
  28788. * @param flag defines the flag used to specify which material part must be marked as dirty
  28789. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28790. */
  28791. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28792. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28793. var material = _a[_i];
  28794. if (predicate && !predicate(material)) {
  28795. continue;
  28796. }
  28797. material.markAsDirty(flag);
  28798. }
  28799. };
  28800. /** @hidden */
  28801. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28802. var _this = this;
  28803. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28804. this._activeRequests.push(request);
  28805. request.onCompleteObservable.add(function (request) {
  28806. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28807. });
  28808. return request;
  28809. };
  28810. /** @hidden */
  28811. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28812. var _this = this;
  28813. return new Promise(function (resolve, reject) {
  28814. _this._loadFile(url, function (data) {
  28815. resolve(data);
  28816. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28817. reject(exception);
  28818. });
  28819. });
  28820. };
  28821. // Statics
  28822. Scene._FOGMODE_NONE = 0;
  28823. Scene._FOGMODE_EXP = 1;
  28824. Scene._FOGMODE_EXP2 = 2;
  28825. Scene._FOGMODE_LINEAR = 3;
  28826. Scene._uniqueIdCounter = 0;
  28827. /**
  28828. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28829. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28830. */
  28831. Scene.MinDeltaTime = 1.0;
  28832. /**
  28833. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28834. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28835. */
  28836. Scene.MaxDeltaTime = 1000.0;
  28837. /** The distance in pixel that you have to move to prevent some events */
  28838. Scene.DragMovementThreshold = 10; // in pixels
  28839. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28840. Scene.LongPressDelay = 500; // in milliseconds
  28841. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28842. Scene.DoubleClickDelay = 300; // in milliseconds
  28843. /** If you need to check double click without raising a single click at first click, enable this flag */
  28844. Scene.ExclusiveDoubleClickMode = false;
  28845. return Scene;
  28846. }());
  28847. BABYLON.Scene = Scene;
  28848. })(BABYLON || (BABYLON = {}));
  28849. //# sourceMappingURL=babylon.scene.js.map
  28850. var BABYLON;
  28851. (function (BABYLON) {
  28852. /**
  28853. * Set of assets to keep when moving a scene into an asset container.
  28854. */
  28855. var KeepAssets = /** @class */ (function () {
  28856. function KeepAssets() {
  28857. /**
  28858. * Cameras to keep.
  28859. */
  28860. this.cameras = new Array();
  28861. /**
  28862. * Lights to keep.
  28863. */
  28864. this.lights = new Array();
  28865. /**
  28866. * Meshes to keep.
  28867. */
  28868. this.meshes = new Array();
  28869. /**
  28870. * Skeletons to keep.
  28871. */
  28872. this.skeletons = new Array();
  28873. /**
  28874. * ParticleSystems to keep.
  28875. */
  28876. this.particleSystems = new Array();
  28877. /**
  28878. * Animations to keep.
  28879. */
  28880. this.animations = new Array();
  28881. /**
  28882. * AnimationGroups to keep.
  28883. */
  28884. this.animationGroups = new Array();
  28885. /**
  28886. * MultiMaterials to keep.
  28887. */
  28888. this.multiMaterials = new Array();
  28889. /**
  28890. * Materials to keep.
  28891. */
  28892. this.materials = new Array();
  28893. /**
  28894. * MorphTargetManagers to keep.
  28895. */
  28896. this.morphTargetManagers = new Array();
  28897. /**
  28898. * Geometries to keep.
  28899. */
  28900. this.geometries = new Array();
  28901. /**
  28902. * TransformNodes to keep.
  28903. */
  28904. this.transformNodes = new Array();
  28905. /**
  28906. * LensFlareSystems to keep.
  28907. */
  28908. this.lensFlareSystems = new Array();
  28909. /**
  28910. * ShadowGenerators to keep.
  28911. */
  28912. this.shadowGenerators = new Array();
  28913. /**
  28914. * ActionManagers to keep.
  28915. */
  28916. this.actionManagers = new Array();
  28917. /**
  28918. * Sounds to keep.
  28919. */
  28920. this.sounds = new Array();
  28921. /**
  28922. * Textures to keep.
  28923. */
  28924. this.textures = new Array();
  28925. /**
  28926. * Effect layers to keep.
  28927. */
  28928. this.effectLayers = new Array();
  28929. }
  28930. return KeepAssets;
  28931. }());
  28932. BABYLON.KeepAssets = KeepAssets;
  28933. /**
  28934. * Container with a set of assets that can be added or removed from a scene.
  28935. */
  28936. var AssetContainer = /** @class */ (function () {
  28937. /**
  28938. * Instantiates an AssetContainer.
  28939. * @param scene The scene the AssetContainer belongs to.
  28940. */
  28941. function AssetContainer(scene) {
  28942. // Objects
  28943. /**
  28944. * Cameras populated in the container.
  28945. */
  28946. this.cameras = new Array();
  28947. /**
  28948. * Lights populated in the container.
  28949. */
  28950. this.lights = new Array();
  28951. /**
  28952. * Meshes populated in the container.
  28953. */
  28954. this.meshes = new Array();
  28955. /**
  28956. * Skeletons populated in the container.
  28957. */
  28958. this.skeletons = new Array();
  28959. /**
  28960. * ParticleSystems populated in the container.
  28961. */
  28962. this.particleSystems = new Array();
  28963. /**
  28964. * Animations populated in the container.
  28965. */
  28966. this.animations = new Array();
  28967. /**
  28968. * AnimationGroups populated in the container.
  28969. */
  28970. this.animationGroups = new Array();
  28971. /**
  28972. * MultiMaterials populated in the container.
  28973. */
  28974. this.multiMaterials = new Array();
  28975. /**
  28976. * Materials populated in the container.
  28977. */
  28978. this.materials = new Array();
  28979. /**
  28980. * MorphTargetManagers populated in the container.
  28981. */
  28982. this.morphTargetManagers = new Array();
  28983. /**
  28984. * Geometries populated in the container.
  28985. */
  28986. this.geometries = new Array();
  28987. /**
  28988. * TransformNodes populated in the container.
  28989. */
  28990. this.transformNodes = new Array();
  28991. /**
  28992. * LensFlareSystems populated in the container.
  28993. */
  28994. this.lensFlareSystems = new Array();
  28995. /**
  28996. * ShadowGenerators populated in the container.
  28997. */
  28998. this.shadowGenerators = new Array();
  28999. /**
  29000. * ActionManagers populated in the container.
  29001. */
  29002. this.actionManagers = new Array();
  29003. /**
  29004. * Sounds populated in the container.
  29005. */
  29006. this.sounds = new Array();
  29007. /**
  29008. * Textures populated in the container.
  29009. */
  29010. this.textures = new Array();
  29011. /**
  29012. * Effect layers populated in the container.
  29013. */
  29014. this.effectLayers = new Array();
  29015. this.scene = scene;
  29016. }
  29017. /**
  29018. * Adds all the assets from the container to the scene.
  29019. */
  29020. AssetContainer.prototype.addAllToScene = function () {
  29021. var _this = this;
  29022. this.cameras.forEach(function (o) {
  29023. _this.scene.addCamera(o);
  29024. });
  29025. this.lights.forEach(function (o) {
  29026. _this.scene.addLight(o);
  29027. });
  29028. this.meshes.forEach(function (o) {
  29029. _this.scene.addMesh(o);
  29030. });
  29031. this.skeletons.forEach(function (o) {
  29032. _this.scene.addSkeleton(o);
  29033. });
  29034. this.particleSystems.forEach(function (o) {
  29035. _this.scene.addParticleSystem(o);
  29036. });
  29037. this.animations.forEach(function (o) {
  29038. _this.scene.addAnimation(o);
  29039. });
  29040. this.animationGroups.forEach(function (o) {
  29041. _this.scene.addAnimationGroup(o);
  29042. });
  29043. this.multiMaterials.forEach(function (o) {
  29044. _this.scene.addMultiMaterial(o);
  29045. });
  29046. this.materials.forEach(function (o) {
  29047. _this.scene.addMaterial(o);
  29048. });
  29049. this.morphTargetManagers.forEach(function (o) {
  29050. _this.scene.addMorphTargetManager(o);
  29051. });
  29052. this.geometries.forEach(function (o) {
  29053. _this.scene.addGeometry(o);
  29054. });
  29055. this.transformNodes.forEach(function (o) {
  29056. _this.scene.addTransformNode(o);
  29057. });
  29058. this.lensFlareSystems.forEach(function (o) {
  29059. _this.scene.addLensFlareSystem(o);
  29060. });
  29061. this.actionManagers.forEach(function (o) {
  29062. _this.scene.addActionManager(o);
  29063. });
  29064. this.sounds.forEach(function (o) {
  29065. o.play();
  29066. o.autoplay = true;
  29067. _this.scene.mainSoundTrack.AddSound(o);
  29068. });
  29069. this.textures.forEach(function (o) {
  29070. _this.scene.addTexture(o);
  29071. });
  29072. this.effectLayers.forEach(function (o) {
  29073. _this.scene.addEffectLayer(o);
  29074. });
  29075. };
  29076. /**
  29077. * Removes all the assets in the container from the scene
  29078. */
  29079. AssetContainer.prototype.removeAllFromScene = function () {
  29080. var _this = this;
  29081. this.cameras.forEach(function (o) {
  29082. _this.scene.removeCamera(o);
  29083. });
  29084. this.lights.forEach(function (o) {
  29085. _this.scene.removeLight(o);
  29086. });
  29087. this.meshes.forEach(function (o) {
  29088. _this.scene.removeMesh(o);
  29089. });
  29090. this.skeletons.forEach(function (o) {
  29091. _this.scene.removeSkeleton(o);
  29092. });
  29093. this.particleSystems.forEach(function (o) {
  29094. _this.scene.removeParticleSystem(o);
  29095. });
  29096. this.animations.forEach(function (o) {
  29097. _this.scene.removeAnimation(o);
  29098. });
  29099. this.animationGroups.forEach(function (o) {
  29100. _this.scene.removeAnimationGroup(o);
  29101. });
  29102. this.multiMaterials.forEach(function (o) {
  29103. _this.scene.removeMultiMaterial(o);
  29104. });
  29105. this.materials.forEach(function (o) {
  29106. _this.scene.removeMaterial(o);
  29107. });
  29108. this.morphTargetManagers.forEach(function (o) {
  29109. _this.scene.removeMorphTargetManager(o);
  29110. });
  29111. this.geometries.forEach(function (o) {
  29112. _this.scene.removeGeometry(o);
  29113. });
  29114. this.transformNodes.forEach(function (o) {
  29115. _this.scene.removeTransformNode(o);
  29116. });
  29117. this.lensFlareSystems.forEach(function (o) {
  29118. _this.scene.removeLensFlareSystem(o);
  29119. });
  29120. this.actionManagers.forEach(function (o) {
  29121. _this.scene.removeActionManager(o);
  29122. });
  29123. this.sounds.forEach(function (o) {
  29124. o.stop();
  29125. o.autoplay = false;
  29126. _this.scene.mainSoundTrack.RemoveSound(o);
  29127. });
  29128. this.textures.forEach(function (o) {
  29129. _this.scene.removeTexture(o);
  29130. });
  29131. this.effectLayers.forEach(function (o) {
  29132. _this.scene.removeEffectLayer(o);
  29133. });
  29134. };
  29135. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29136. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29137. var asset = sourceAssets_1[_i];
  29138. var move = true;
  29139. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29140. var keepAsset = keepAssets_1[_a];
  29141. if (asset === keepAsset) {
  29142. move = false;
  29143. break;
  29144. }
  29145. }
  29146. if (move) {
  29147. targetAssets.push(asset);
  29148. }
  29149. }
  29150. };
  29151. /**
  29152. * Removes all the assets contained in the scene and adds them to the container.
  29153. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29154. */
  29155. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29156. if (keepAssets === undefined) {
  29157. keepAssets = new KeepAssets();
  29158. }
  29159. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29160. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29161. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29162. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29163. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29164. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29165. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29166. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29167. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29168. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29169. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29170. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29171. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29172. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29173. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29174. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29175. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29176. this.removeAllFromScene();
  29177. };
  29178. return AssetContainer;
  29179. }());
  29180. BABYLON.AssetContainer = AssetContainer;
  29181. })(BABYLON || (BABYLON = {}));
  29182. //# sourceMappingURL=babylon.assetContainer.js.map
  29183. var BABYLON;
  29184. (function (BABYLON) {
  29185. var Buffer = /** @class */ (function () {
  29186. /**
  29187. * Constructor
  29188. * @param engine the engine
  29189. * @param data the data to use for this buffer
  29190. * @param updatable whether the data is updatable
  29191. * @param stride the stride (optional)
  29192. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29193. * @param instanced whether the buffer is instanced (optional)
  29194. * @param useBytes set to true if the stride in in bytes (optional)
  29195. */
  29196. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29197. if (stride === void 0) { stride = 0; }
  29198. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29199. if (instanced === void 0) { instanced = false; }
  29200. if (useBytes === void 0) { useBytes = false; }
  29201. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29202. this._engine = engine.getScene().getEngine();
  29203. }
  29204. else {
  29205. this._engine = engine;
  29206. }
  29207. this._updatable = updatable;
  29208. this._instanced = instanced;
  29209. this._data = data;
  29210. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29211. if (!postponeInternalCreation) { // by default
  29212. this.create();
  29213. }
  29214. }
  29215. /**
  29216. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29217. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29218. * @param offset defines offset in the buffer (0 by default)
  29219. * @param size defines the size in floats of attributes (position is 3 for instance)
  29220. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29221. * @param instanced defines if the vertex buffer contains indexed data
  29222. * @param useBytes defines if the offset and stride are in bytes
  29223. * @returns the new vertex buffer
  29224. */
  29225. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29226. if (useBytes === void 0) { useBytes = false; }
  29227. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29228. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29229. // a lot of these parameters are ignored as they are overriden by the buffer
  29230. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29231. };
  29232. // Properties
  29233. Buffer.prototype.isUpdatable = function () {
  29234. return this._updatable;
  29235. };
  29236. Buffer.prototype.getData = function () {
  29237. return this._data;
  29238. };
  29239. Buffer.prototype.getBuffer = function () {
  29240. return this._buffer;
  29241. };
  29242. /**
  29243. * Gets the stride in float32 units (i.e. byte stride / 4).
  29244. * May not be an integer if the byte stride is not divisible by 4.
  29245. * DEPRECATED. Use byteStride instead.
  29246. * @returns the stride in float32 units
  29247. */
  29248. Buffer.prototype.getStrideSize = function () {
  29249. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29250. };
  29251. // Methods
  29252. Buffer.prototype.create = function (data) {
  29253. if (data === void 0) { data = null; }
  29254. if (!data && this._buffer) {
  29255. return; // nothing to do
  29256. }
  29257. data = data || this._data;
  29258. if (!data) {
  29259. return;
  29260. }
  29261. if (!this._buffer) { // create buffer
  29262. if (this._updatable) {
  29263. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29264. this._data = data;
  29265. }
  29266. else {
  29267. this._buffer = this._engine.createVertexBuffer(data);
  29268. }
  29269. }
  29270. else if (this._updatable) { // update buffer
  29271. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29272. this._data = data;
  29273. }
  29274. };
  29275. Buffer.prototype._rebuild = function () {
  29276. this._buffer = null;
  29277. this.create(this._data);
  29278. };
  29279. Buffer.prototype.update = function (data) {
  29280. this.create(data);
  29281. };
  29282. /**
  29283. * Updates the data directly.
  29284. * @param data the new data
  29285. * @param offset the new offset
  29286. * @param vertexCount the vertex count (optional)
  29287. * @param useBytes set to true if the offset is in bytes
  29288. */
  29289. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29290. if (useBytes === void 0) { useBytes = false; }
  29291. if (!this._buffer) {
  29292. return;
  29293. }
  29294. if (this._updatable) { // update buffer
  29295. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29296. this._data = null;
  29297. }
  29298. };
  29299. Buffer.prototype.dispose = function () {
  29300. if (!this._buffer) {
  29301. return;
  29302. }
  29303. if (this._engine._releaseBuffer(this._buffer)) {
  29304. this._buffer = null;
  29305. }
  29306. };
  29307. return Buffer;
  29308. }());
  29309. BABYLON.Buffer = Buffer;
  29310. })(BABYLON || (BABYLON = {}));
  29311. //# sourceMappingURL=babylon.buffer.js.map
  29312. var BABYLON;
  29313. (function (BABYLON) {
  29314. var VertexBuffer = /** @class */ (function () {
  29315. /**
  29316. * Constructor
  29317. * @param engine the engine
  29318. * @param data the data to use for this vertex buffer
  29319. * @param kind the vertex buffer kind
  29320. * @param updatable whether the data is updatable
  29321. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29322. * @param stride the stride (optional)
  29323. * @param instanced whether the buffer is instanced (optional)
  29324. * @param offset the offset of the data (optional)
  29325. * @param size the number of components (optional)
  29326. * @param type the type of the component (optional)
  29327. * @param normalized whether the data contains normalized data (optional)
  29328. * @param useBytes set to true if stride and offset are in bytes (optional)
  29329. */
  29330. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29331. if (normalized === void 0) { normalized = false; }
  29332. if (useBytes === void 0) { useBytes = false; }
  29333. if (data instanceof BABYLON.Buffer) {
  29334. this._buffer = data;
  29335. this._ownsBuffer = false;
  29336. }
  29337. else {
  29338. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29339. this._ownsBuffer = true;
  29340. }
  29341. this._kind = kind;
  29342. if (type == undefined) {
  29343. var data_1 = this.getData();
  29344. this.type = VertexBuffer.FLOAT;
  29345. if (data_1 instanceof Int8Array)
  29346. this.type = VertexBuffer.BYTE;
  29347. else if (data_1 instanceof Uint8Array)
  29348. this.type = VertexBuffer.UNSIGNED_BYTE;
  29349. else if (data_1 instanceof Int16Array)
  29350. this.type = VertexBuffer.SHORT;
  29351. else if (data_1 instanceof Uint16Array)
  29352. this.type = VertexBuffer.UNSIGNED_SHORT;
  29353. else if (data_1 instanceof Int32Array)
  29354. this.type = VertexBuffer.INT;
  29355. else if (data_1 instanceof Uint32Array)
  29356. this.type = VertexBuffer.UNSIGNED_INT;
  29357. }
  29358. else {
  29359. this.type = type;
  29360. }
  29361. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29362. if (useBytes) {
  29363. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29364. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29365. this.byteOffset = offset || 0;
  29366. }
  29367. else {
  29368. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29369. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29370. this.byteOffset = (offset || 0) * typeByteLength;
  29371. }
  29372. this.normalized = normalized;
  29373. this._instanced = instanced !== undefined ? instanced : false;
  29374. this._instanceDivisor = instanced ? 1 : 0;
  29375. }
  29376. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29377. /**
  29378. * Gets or sets the instance divisor when in instanced mode
  29379. */
  29380. get: function () {
  29381. return this._instanceDivisor;
  29382. },
  29383. set: function (value) {
  29384. this._instanceDivisor = value;
  29385. if (value == 0) {
  29386. this._instanced = false;
  29387. }
  29388. else {
  29389. this._instanced = true;
  29390. }
  29391. },
  29392. enumerable: true,
  29393. configurable: true
  29394. });
  29395. VertexBuffer.prototype._rebuild = function () {
  29396. if (!this._buffer) {
  29397. return;
  29398. }
  29399. this._buffer._rebuild();
  29400. };
  29401. /**
  29402. * Returns the kind of the VertexBuffer (string).
  29403. */
  29404. VertexBuffer.prototype.getKind = function () {
  29405. return this._kind;
  29406. };
  29407. // Properties
  29408. /**
  29409. * Boolean : is the VertexBuffer updatable ?
  29410. */
  29411. VertexBuffer.prototype.isUpdatable = function () {
  29412. return this._buffer.isUpdatable();
  29413. };
  29414. /**
  29415. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29416. */
  29417. VertexBuffer.prototype.getData = function () {
  29418. return this._buffer.getData();
  29419. };
  29420. /**
  29421. * Returns the WebGLBuffer associated to the VertexBuffer.
  29422. */
  29423. VertexBuffer.prototype.getBuffer = function () {
  29424. return this._buffer.getBuffer();
  29425. };
  29426. /**
  29427. * Returns the stride as a multiple of the type byte length.
  29428. * DEPRECATED. Use byteStride instead.
  29429. */
  29430. VertexBuffer.prototype.getStrideSize = function () {
  29431. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29432. };
  29433. /**
  29434. * Returns the offset as a multiple of the type byte length.
  29435. * DEPRECATED. Use byteOffset instead.
  29436. */
  29437. VertexBuffer.prototype.getOffset = function () {
  29438. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29439. };
  29440. /**
  29441. * Returns the number of components per vertex attribute (integer).
  29442. */
  29443. VertexBuffer.prototype.getSize = function () {
  29444. return this._size;
  29445. };
  29446. /**
  29447. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29448. */
  29449. VertexBuffer.prototype.getIsInstanced = function () {
  29450. return this._instanced;
  29451. };
  29452. /**
  29453. * Returns the instancing divisor, zero for non-instanced (integer).
  29454. */
  29455. VertexBuffer.prototype.getInstanceDivisor = function () {
  29456. return this._instanceDivisor;
  29457. };
  29458. // Methods
  29459. /**
  29460. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29461. * Returns the created WebGLBuffer.
  29462. */
  29463. VertexBuffer.prototype.create = function (data) {
  29464. return this._buffer.create(data);
  29465. };
  29466. /**
  29467. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29468. * This function will create a new buffer if the current one is not updatable
  29469. * Returns the updated WebGLBuffer.
  29470. */
  29471. VertexBuffer.prototype.update = function (data) {
  29472. return this._buffer.update(data);
  29473. };
  29474. /**
  29475. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29476. * Returns the directly updated WebGLBuffer.
  29477. * @param data the new data
  29478. * @param offset the new offset
  29479. * @param useBytes set to true if the offset is in bytes
  29480. */
  29481. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29482. if (useBytes === void 0) { useBytes = false; }
  29483. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29484. };
  29485. /**
  29486. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29487. */
  29488. VertexBuffer.prototype.dispose = function () {
  29489. if (this._ownsBuffer) {
  29490. this._buffer.dispose();
  29491. }
  29492. };
  29493. /**
  29494. * Enumerates each value of this vertex buffer as numbers.
  29495. * @param count the number of values to enumerate
  29496. * @param callback the callback function called for each value
  29497. */
  29498. VertexBuffer.prototype.forEach = function (count, callback) {
  29499. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29500. };
  29501. Object.defineProperty(VertexBuffer, "PositionKind", {
  29502. get: function () {
  29503. return VertexBuffer._PositionKind;
  29504. },
  29505. enumerable: true,
  29506. configurable: true
  29507. });
  29508. Object.defineProperty(VertexBuffer, "NormalKind", {
  29509. get: function () {
  29510. return VertexBuffer._NormalKind;
  29511. },
  29512. enumerable: true,
  29513. configurable: true
  29514. });
  29515. Object.defineProperty(VertexBuffer, "TangentKind", {
  29516. get: function () {
  29517. return VertexBuffer._TangentKind;
  29518. },
  29519. enumerable: true,
  29520. configurable: true
  29521. });
  29522. Object.defineProperty(VertexBuffer, "UVKind", {
  29523. get: function () {
  29524. return VertexBuffer._UVKind;
  29525. },
  29526. enumerable: true,
  29527. configurable: true
  29528. });
  29529. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29530. get: function () {
  29531. return VertexBuffer._UV2Kind;
  29532. },
  29533. enumerable: true,
  29534. configurable: true
  29535. });
  29536. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29537. get: function () {
  29538. return VertexBuffer._UV3Kind;
  29539. },
  29540. enumerable: true,
  29541. configurable: true
  29542. });
  29543. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29544. get: function () {
  29545. return VertexBuffer._UV4Kind;
  29546. },
  29547. enumerable: true,
  29548. configurable: true
  29549. });
  29550. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29551. get: function () {
  29552. return VertexBuffer._UV5Kind;
  29553. },
  29554. enumerable: true,
  29555. configurable: true
  29556. });
  29557. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29558. get: function () {
  29559. return VertexBuffer._UV6Kind;
  29560. },
  29561. enumerable: true,
  29562. configurable: true
  29563. });
  29564. Object.defineProperty(VertexBuffer, "ColorKind", {
  29565. get: function () {
  29566. return VertexBuffer._ColorKind;
  29567. },
  29568. enumerable: true,
  29569. configurable: true
  29570. });
  29571. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29572. get: function () {
  29573. return VertexBuffer._MatricesIndicesKind;
  29574. },
  29575. enumerable: true,
  29576. configurable: true
  29577. });
  29578. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29579. get: function () {
  29580. return VertexBuffer._MatricesWeightsKind;
  29581. },
  29582. enumerable: true,
  29583. configurable: true
  29584. });
  29585. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29586. get: function () {
  29587. return VertexBuffer._MatricesIndicesExtraKind;
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29593. get: function () {
  29594. return VertexBuffer._MatricesWeightsExtraKind;
  29595. },
  29596. enumerable: true,
  29597. configurable: true
  29598. });
  29599. /**
  29600. * Deduces the stride given a kind.
  29601. * @param kind The kind string to deduce
  29602. * @returns The deduced stride
  29603. */
  29604. VertexBuffer.DeduceStride = function (kind) {
  29605. switch (kind) {
  29606. case VertexBuffer.UVKind:
  29607. case VertexBuffer.UV2Kind:
  29608. case VertexBuffer.UV3Kind:
  29609. case VertexBuffer.UV4Kind:
  29610. case VertexBuffer.UV5Kind:
  29611. case VertexBuffer.UV6Kind:
  29612. return 2;
  29613. case VertexBuffer.NormalKind:
  29614. case VertexBuffer.PositionKind:
  29615. return 3;
  29616. case VertexBuffer.ColorKind:
  29617. case VertexBuffer.MatricesIndicesKind:
  29618. case VertexBuffer.MatricesIndicesExtraKind:
  29619. case VertexBuffer.MatricesWeightsKind:
  29620. case VertexBuffer.MatricesWeightsExtraKind:
  29621. case VertexBuffer.TangentKind:
  29622. return 4;
  29623. default:
  29624. throw new Error("Invalid kind '" + kind + "'");
  29625. }
  29626. };
  29627. /**
  29628. * Gets the byte length of the given type.
  29629. * @param type the type
  29630. * @returns the number of bytes
  29631. */
  29632. VertexBuffer.GetTypeByteLength = function (type) {
  29633. switch (type) {
  29634. case VertexBuffer.BYTE:
  29635. case VertexBuffer.UNSIGNED_BYTE:
  29636. return 1;
  29637. case VertexBuffer.SHORT:
  29638. case VertexBuffer.UNSIGNED_SHORT:
  29639. return 2;
  29640. case VertexBuffer.INT:
  29641. case VertexBuffer.FLOAT:
  29642. return 4;
  29643. default:
  29644. throw new Error("Invalid type '" + type + "'");
  29645. }
  29646. };
  29647. /**
  29648. * Enumerates each value of the given parameters as numbers.
  29649. * @param data the data to enumerate
  29650. * @param byteOffset the byte offset of the data
  29651. * @param byteStride the byte stride of the data
  29652. * @param componentCount the number of components per element
  29653. * @param componentType the type of the component
  29654. * @param count the total number of components
  29655. * @param normalized whether the data is normalized
  29656. * @param callback the callback function called for each value
  29657. */
  29658. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29659. if (data instanceof Array) {
  29660. var offset = byteOffset / 4;
  29661. var stride = byteStride / 4;
  29662. for (var index = 0; index < count; index += componentCount) {
  29663. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29664. callback(data[offset + componentIndex], index + componentIndex);
  29665. }
  29666. offset += stride;
  29667. }
  29668. }
  29669. else {
  29670. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29671. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29672. for (var index = 0; index < count; index += componentCount) {
  29673. var componentByteOffset = byteOffset;
  29674. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29675. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29676. callback(value, index + componentIndex);
  29677. componentByteOffset += componentByteLength;
  29678. }
  29679. byteOffset += byteStride;
  29680. }
  29681. }
  29682. };
  29683. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29684. switch (type) {
  29685. case VertexBuffer.BYTE: {
  29686. var value = dataView.getInt8(byteOffset);
  29687. if (normalized) {
  29688. value = Math.max(value / 127, -1);
  29689. }
  29690. return value;
  29691. }
  29692. case VertexBuffer.UNSIGNED_BYTE: {
  29693. var value = dataView.getUint8(byteOffset);
  29694. if (normalized) {
  29695. value = value / 255;
  29696. }
  29697. return value;
  29698. }
  29699. case VertexBuffer.SHORT: {
  29700. var value = dataView.getInt16(byteOffset, true);
  29701. if (normalized) {
  29702. value = Math.max(value / 16383, -1);
  29703. }
  29704. return value;
  29705. }
  29706. case VertexBuffer.UNSIGNED_SHORT: {
  29707. var value = dataView.getUint16(byteOffset, true);
  29708. if (normalized) {
  29709. value = value / 65535;
  29710. }
  29711. return value;
  29712. }
  29713. case VertexBuffer.FLOAT: {
  29714. return dataView.getFloat32(byteOffset, true);
  29715. }
  29716. default: {
  29717. throw new Error("Invalid component type " + type);
  29718. }
  29719. }
  29720. };
  29721. /**
  29722. * The byte type.
  29723. */
  29724. VertexBuffer.BYTE = 5120;
  29725. /**
  29726. * The unsigned byte type.
  29727. */
  29728. VertexBuffer.UNSIGNED_BYTE = 5121;
  29729. /**
  29730. * The short type.
  29731. */
  29732. VertexBuffer.SHORT = 5122;
  29733. /**
  29734. * The unsigned short type.
  29735. */
  29736. VertexBuffer.UNSIGNED_SHORT = 5123;
  29737. /**
  29738. * The integer type.
  29739. */
  29740. VertexBuffer.INT = 5124;
  29741. /**
  29742. * The unsigned integer type.
  29743. */
  29744. VertexBuffer.UNSIGNED_INT = 5125;
  29745. /**
  29746. * The float type.
  29747. */
  29748. VertexBuffer.FLOAT = 5126;
  29749. // Enums
  29750. VertexBuffer._PositionKind = "position";
  29751. VertexBuffer._NormalKind = "normal";
  29752. VertexBuffer._TangentKind = "tangent";
  29753. VertexBuffer._UVKind = "uv";
  29754. VertexBuffer._UV2Kind = "uv2";
  29755. VertexBuffer._UV3Kind = "uv3";
  29756. VertexBuffer._UV4Kind = "uv4";
  29757. VertexBuffer._UV5Kind = "uv5";
  29758. VertexBuffer._UV6Kind = "uv6";
  29759. VertexBuffer._ColorKind = "color";
  29760. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29761. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29762. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29763. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29764. return VertexBuffer;
  29765. }());
  29766. BABYLON.VertexBuffer = VertexBuffer;
  29767. })(BABYLON || (BABYLON = {}));
  29768. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29769. var BABYLON;
  29770. (function (BABYLON) {
  29771. /**
  29772. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29773. */
  29774. var DummyInternalTextureTracker = /** @class */ (function () {
  29775. function DummyInternalTextureTracker() {
  29776. /**
  29777. * Gets or set the previous tracker in the list
  29778. */
  29779. this.previous = null;
  29780. /**
  29781. * Gets or set the next tracker in the list
  29782. */
  29783. this.next = null;
  29784. }
  29785. return DummyInternalTextureTracker;
  29786. }());
  29787. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29788. })(BABYLON || (BABYLON = {}));
  29789. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29790. var BABYLON;
  29791. (function (BABYLON) {
  29792. /**
  29793. * Class used to store data associated with WebGL texture data for the engine
  29794. * This class should not be used directly
  29795. */
  29796. var InternalTexture = /** @class */ (function () {
  29797. /**
  29798. * Creates a new InternalTexture
  29799. * @param engine defines the engine to use
  29800. * @param dataSource defines the type of data that will be used
  29801. */
  29802. function InternalTexture(engine, dataSource) {
  29803. /**
  29804. * Observable called when the texture is loaded
  29805. */
  29806. this.onLoadedObservable = new BABYLON.Observable();
  29807. /**
  29808. * Gets or set the previous tracker in the list
  29809. */
  29810. this.previous = null;
  29811. /**
  29812. * Gets or set the next tracker in the list
  29813. */
  29814. this.next = null;
  29815. // Private
  29816. /** @hidden */
  29817. this._initialSlot = -1;
  29818. /** @hidden */
  29819. this._designatedSlot = -1;
  29820. /** @hidden */
  29821. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29822. /** @hidden */
  29823. this._comparisonFunction = 0;
  29824. /** @hidden */
  29825. this._references = 1;
  29826. this._engine = engine;
  29827. this._dataSource = dataSource;
  29828. this._webGLTexture = engine._createTexture();
  29829. }
  29830. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29831. /**
  29832. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29833. */
  29834. get: function () {
  29835. return this._dataSource;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. /**
  29841. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29842. */
  29843. InternalTexture.prototype.incrementReferences = function () {
  29844. this._references++;
  29845. };
  29846. /**
  29847. * Change the size of the texture (not the size of the content)
  29848. * @param width defines the new width
  29849. * @param height defines the new height
  29850. * @param depth defines the new depth (1 by default)
  29851. */
  29852. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29853. if (depth === void 0) { depth = 1; }
  29854. this.width = width;
  29855. this.height = height;
  29856. this.depth = depth;
  29857. this.baseWidth = width;
  29858. this.baseHeight = height;
  29859. this.baseDepth = depth;
  29860. this._size = width * height * depth;
  29861. };
  29862. /** @hidden */
  29863. InternalTexture.prototype._rebuild = function () {
  29864. var _this = this;
  29865. var proxy;
  29866. this.isReady = false;
  29867. this._cachedCoordinatesMode = null;
  29868. this._cachedWrapU = null;
  29869. this._cachedWrapV = null;
  29870. this._cachedAnisotropicFilteringLevel = null;
  29871. switch (this._dataSource) {
  29872. case InternalTexture.DATASOURCE_TEMP:
  29873. return;
  29874. case InternalTexture.DATASOURCE_URL:
  29875. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29876. _this.isReady = true;
  29877. }, null, this._buffer, undefined, this.format);
  29878. proxy._swapAndDie(this);
  29879. return;
  29880. case InternalTexture.DATASOURCE_RAW:
  29881. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29882. proxy._swapAndDie(this);
  29883. this.isReady = true;
  29884. return;
  29885. case InternalTexture.DATASOURCE_RAW3D:
  29886. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29887. proxy._swapAndDie(this);
  29888. this.isReady = true;
  29889. return;
  29890. case InternalTexture.DATASOURCE_DYNAMIC:
  29891. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29892. proxy._swapAndDie(this);
  29893. // The engine will make sure to update content so no need to flag it as isReady = true
  29894. return;
  29895. case InternalTexture.DATASOURCE_RENDERTARGET:
  29896. var options = new BABYLON.RenderTargetCreationOptions();
  29897. options.generateDepthBuffer = this._generateDepthBuffer;
  29898. options.generateMipMaps = this.generateMipMaps;
  29899. options.generateStencilBuffer = this._generateStencilBuffer;
  29900. options.samplingMode = this.samplingMode;
  29901. options.type = this.type;
  29902. if (this.isCube) {
  29903. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29904. }
  29905. else {
  29906. var size = {
  29907. width: this.width,
  29908. height: this.height
  29909. };
  29910. proxy = this._engine.createRenderTargetTexture(size, options);
  29911. }
  29912. proxy._swapAndDie(this);
  29913. this.isReady = true;
  29914. return;
  29915. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29916. var depthTextureOptions = {
  29917. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29918. comparisonFunction: this._comparisonFunction,
  29919. generateStencil: this._generateStencilBuffer,
  29920. isCube: this.isCube
  29921. };
  29922. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29923. proxy._swapAndDie(this);
  29924. this.isReady = true;
  29925. return;
  29926. case InternalTexture.DATASOURCE_CUBE:
  29927. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29928. _this.isReady = true;
  29929. }, null, this.format, this._extension);
  29930. proxy._swapAndDie(this);
  29931. return;
  29932. case InternalTexture.DATASOURCE_CUBERAW:
  29933. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29934. proxy._swapAndDie(this);
  29935. this.isReady = true;
  29936. return;
  29937. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29938. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29939. if (proxy) {
  29940. proxy._swapAndDie(_this);
  29941. }
  29942. _this.isReady = true;
  29943. }, null, this.format, this._extension);
  29944. return;
  29945. }
  29946. };
  29947. InternalTexture.prototype._swapAndDie = function (target) {
  29948. target._webGLTexture = this._webGLTexture;
  29949. if (this._framebuffer) {
  29950. target._framebuffer = this._framebuffer;
  29951. }
  29952. if (this._depthStencilBuffer) {
  29953. target._depthStencilBuffer = this._depthStencilBuffer;
  29954. }
  29955. if (this._lodTextureHigh) {
  29956. if (target._lodTextureHigh) {
  29957. target._lodTextureHigh.dispose();
  29958. }
  29959. target._lodTextureHigh = this._lodTextureHigh;
  29960. }
  29961. if (this._lodTextureMid) {
  29962. if (target._lodTextureMid) {
  29963. target._lodTextureMid.dispose();
  29964. }
  29965. target._lodTextureMid = this._lodTextureMid;
  29966. }
  29967. if (this._lodTextureLow) {
  29968. if (target._lodTextureLow) {
  29969. target._lodTextureLow.dispose();
  29970. }
  29971. target._lodTextureLow = this._lodTextureLow;
  29972. }
  29973. var cache = this._engine.getLoadedTexturesCache();
  29974. var index = cache.indexOf(this);
  29975. if (index !== -1) {
  29976. cache.splice(index, 1);
  29977. }
  29978. };
  29979. /**
  29980. * Dispose the current allocated resources
  29981. */
  29982. InternalTexture.prototype.dispose = function () {
  29983. if (!this._webGLTexture) {
  29984. return;
  29985. }
  29986. this._references--;
  29987. if (this._references === 0) {
  29988. this._engine._releaseTexture(this);
  29989. this._webGLTexture = null;
  29990. this.previous = null;
  29991. this.next = null;
  29992. }
  29993. };
  29994. /**
  29995. * The source of the texture data is unknown
  29996. */
  29997. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29998. /**
  29999. * Texture data comes from an URL
  30000. */
  30001. InternalTexture.DATASOURCE_URL = 1;
  30002. /**
  30003. * Texture data is only used for temporary storage
  30004. */
  30005. InternalTexture.DATASOURCE_TEMP = 2;
  30006. /**
  30007. * Texture data comes from raw data (ArrayBuffer)
  30008. */
  30009. InternalTexture.DATASOURCE_RAW = 3;
  30010. /**
  30011. * Texture content is dynamic (video or dynamic texture)
  30012. */
  30013. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30014. /**
  30015. * Texture content is generated by rendering to it
  30016. */
  30017. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30018. /**
  30019. * Texture content is part of a multi render target process
  30020. */
  30021. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30022. /**
  30023. * Texture data comes from a cube data file
  30024. */
  30025. InternalTexture.DATASOURCE_CUBE = 7;
  30026. /**
  30027. * Texture data comes from a raw cube data
  30028. */
  30029. InternalTexture.DATASOURCE_CUBERAW = 8;
  30030. /**
  30031. * Texture data come from a prefiltered cube data file
  30032. */
  30033. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30034. /**
  30035. * Texture content is raw 3D data
  30036. */
  30037. InternalTexture.DATASOURCE_RAW3D = 10;
  30038. /**
  30039. * Texture content is a depth texture
  30040. */
  30041. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30042. return InternalTexture;
  30043. }());
  30044. BABYLON.InternalTexture = InternalTexture;
  30045. })(BABYLON || (BABYLON = {}));
  30046. //# sourceMappingURL=babylon.internalTexture.js.map
  30047. var BABYLON;
  30048. (function (BABYLON) {
  30049. var BaseTexture = /** @class */ (function () {
  30050. function BaseTexture(scene) {
  30051. this._hasAlpha = false;
  30052. this.getAlphaFromRGB = false;
  30053. this.level = 1;
  30054. this.coordinatesIndex = 0;
  30055. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30056. /**
  30057. * | Value | Type | Description |
  30058. * | ----- | ------------------ | ----------- |
  30059. * | 0 | CLAMP_ADDRESSMODE | |
  30060. * | 1 | WRAP_ADDRESSMODE | |
  30061. * | 2 | MIRROR_ADDRESSMODE | |
  30062. */
  30063. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30064. /**
  30065. * | Value | Type | Description |
  30066. * | ----- | ------------------ | ----------- |
  30067. * | 0 | CLAMP_ADDRESSMODE | |
  30068. * | 1 | WRAP_ADDRESSMODE | |
  30069. * | 2 | MIRROR_ADDRESSMODE | |
  30070. */
  30071. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30072. /**
  30073. * | Value | Type | Description |
  30074. * | ----- | ------------------ | ----------- |
  30075. * | 0 | CLAMP_ADDRESSMODE | |
  30076. * | 1 | WRAP_ADDRESSMODE | |
  30077. * | 2 | MIRROR_ADDRESSMODE | |
  30078. */
  30079. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30080. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30081. this.isCube = false;
  30082. this.is3D = false;
  30083. this.gammaSpace = true;
  30084. this.invertZ = false;
  30085. this.lodLevelInAlpha = false;
  30086. this.lodGenerationOffset = 0.0;
  30087. this.lodGenerationScale = 0.8;
  30088. this.isRenderTarget = false;
  30089. this.animations = new Array();
  30090. /**
  30091. * An event triggered when the texture is disposed.
  30092. */
  30093. this.onDisposeObservable = new BABYLON.Observable();
  30094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30095. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30096. if (this._scene) {
  30097. this._scene.textures.push(this);
  30098. }
  30099. this._uid = null;
  30100. }
  30101. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30102. get: function () {
  30103. return this._hasAlpha;
  30104. },
  30105. set: function (value) {
  30106. if (this._hasAlpha === value) {
  30107. return;
  30108. }
  30109. this._hasAlpha = value;
  30110. if (this._scene) {
  30111. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30112. }
  30113. },
  30114. enumerable: true,
  30115. configurable: true
  30116. });
  30117. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30118. get: function () {
  30119. return this._coordinatesMode;
  30120. },
  30121. /**
  30122. * How a texture is mapped.
  30123. *
  30124. * | Value | Type | Description |
  30125. * | ----- | ----------------------------------- | ----------- |
  30126. * | 0 | EXPLICIT_MODE | |
  30127. * | 1 | SPHERICAL_MODE | |
  30128. * | 2 | PLANAR_MODE | |
  30129. * | 3 | CUBIC_MODE | |
  30130. * | 4 | PROJECTION_MODE | |
  30131. * | 5 | SKYBOX_MODE | |
  30132. * | 6 | INVCUBIC_MODE | |
  30133. * | 7 | EQUIRECTANGULAR_MODE | |
  30134. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30135. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30136. */
  30137. set: function (value) {
  30138. if (this._coordinatesMode === value) {
  30139. return;
  30140. }
  30141. this._coordinatesMode = value;
  30142. if (this._scene) {
  30143. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30144. }
  30145. },
  30146. enumerable: true,
  30147. configurable: true
  30148. });
  30149. Object.defineProperty(BaseTexture.prototype, "uid", {
  30150. get: function () {
  30151. if (!this._uid) {
  30152. this._uid = BABYLON.Tools.RandomId();
  30153. }
  30154. return this._uid;
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. BaseTexture.prototype.toString = function () {
  30160. return this.name;
  30161. };
  30162. BaseTexture.prototype.getClassName = function () {
  30163. return "BaseTexture";
  30164. };
  30165. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30166. set: function (callback) {
  30167. if (this._onDisposeObserver) {
  30168. this.onDisposeObservable.remove(this._onDisposeObserver);
  30169. }
  30170. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30171. },
  30172. enumerable: true,
  30173. configurable: true
  30174. });
  30175. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30176. get: function () {
  30177. return true;
  30178. },
  30179. enumerable: true,
  30180. configurable: true
  30181. });
  30182. BaseTexture.prototype.getScene = function () {
  30183. return this._scene;
  30184. };
  30185. BaseTexture.prototype.getTextureMatrix = function () {
  30186. return BABYLON.Matrix.IdentityReadOnly;
  30187. };
  30188. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30189. return BABYLON.Matrix.IdentityReadOnly;
  30190. };
  30191. BaseTexture.prototype.getInternalTexture = function () {
  30192. return this._texture;
  30193. };
  30194. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30195. return !this.isBlocking || this.isReady();
  30196. };
  30197. BaseTexture.prototype.isReady = function () {
  30198. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30199. this.delayLoad();
  30200. return false;
  30201. }
  30202. if (this._texture) {
  30203. return this._texture.isReady;
  30204. }
  30205. return false;
  30206. };
  30207. BaseTexture.prototype.getSize = function () {
  30208. if (this._texture && this._texture.width) {
  30209. return new BABYLON.Size(this._texture.width, this._texture.height);
  30210. }
  30211. if (this._texture && this._texture._size) {
  30212. return new BABYLON.Size(this._texture._size, this._texture._size);
  30213. }
  30214. return BABYLON.Size.Zero();
  30215. };
  30216. BaseTexture.prototype.getBaseSize = function () {
  30217. if (!this.isReady() || !this._texture)
  30218. return BABYLON.Size.Zero();
  30219. if (this._texture._size) {
  30220. return new BABYLON.Size(this._texture._size, this._texture._size);
  30221. }
  30222. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30223. };
  30224. BaseTexture.prototype.scale = function (ratio) {
  30225. };
  30226. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30227. get: function () {
  30228. return false;
  30229. },
  30230. enumerable: true,
  30231. configurable: true
  30232. });
  30233. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30234. if (!this._scene) {
  30235. return null;
  30236. }
  30237. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30238. for (var index = 0; index < texturesCache.length; index++) {
  30239. var texturesCacheEntry = texturesCache[index];
  30240. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30241. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30242. texturesCacheEntry.incrementReferences();
  30243. return texturesCacheEntry;
  30244. }
  30245. }
  30246. }
  30247. return null;
  30248. };
  30249. BaseTexture.prototype._rebuild = function () {
  30250. };
  30251. BaseTexture.prototype.delayLoad = function () {
  30252. };
  30253. BaseTexture.prototype.clone = function () {
  30254. return null;
  30255. };
  30256. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30257. get: function () {
  30258. if (!this._texture) {
  30259. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30260. }
  30261. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30267. get: function () {
  30268. if (!this._texture) {
  30269. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30270. }
  30271. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. BaseTexture.prototype.readPixels = function (faceIndex) {
  30277. if (faceIndex === void 0) { faceIndex = 0; }
  30278. if (!this._texture) {
  30279. return null;
  30280. }
  30281. var size = this.getSize();
  30282. var scene = this.getScene();
  30283. if (!scene) {
  30284. return null;
  30285. }
  30286. var engine = scene.getEngine();
  30287. if (this._texture.isCube) {
  30288. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30289. }
  30290. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30291. };
  30292. BaseTexture.prototype.releaseInternalTexture = function () {
  30293. if (this._texture) {
  30294. this._texture.dispose();
  30295. this._texture = null;
  30296. }
  30297. };
  30298. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30299. get: function () {
  30300. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30301. return null;
  30302. }
  30303. if (!this._texture._sphericalPolynomial) {
  30304. this._texture._sphericalPolynomial =
  30305. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30306. }
  30307. return this._texture._sphericalPolynomial;
  30308. },
  30309. set: function (value) {
  30310. if (this._texture) {
  30311. this._texture._sphericalPolynomial = value;
  30312. }
  30313. },
  30314. enumerable: true,
  30315. configurable: true
  30316. });
  30317. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30318. get: function () {
  30319. if (this._texture) {
  30320. return this._texture._lodTextureHigh;
  30321. }
  30322. return null;
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30328. get: function () {
  30329. if (this._texture) {
  30330. return this._texture._lodTextureMid;
  30331. }
  30332. return null;
  30333. },
  30334. enumerable: true,
  30335. configurable: true
  30336. });
  30337. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30338. get: function () {
  30339. if (this._texture) {
  30340. return this._texture._lodTextureLow;
  30341. }
  30342. return null;
  30343. },
  30344. enumerable: true,
  30345. configurable: true
  30346. });
  30347. BaseTexture.prototype.dispose = function () {
  30348. if (!this._scene) {
  30349. return;
  30350. }
  30351. // Animations
  30352. this._scene.stopAnimation(this);
  30353. // Remove from scene
  30354. this._scene._removePendingData(this);
  30355. var index = this._scene.textures.indexOf(this);
  30356. if (index >= 0) {
  30357. this._scene.textures.splice(index, 1);
  30358. }
  30359. if (this._texture === undefined) {
  30360. return;
  30361. }
  30362. // Release
  30363. this.releaseInternalTexture();
  30364. // Callback
  30365. this.onDisposeObservable.notifyObservers(this);
  30366. this.onDisposeObservable.clear();
  30367. };
  30368. BaseTexture.prototype.serialize = function () {
  30369. if (!this.name) {
  30370. return null;
  30371. }
  30372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30373. // Animations
  30374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30375. return serializationObject;
  30376. };
  30377. BaseTexture.WhenAllReady = function (textures, callback) {
  30378. var numRemaining = textures.length;
  30379. if (numRemaining === 0) {
  30380. callback();
  30381. return;
  30382. }
  30383. var _loop_1 = function () {
  30384. texture = textures[i];
  30385. if (texture.isReady()) {
  30386. if (--numRemaining === 0) {
  30387. callback();
  30388. }
  30389. }
  30390. else {
  30391. onLoadObservable = texture.onLoadObservable;
  30392. var onLoadCallback_1 = function () {
  30393. onLoadObservable.removeCallback(onLoadCallback_1);
  30394. if (--numRemaining === 0) {
  30395. callback();
  30396. }
  30397. };
  30398. onLoadObservable.add(onLoadCallback_1);
  30399. }
  30400. };
  30401. var texture, onLoadObservable;
  30402. for (var i = 0; i < textures.length; i++) {
  30403. _loop_1();
  30404. }
  30405. };
  30406. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30407. __decorate([
  30408. BABYLON.serialize()
  30409. ], BaseTexture.prototype, "name", void 0);
  30410. __decorate([
  30411. BABYLON.serialize("hasAlpha")
  30412. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30413. __decorate([
  30414. BABYLON.serialize()
  30415. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30416. __decorate([
  30417. BABYLON.serialize()
  30418. ], BaseTexture.prototype, "level", void 0);
  30419. __decorate([
  30420. BABYLON.serialize()
  30421. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30422. __decorate([
  30423. BABYLON.serialize("coordinatesMode")
  30424. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30425. __decorate([
  30426. BABYLON.serialize()
  30427. ], BaseTexture.prototype, "wrapU", void 0);
  30428. __decorate([
  30429. BABYLON.serialize()
  30430. ], BaseTexture.prototype, "wrapV", void 0);
  30431. __decorate([
  30432. BABYLON.serialize()
  30433. ], BaseTexture.prototype, "wrapR", void 0);
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30437. __decorate([
  30438. BABYLON.serialize()
  30439. ], BaseTexture.prototype, "isCube", void 0);
  30440. __decorate([
  30441. BABYLON.serialize()
  30442. ], BaseTexture.prototype, "is3D", void 0);
  30443. __decorate([
  30444. BABYLON.serialize()
  30445. ], BaseTexture.prototype, "gammaSpace", void 0);
  30446. __decorate([
  30447. BABYLON.serialize()
  30448. ], BaseTexture.prototype, "invertZ", void 0);
  30449. __decorate([
  30450. BABYLON.serialize()
  30451. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30452. __decorate([
  30453. BABYLON.serialize()
  30454. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30455. __decorate([
  30456. BABYLON.serialize()
  30457. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30458. __decorate([
  30459. BABYLON.serialize()
  30460. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30461. return BaseTexture;
  30462. }());
  30463. BABYLON.BaseTexture = BaseTexture;
  30464. })(BABYLON || (BABYLON = {}));
  30465. //# sourceMappingURL=babylon.baseTexture.js.map
  30466. var BABYLON;
  30467. (function (BABYLON) {
  30468. var Texture = /** @class */ (function (_super) {
  30469. __extends(Texture, _super);
  30470. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30471. if (noMipmap === void 0) { noMipmap = false; }
  30472. if (invertY === void 0) { invertY = true; }
  30473. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30474. if (onLoad === void 0) { onLoad = null; }
  30475. if (onError === void 0) { onError = null; }
  30476. if (buffer === void 0) { buffer = null; }
  30477. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30478. var _this = _super.call(this, scene) || this;
  30479. _this.uOffset = 0;
  30480. _this.vOffset = 0;
  30481. _this.uScale = 1.0;
  30482. _this.vScale = 1.0;
  30483. _this.uAng = 0;
  30484. _this.vAng = 0;
  30485. _this.wAng = 0;
  30486. /**
  30487. * Defines the center of rotation (U)
  30488. */
  30489. _this.uRotationCenter = 0.5;
  30490. /**
  30491. * Defines the center of rotation (V)
  30492. */
  30493. _this.vRotationCenter = 0.5;
  30494. /**
  30495. * Defines the center of rotation (W)
  30496. */
  30497. _this.wRotationCenter = 0.5;
  30498. _this._isBlocking = true;
  30499. _this.name = url || "";
  30500. _this.url = url;
  30501. _this._noMipmap = noMipmap;
  30502. _this._invertY = invertY;
  30503. _this._samplingMode = samplingMode;
  30504. _this._buffer = buffer;
  30505. _this._deleteBuffer = deleteBuffer;
  30506. if (format) {
  30507. _this._format = format;
  30508. }
  30509. scene = _this.getScene();
  30510. if (!scene) {
  30511. return _this;
  30512. }
  30513. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30514. var load = function () {
  30515. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30516. _this.onLoadObservable.notifyObservers(_this);
  30517. }
  30518. if (onLoad) {
  30519. onLoad();
  30520. }
  30521. if (!_this.isBlocking && scene) {
  30522. scene.resetCachedMaterial();
  30523. }
  30524. };
  30525. if (!_this.url) {
  30526. _this._delayedOnLoad = load;
  30527. _this._delayedOnError = onError;
  30528. return _this;
  30529. }
  30530. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30531. if (!_this._texture) {
  30532. if (!scene.useDelayedTextureLoading) {
  30533. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30534. if (deleteBuffer) {
  30535. delete _this._buffer;
  30536. }
  30537. }
  30538. else {
  30539. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30540. _this._delayedOnLoad = load;
  30541. _this._delayedOnError = onError;
  30542. }
  30543. }
  30544. else {
  30545. if (_this._texture.isReady) {
  30546. BABYLON.Tools.SetImmediate(function () { return load(); });
  30547. }
  30548. else {
  30549. _this._texture.onLoadedObservable.add(load);
  30550. }
  30551. }
  30552. return _this;
  30553. }
  30554. Object.defineProperty(Texture.prototype, "noMipmap", {
  30555. get: function () {
  30556. return this._noMipmap;
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(Texture.prototype, "isBlocking", {
  30562. get: function () {
  30563. return this._isBlocking;
  30564. },
  30565. set: function (value) {
  30566. this._isBlocking = value;
  30567. },
  30568. enumerable: true,
  30569. configurable: true
  30570. });
  30571. Object.defineProperty(Texture.prototype, "samplingMode", {
  30572. get: function () {
  30573. return this._samplingMode;
  30574. },
  30575. enumerable: true,
  30576. configurable: true
  30577. });
  30578. Texture.prototype.updateURL = function (url) {
  30579. this.url = url;
  30580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30581. this.delayLoad();
  30582. };
  30583. Texture.prototype.delayLoad = function () {
  30584. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30585. return;
  30586. }
  30587. var scene = this.getScene();
  30588. if (!scene) {
  30589. return;
  30590. }
  30591. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30592. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30593. if (!this._texture) {
  30594. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30595. if (this._deleteBuffer) {
  30596. delete this._buffer;
  30597. }
  30598. }
  30599. else {
  30600. if (this._delayedOnLoad) {
  30601. if (this._texture.isReady) {
  30602. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30603. }
  30604. else {
  30605. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30606. }
  30607. }
  30608. }
  30609. this._delayedOnLoad = null;
  30610. this._delayedOnError = null;
  30611. };
  30612. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30613. if (!this._texture) {
  30614. return;
  30615. }
  30616. var scene = this.getScene();
  30617. if (!scene) {
  30618. return;
  30619. }
  30620. this._samplingMode = samplingMode;
  30621. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30622. };
  30623. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30624. x *= this.uScale;
  30625. y *= this.vScale;
  30626. x -= this.uRotationCenter * this.uScale;
  30627. y -= this.vRotationCenter * this.vScale;
  30628. z -= this.wRotationCenter;
  30629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30630. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30631. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30632. t.z += this.wRotationCenter;
  30633. };
  30634. Texture.prototype.getTextureMatrix = function () {
  30635. var _this = this;
  30636. if (this.uOffset === this._cachedUOffset &&
  30637. this.vOffset === this._cachedVOffset &&
  30638. this.uScale === this._cachedUScale &&
  30639. this.vScale === this._cachedVScale &&
  30640. this.uAng === this._cachedUAng &&
  30641. this.vAng === this._cachedVAng &&
  30642. this.wAng === this._cachedWAng) {
  30643. return this._cachedTextureMatrix;
  30644. }
  30645. this._cachedUOffset = this.uOffset;
  30646. this._cachedVOffset = this.vOffset;
  30647. this._cachedUScale = this.uScale;
  30648. this._cachedVScale = this.vScale;
  30649. this._cachedUAng = this.uAng;
  30650. this._cachedVAng = this.vAng;
  30651. this._cachedWAng = this.wAng;
  30652. if (!this._cachedTextureMatrix) {
  30653. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30654. this._rowGenerationMatrix = new BABYLON.Matrix();
  30655. this._t0 = BABYLON.Vector3.Zero();
  30656. this._t1 = BABYLON.Vector3.Zero();
  30657. this._t2 = BABYLON.Vector3.Zero();
  30658. }
  30659. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30660. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30661. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30662. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30663. this._t1.subtractInPlace(this._t0);
  30664. this._t2.subtractInPlace(this._t0);
  30665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30666. this._cachedTextureMatrix.m[0] = this._t1.x;
  30667. this._cachedTextureMatrix.m[1] = this._t1.y;
  30668. this._cachedTextureMatrix.m[2] = this._t1.z;
  30669. this._cachedTextureMatrix.m[4] = this._t2.x;
  30670. this._cachedTextureMatrix.m[5] = this._t2.y;
  30671. this._cachedTextureMatrix.m[6] = this._t2.z;
  30672. this._cachedTextureMatrix.m[8] = this._t0.x;
  30673. this._cachedTextureMatrix.m[9] = this._t0.y;
  30674. this._cachedTextureMatrix.m[10] = this._t0.z;
  30675. var scene = this.getScene();
  30676. if (!scene) {
  30677. return this._cachedTextureMatrix;
  30678. }
  30679. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30680. return mat.hasTexture(_this);
  30681. });
  30682. return this._cachedTextureMatrix;
  30683. };
  30684. Texture.prototype.getReflectionTextureMatrix = function () {
  30685. var _this = this;
  30686. var scene = this.getScene();
  30687. if (!scene) {
  30688. return this._cachedTextureMatrix;
  30689. }
  30690. if (this.uOffset === this._cachedUOffset &&
  30691. this.vOffset === this._cachedVOffset &&
  30692. this.uScale === this._cachedUScale &&
  30693. this.vScale === this._cachedVScale &&
  30694. this.coordinatesMode === this._cachedCoordinatesMode) {
  30695. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30696. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30697. return this._cachedTextureMatrix;
  30698. }
  30699. }
  30700. else {
  30701. return this._cachedTextureMatrix;
  30702. }
  30703. }
  30704. if (!this._cachedTextureMatrix) {
  30705. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30706. }
  30707. if (!this._projectionModeMatrix) {
  30708. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30709. }
  30710. this._cachedUOffset = this.uOffset;
  30711. this._cachedVOffset = this.vOffset;
  30712. this._cachedUScale = this.uScale;
  30713. this._cachedVScale = this.vScale;
  30714. this._cachedCoordinatesMode = this.coordinatesMode;
  30715. switch (this.coordinatesMode) {
  30716. case Texture.PLANAR_MODE:
  30717. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30718. this._cachedTextureMatrix[0] = this.uScale;
  30719. this._cachedTextureMatrix[5] = this.vScale;
  30720. this._cachedTextureMatrix[12] = this.uOffset;
  30721. this._cachedTextureMatrix[13] = this.vOffset;
  30722. break;
  30723. case Texture.PROJECTION_MODE:
  30724. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30725. this._projectionModeMatrix.m[0] = 0.5;
  30726. this._projectionModeMatrix.m[5] = -0.5;
  30727. this._projectionModeMatrix.m[10] = 0.0;
  30728. this._projectionModeMatrix.m[12] = 0.5;
  30729. this._projectionModeMatrix.m[13] = 0.5;
  30730. this._projectionModeMatrix.m[14] = 1.0;
  30731. this._projectionModeMatrix.m[15] = 1.0;
  30732. var projectionMatrix = scene.getProjectionMatrix();
  30733. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30734. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30735. break;
  30736. default:
  30737. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30738. break;
  30739. }
  30740. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30741. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30742. });
  30743. return this._cachedTextureMatrix;
  30744. };
  30745. Texture.prototype.clone = function () {
  30746. var _this = this;
  30747. return BABYLON.SerializationHelper.Clone(function () {
  30748. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30749. }, this);
  30750. };
  30751. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30752. get: function () {
  30753. if (!this._onLoadObservable) {
  30754. this._onLoadObservable = new BABYLON.Observable();
  30755. }
  30756. return this._onLoadObservable;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Texture.prototype.serialize = function () {
  30762. var serializationObject = _super.prototype.serialize.call(this);
  30763. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30764. serializationObject.base64String = this._buffer;
  30765. serializationObject.name = serializationObject.name.replace("data:", "");
  30766. }
  30767. serializationObject.invertY = this._invertY;
  30768. serializationObject.samplingMode = this.samplingMode;
  30769. return serializationObject;
  30770. };
  30771. Texture.prototype.getClassName = function () {
  30772. return "Texture";
  30773. };
  30774. Texture.prototype.dispose = function () {
  30775. _super.prototype.dispose.call(this);
  30776. if (this.onLoadObservable) {
  30777. this.onLoadObservable.clear();
  30778. this._onLoadObservable = null;
  30779. }
  30780. this._delayedOnLoad = null;
  30781. this._delayedOnError = null;
  30782. };
  30783. // Statics
  30784. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30785. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30786. if (onLoad === void 0) { onLoad = null; }
  30787. if (onError === void 0) { onError = null; }
  30788. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30789. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30790. };
  30791. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30792. if (parsedTexture.customType) {
  30793. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30794. // Update Sampling Mode
  30795. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30796. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30797. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30798. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30799. }
  30800. }
  30801. return parsedCustomTexture;
  30802. }
  30803. if (parsedTexture.isCube) {
  30804. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30805. }
  30806. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30807. return null;
  30808. }
  30809. var texture = BABYLON.SerializationHelper.Parse(function () {
  30810. var generateMipMaps = true;
  30811. if (parsedTexture.noMipmap) {
  30812. generateMipMaps = false;
  30813. }
  30814. if (parsedTexture.mirrorPlane) {
  30815. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30816. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30817. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30818. return mirrorTexture;
  30819. }
  30820. else if (parsedTexture.isRenderTarget) {
  30821. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30822. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30823. return renderTargetTexture;
  30824. }
  30825. else {
  30826. var texture;
  30827. if (parsedTexture.base64String) {
  30828. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30829. }
  30830. else {
  30831. var url = rootUrl + parsedTexture.name;
  30832. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30833. url = parsedTexture.url;
  30834. }
  30835. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30836. }
  30837. return texture;
  30838. }
  30839. }, parsedTexture, scene);
  30840. // Update Sampling Mode
  30841. if (parsedTexture.samplingMode) {
  30842. var sampling = parsedTexture.samplingMode;
  30843. if (texture._samplingMode !== sampling) {
  30844. texture.updateSamplingMode(sampling);
  30845. }
  30846. }
  30847. // Animations
  30848. if (parsedTexture.animations) {
  30849. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30850. var parsedAnimation = parsedTexture.animations[animationIndex];
  30851. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30852. }
  30853. }
  30854. return texture;
  30855. };
  30856. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30857. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30858. if (noMipmap === void 0) { noMipmap = false; }
  30859. if (invertY === void 0) { invertY = true; }
  30860. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30861. if (onLoad === void 0) { onLoad = null; }
  30862. if (onError === void 0) { onError = null; }
  30863. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30864. if (name.substr(0, 5) !== "data:") {
  30865. name = "data:" + name;
  30866. }
  30867. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30868. };
  30869. // Constants
  30870. Texture.NEAREST_SAMPLINGMODE = 1;
  30871. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30872. Texture.BILINEAR_SAMPLINGMODE = 2;
  30873. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30874. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30875. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30876. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30877. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30878. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30879. Texture.NEAREST_LINEAR = 7;
  30880. Texture.NEAREST_NEAREST = 8;
  30881. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30882. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30883. Texture.LINEAR_LINEAR = 11;
  30884. Texture.LINEAR_NEAREST = 12;
  30885. Texture.EXPLICIT_MODE = 0;
  30886. Texture.SPHERICAL_MODE = 1;
  30887. Texture.PLANAR_MODE = 2;
  30888. Texture.CUBIC_MODE = 3;
  30889. Texture.PROJECTION_MODE = 4;
  30890. Texture.SKYBOX_MODE = 5;
  30891. Texture.INVCUBIC_MODE = 6;
  30892. Texture.EQUIRECTANGULAR_MODE = 7;
  30893. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30894. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30895. Texture.CLAMP_ADDRESSMODE = 0;
  30896. Texture.WRAP_ADDRESSMODE = 1;
  30897. Texture.MIRROR_ADDRESSMODE = 2;
  30898. /**
  30899. * 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
  30900. */
  30901. Texture.UseSerializedUrlIfAny = false;
  30902. __decorate([
  30903. BABYLON.serialize()
  30904. ], Texture.prototype, "url", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], Texture.prototype, "uOffset", void 0);
  30908. __decorate([
  30909. BABYLON.serialize()
  30910. ], Texture.prototype, "vOffset", void 0);
  30911. __decorate([
  30912. BABYLON.serialize()
  30913. ], Texture.prototype, "uScale", void 0);
  30914. __decorate([
  30915. BABYLON.serialize()
  30916. ], Texture.prototype, "vScale", void 0);
  30917. __decorate([
  30918. BABYLON.serialize()
  30919. ], Texture.prototype, "uAng", void 0);
  30920. __decorate([
  30921. BABYLON.serialize()
  30922. ], Texture.prototype, "vAng", void 0);
  30923. __decorate([
  30924. BABYLON.serialize()
  30925. ], Texture.prototype, "wAng", void 0);
  30926. __decorate([
  30927. BABYLON.serialize()
  30928. ], Texture.prototype, "uRotationCenter", void 0);
  30929. __decorate([
  30930. BABYLON.serialize()
  30931. ], Texture.prototype, "vRotationCenter", void 0);
  30932. __decorate([
  30933. BABYLON.serialize()
  30934. ], Texture.prototype, "wRotationCenter", void 0);
  30935. __decorate([
  30936. BABYLON.serialize()
  30937. ], Texture.prototype, "isBlocking", null);
  30938. return Texture;
  30939. }(BABYLON.BaseTexture));
  30940. BABYLON.Texture = Texture;
  30941. })(BABYLON || (BABYLON = {}));
  30942. //# sourceMappingURL=babylon.texture.js.map
  30943. var BABYLON;
  30944. (function (BABYLON) {
  30945. /**
  30946. * @hidden
  30947. **/
  30948. var _InstancesBatch = /** @class */ (function () {
  30949. function _InstancesBatch() {
  30950. this.mustReturn = false;
  30951. this.visibleInstances = new Array();
  30952. this.renderSelf = new Array();
  30953. }
  30954. return _InstancesBatch;
  30955. }());
  30956. BABYLON._InstancesBatch = _InstancesBatch;
  30957. var Mesh = /** @class */ (function (_super) {
  30958. __extends(Mesh, _super);
  30959. /**
  30960. * @constructor
  30961. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30962. * @param {Scene} scene The scene to add this mesh to.
  30963. * @param {Node} parent The parent of this mesh, if it has one
  30964. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30965. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30966. * When false, achieved by calling a clone(), also passing False.
  30967. * This will make creation of children, recursive.
  30968. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30969. */
  30970. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30971. if (scene === void 0) { scene = null; }
  30972. if (parent === void 0) { parent = null; }
  30973. if (source === void 0) { source = null; }
  30974. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30975. var _this = _super.call(this, name, scene) || this;
  30976. // Events
  30977. /**
  30978. * An event triggered before rendering the mesh
  30979. */
  30980. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30981. /**
  30982. * An event triggered after rendering the mesh
  30983. */
  30984. _this.onAfterRenderObservable = new BABYLON.Observable();
  30985. /**
  30986. * An event triggered before drawing the mesh
  30987. */
  30988. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30989. // Members
  30990. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30991. _this.instances = new Array();
  30992. _this._LODLevels = new Array();
  30993. _this._visibleInstances = {};
  30994. _this._renderIdForInstances = new Array();
  30995. _this._batchCache = new _InstancesBatch();
  30996. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30997. // Use by builder only to know what orientation were the mesh build in.
  30998. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30999. _this.overrideMaterialSideOrientation = null;
  31000. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31001. // Will be used to save a source mesh reference, If any
  31002. _this._source = null;
  31003. scene = _this.getScene();
  31004. if (source) {
  31005. // Source mesh
  31006. _this._source = source;
  31007. // Geometry
  31008. if (source._geometry) {
  31009. source._geometry.applyToMesh(_this);
  31010. }
  31011. // Deep copy
  31012. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31013. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  31014. // Metadata
  31015. if (source.metadata && source.metadata.clone) {
  31016. _this.metadata = source.metadata.clone();
  31017. }
  31018. else {
  31019. _this.metadata = source.metadata;
  31020. }
  31021. // Tags
  31022. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31023. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31024. }
  31025. // Parent
  31026. _this.parent = source.parent;
  31027. // Pivot
  31028. _this.setPivotMatrix(source.getPivotMatrix());
  31029. _this.id = name + "." + source.id;
  31030. // Material
  31031. _this.material = source.material;
  31032. var index;
  31033. if (!doNotCloneChildren) {
  31034. // Children
  31035. var directDescendants = source.getDescendants(true);
  31036. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31037. var child = directDescendants[index_1];
  31038. if (child.clone) {
  31039. child.clone(name + "." + child.name, _this);
  31040. }
  31041. }
  31042. }
  31043. // Physics clone
  31044. var physicsEngine = _this.getScene().getPhysicsEngine();
  31045. if (clonePhysicsImpostor && physicsEngine) {
  31046. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31047. if (impostor) {
  31048. _this.physicsImpostor = impostor.clone(_this);
  31049. }
  31050. }
  31051. // Particles
  31052. for (index = 0; index < scene.particleSystems.length; index++) {
  31053. var system = scene.particleSystems[index];
  31054. if (system.emitter === source) {
  31055. system.clone(system.name, _this);
  31056. }
  31057. }
  31058. _this.computeWorldMatrix(true);
  31059. }
  31060. // Parent
  31061. if (parent !== null) {
  31062. _this.parent = parent;
  31063. }
  31064. return _this;
  31065. }
  31066. Object.defineProperty(Mesh, "FRONTSIDE", {
  31067. /**
  31068. * Mesh side orientation : usually the external or front surface
  31069. */
  31070. get: function () {
  31071. return Mesh._FRONTSIDE;
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(Mesh, "BACKSIDE", {
  31077. /**
  31078. * Mesh side orientation : usually the internal or back surface
  31079. */
  31080. get: function () {
  31081. return Mesh._BACKSIDE;
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31087. /**
  31088. * Mesh side orientation : both internal and external or front and back surfaces
  31089. */
  31090. get: function () {
  31091. return Mesh._DOUBLESIDE;
  31092. },
  31093. enumerable: true,
  31094. configurable: true
  31095. });
  31096. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31097. /**
  31098. * Mesh side orientation : by default, `FRONTSIDE`
  31099. */
  31100. get: function () {
  31101. return Mesh._DEFAULTSIDE;
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(Mesh, "NO_CAP", {
  31107. /**
  31108. * Mesh cap setting : no cap
  31109. */
  31110. get: function () {
  31111. return Mesh._NO_CAP;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Mesh, "CAP_START", {
  31117. /**
  31118. * Mesh cap setting : one cap at the beginning of the mesh
  31119. */
  31120. get: function () {
  31121. return Mesh._CAP_START;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. Object.defineProperty(Mesh, "CAP_END", {
  31127. /**
  31128. * Mesh cap setting : one cap at the end of the mesh
  31129. */
  31130. get: function () {
  31131. return Mesh._CAP_END;
  31132. },
  31133. enumerable: true,
  31134. configurable: true
  31135. });
  31136. Object.defineProperty(Mesh, "CAP_ALL", {
  31137. /**
  31138. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31139. */
  31140. get: function () {
  31141. return Mesh._CAP_ALL;
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31147. set: function (callback) {
  31148. if (this._onBeforeDrawObserver) {
  31149. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31150. }
  31151. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31157. get: function () {
  31158. return this._morphTargetManager;
  31159. },
  31160. set: function (value) {
  31161. if (this._morphTargetManager === value) {
  31162. return;
  31163. }
  31164. this._morphTargetManager = value;
  31165. this._syncGeometryWithMorphTargetManager();
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Object.defineProperty(Mesh.prototype, "source", {
  31171. get: function () {
  31172. return this._source;
  31173. },
  31174. enumerable: true,
  31175. configurable: true
  31176. });
  31177. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31178. get: function () {
  31179. return this._unIndexed;
  31180. },
  31181. set: function (value) {
  31182. if (this._unIndexed !== value) {
  31183. this._unIndexed = value;
  31184. this._markSubMeshesAsAttributesDirty();
  31185. }
  31186. },
  31187. enumerable: true,
  31188. configurable: true
  31189. });
  31190. // Methods
  31191. /**
  31192. * Returns the string "Mesh".
  31193. */
  31194. Mesh.prototype.getClassName = function () {
  31195. return "Mesh";
  31196. };
  31197. /**
  31198. * Returns a string.
  31199. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31200. */
  31201. Mesh.prototype.toString = function (fullDetails) {
  31202. var ret = _super.prototype.toString.call(this, fullDetails);
  31203. ret += ", n vertices: " + this.getTotalVertices();
  31204. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31205. if (this.animations) {
  31206. for (var i = 0; i < this.animations.length; i++) {
  31207. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31208. }
  31209. }
  31210. if (fullDetails) {
  31211. if (this._geometry) {
  31212. var ib = this.getIndices();
  31213. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31214. if (vb && ib) {
  31215. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31216. }
  31217. }
  31218. else {
  31219. ret += ", flat shading: UNKNOWN";
  31220. }
  31221. }
  31222. return ret;
  31223. };
  31224. Mesh.prototype._unBindEffect = function () {
  31225. _super.prototype._unBindEffect.call(this);
  31226. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31227. var instance = _a[_i];
  31228. instance._unBindEffect();
  31229. }
  31230. };
  31231. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31232. /**
  31233. * True if the mesh has some Levels Of Details (LOD).
  31234. * Returns a boolean.
  31235. */
  31236. get: function () {
  31237. return this._LODLevels.length > 0;
  31238. },
  31239. enumerable: true,
  31240. configurable: true
  31241. });
  31242. /**
  31243. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31244. * @returns an array of {BABYLON.MeshLODLevel}
  31245. */
  31246. Mesh.prototype.getLODLevels = function () {
  31247. return this._LODLevels;
  31248. };
  31249. Mesh.prototype._sortLODLevels = function () {
  31250. this._LODLevels.sort(function (a, b) {
  31251. if (a.distance < b.distance) {
  31252. return 1;
  31253. }
  31254. if (a.distance > b.distance) {
  31255. return -1;
  31256. }
  31257. return 0;
  31258. });
  31259. };
  31260. /**
  31261. * Add a mesh as LOD level triggered at the given distance.
  31262. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31263. * @param {number} distance The distance from the center of the object to show this level
  31264. * @param {Mesh} mesh The mesh to be added as LOD level
  31265. * @return {Mesh} This mesh (for chaining)
  31266. */
  31267. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31268. if (mesh && mesh._masterMesh) {
  31269. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31270. return this;
  31271. }
  31272. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31273. this._LODLevels.push(level);
  31274. if (mesh) {
  31275. mesh._masterMesh = this;
  31276. }
  31277. this._sortLODLevels();
  31278. return this;
  31279. };
  31280. /**
  31281. * Returns the LOD level mesh at the passed distance or null if not found.
  31282. * It is related to the method `addLODLevel(distance, mesh)`.
  31283. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31284. * Returns an object Mesh or `null`.
  31285. */
  31286. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31287. for (var index = 0; index < this._LODLevels.length; index++) {
  31288. var level = this._LODLevels[index];
  31289. if (level.distance === distance) {
  31290. return level.mesh;
  31291. }
  31292. }
  31293. return null;
  31294. };
  31295. /**
  31296. * Remove a mesh from the LOD array
  31297. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31298. * @param {Mesh} mesh The mesh to be removed.
  31299. * @return {Mesh} This mesh (for chaining)
  31300. */
  31301. Mesh.prototype.removeLODLevel = function (mesh) {
  31302. for (var index = 0; index < this._LODLevels.length; index++) {
  31303. if (this._LODLevels[index].mesh === mesh) {
  31304. this._LODLevels.splice(index, 1);
  31305. if (mesh) {
  31306. mesh._masterMesh = null;
  31307. }
  31308. }
  31309. }
  31310. this._sortLODLevels();
  31311. return this;
  31312. };
  31313. /**
  31314. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31315. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31316. */
  31317. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31318. if (!this._LODLevels || this._LODLevels.length === 0) {
  31319. return this;
  31320. }
  31321. var bSphere;
  31322. if (boundingSphere) {
  31323. bSphere = boundingSphere;
  31324. }
  31325. else {
  31326. var boundingInfo = this.getBoundingInfo();
  31327. bSphere = boundingInfo.boundingSphere;
  31328. }
  31329. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31330. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31331. if (this.onLODLevelSelection) {
  31332. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31333. }
  31334. return this;
  31335. }
  31336. for (var index = 0; index < this._LODLevels.length; index++) {
  31337. var level = this._LODLevels[index];
  31338. if (level.distance < distanceToCamera) {
  31339. if (level.mesh) {
  31340. level.mesh._preActivate();
  31341. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31342. }
  31343. if (this.onLODLevelSelection) {
  31344. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31345. }
  31346. return level.mesh;
  31347. }
  31348. }
  31349. if (this.onLODLevelSelection) {
  31350. this.onLODLevelSelection(distanceToCamera, this, this);
  31351. }
  31352. return this;
  31353. };
  31354. Object.defineProperty(Mesh.prototype, "geometry", {
  31355. /**
  31356. * Returns the mesh internal Geometry object.
  31357. */
  31358. get: function () {
  31359. return this._geometry;
  31360. },
  31361. enumerable: true,
  31362. configurable: true
  31363. });
  31364. /**
  31365. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31366. */
  31367. Mesh.prototype.getTotalVertices = function () {
  31368. if (this._geometry === null || this._geometry === undefined) {
  31369. return 0;
  31370. }
  31371. return this._geometry.getTotalVertices();
  31372. };
  31373. /**
  31374. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31375. * 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.
  31376. * You can force the copy with forceCopy === true
  31377. * Returns null if the mesh has no geometry or no vertex buffer.
  31378. * Possible `kind` values :
  31379. * - BABYLON.VertexBuffer.PositionKind
  31380. * - BABYLON.VertexBuffer.UVKind
  31381. * - BABYLON.VertexBuffer.UV2Kind
  31382. * - BABYLON.VertexBuffer.UV3Kind
  31383. * - BABYLON.VertexBuffer.UV4Kind
  31384. * - BABYLON.VertexBuffer.UV5Kind
  31385. * - BABYLON.VertexBuffer.UV6Kind
  31386. * - BABYLON.VertexBuffer.ColorKind
  31387. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31388. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31389. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31390. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31391. */
  31392. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31393. if (!this._geometry) {
  31394. return null;
  31395. }
  31396. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31397. };
  31398. /**
  31399. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31400. * Returns `null` if the mesh has no geometry.
  31401. * Possible `kind` values :
  31402. * - BABYLON.VertexBuffer.PositionKind
  31403. * - BABYLON.VertexBuffer.UVKind
  31404. * - BABYLON.VertexBuffer.UV2Kind
  31405. * - BABYLON.VertexBuffer.UV3Kind
  31406. * - BABYLON.VertexBuffer.UV4Kind
  31407. * - BABYLON.VertexBuffer.UV5Kind
  31408. * - BABYLON.VertexBuffer.UV6Kind
  31409. * - BABYLON.VertexBuffer.ColorKind
  31410. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31411. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31412. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31413. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31414. */
  31415. Mesh.prototype.getVertexBuffer = function (kind) {
  31416. if (!this._geometry) {
  31417. return null;
  31418. }
  31419. return this._geometry.getVertexBuffer(kind);
  31420. };
  31421. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31422. if (!this._geometry) {
  31423. if (this._delayInfo) {
  31424. return this._delayInfo.indexOf(kind) !== -1;
  31425. }
  31426. return false;
  31427. }
  31428. return this._geometry.isVerticesDataPresent(kind);
  31429. };
  31430. /**
  31431. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31432. * Possible `kind` values :
  31433. * - BABYLON.VertexBuffer.PositionKind
  31434. * - BABYLON.VertexBuffer.UVKind
  31435. * - BABYLON.VertexBuffer.UV2Kind
  31436. * - BABYLON.VertexBuffer.UV3Kind
  31437. * - BABYLON.VertexBuffer.UV4Kind
  31438. * - BABYLON.VertexBuffer.UV5Kind
  31439. * - BABYLON.VertexBuffer.UV6Kind
  31440. * - BABYLON.VertexBuffer.ColorKind
  31441. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31442. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31443. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31444. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31445. */
  31446. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31447. if (!this._geometry) {
  31448. if (this._delayInfo) {
  31449. return this._delayInfo.indexOf(kind) !== -1;
  31450. }
  31451. return false;
  31452. }
  31453. return this._geometry.isVertexBufferUpdatable(kind);
  31454. };
  31455. /**
  31456. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31457. * Possible `kind` values :
  31458. * - BABYLON.VertexBuffer.PositionKind
  31459. * - BABYLON.VertexBuffer.UVKind
  31460. * - BABYLON.VertexBuffer.UV2Kind
  31461. * - BABYLON.VertexBuffer.UV3Kind
  31462. * - BABYLON.VertexBuffer.UV4Kind
  31463. * - BABYLON.VertexBuffer.UV5Kind
  31464. * - BABYLON.VertexBuffer.UV6Kind
  31465. * - BABYLON.VertexBuffer.ColorKind
  31466. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31467. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31468. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31469. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31470. */
  31471. Mesh.prototype.getVerticesDataKinds = function () {
  31472. if (!this._geometry) {
  31473. var result = new Array();
  31474. if (this._delayInfo) {
  31475. this._delayInfo.forEach(function (kind, index, array) {
  31476. result.push(kind);
  31477. });
  31478. }
  31479. return result;
  31480. }
  31481. return this._geometry.getVerticesDataKinds();
  31482. };
  31483. /**
  31484. * Returns a positive integer : the total number of indices in this mesh geometry.
  31485. * Returns zero if the mesh has no geometry.
  31486. */
  31487. Mesh.prototype.getTotalIndices = function () {
  31488. if (!this._geometry) {
  31489. return 0;
  31490. }
  31491. return this._geometry.getTotalIndices();
  31492. };
  31493. /**
  31494. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31495. * 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.
  31496. * Returns an empty array if the mesh has no geometry.
  31497. */
  31498. Mesh.prototype.getIndices = function (copyWhenShared) {
  31499. if (!this._geometry) {
  31500. return [];
  31501. }
  31502. return this._geometry.getIndices(copyWhenShared);
  31503. };
  31504. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31505. get: function () {
  31506. return this._masterMesh !== null && this._masterMesh !== undefined;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. /**
  31512. * Determine if the current mesh is ready to be rendered
  31513. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31514. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31515. * @returns true if all associated assets are ready (material, textures, shaders)
  31516. */
  31517. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31518. if (completeCheck === void 0) { completeCheck = false; }
  31519. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31520. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31521. return false;
  31522. }
  31523. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31524. return false;
  31525. }
  31526. if (!this.subMeshes || this.subMeshes.length === 0) {
  31527. return true;
  31528. }
  31529. if (!completeCheck) {
  31530. return true;
  31531. }
  31532. var engine = this.getEngine();
  31533. var scene = this.getScene();
  31534. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31535. this.computeWorldMatrix();
  31536. var mat = this.material || scene.defaultMaterial;
  31537. if (mat) {
  31538. if (mat.storeEffectOnSubMeshes) {
  31539. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31540. var subMesh = _a[_i];
  31541. var effectiveMaterial = subMesh.getMaterial();
  31542. if (effectiveMaterial) {
  31543. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31544. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31545. return false;
  31546. }
  31547. }
  31548. else {
  31549. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31550. return false;
  31551. }
  31552. }
  31553. }
  31554. }
  31555. }
  31556. else {
  31557. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31558. return false;
  31559. }
  31560. }
  31561. }
  31562. // Shadows
  31563. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31564. var light = _c[_b];
  31565. var generator = light.getShadowGenerator();
  31566. if (generator) {
  31567. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31568. var subMesh = _e[_d];
  31569. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31570. return false;
  31571. }
  31572. }
  31573. }
  31574. }
  31575. // LOD
  31576. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31577. var lod = _g[_f];
  31578. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31579. return false;
  31580. }
  31581. }
  31582. return true;
  31583. };
  31584. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31585. /**
  31586. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31587. * This property is pertinent only for updatable parametric shapes.
  31588. */
  31589. get: function () {
  31590. return this._areNormalsFrozen;
  31591. },
  31592. enumerable: true,
  31593. configurable: true
  31594. });
  31595. /**
  31596. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31597. * It has no effect at all on other shapes.
  31598. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31599. * Returns the Mesh.
  31600. */
  31601. Mesh.prototype.freezeNormals = function () {
  31602. this._areNormalsFrozen = true;
  31603. return this;
  31604. };
  31605. /**
  31606. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31607. * It has no effect at all on other shapes.
  31608. * It reactivates the mesh normals computation if it was previously frozen.
  31609. * Returns the Mesh.
  31610. */
  31611. Mesh.prototype.unfreezeNormals = function () {
  31612. this._areNormalsFrozen = false;
  31613. return this;
  31614. };
  31615. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31616. /**
  31617. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31618. */
  31619. set: function (count) {
  31620. this._overridenInstanceCount = count;
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. // Methods
  31626. Mesh.prototype._preActivate = function () {
  31627. var sceneRenderId = this.getScene().getRenderId();
  31628. if (this._preActivateId === sceneRenderId) {
  31629. return this;
  31630. }
  31631. this._preActivateId = sceneRenderId;
  31632. this._visibleInstances = null;
  31633. return this;
  31634. };
  31635. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31636. if (this._visibleInstances) {
  31637. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31638. }
  31639. return this;
  31640. };
  31641. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31642. if (!this._visibleInstances) {
  31643. this._visibleInstances = {};
  31644. this._visibleInstances.defaultRenderId = renderId;
  31645. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31646. }
  31647. if (!this._visibleInstances[renderId]) {
  31648. this._visibleInstances[renderId] = new Array();
  31649. }
  31650. this._visibleInstances[renderId].push(instance);
  31651. return this;
  31652. };
  31653. /**
  31654. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31655. * This means the mesh underlying bounding box and sphere are recomputed.
  31656. * Returns the Mesh.
  31657. */
  31658. Mesh.prototype.refreshBoundingInfo = function () {
  31659. return this._refreshBoundingInfo(false);
  31660. };
  31661. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31662. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31663. return this;
  31664. }
  31665. var data = this._getPositionData(applySkeleton);
  31666. if (data) {
  31667. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31668. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31669. }
  31670. if (this.subMeshes) {
  31671. for (var index = 0; index < this.subMeshes.length; index++) {
  31672. this.subMeshes[index].refreshBoundingInfo();
  31673. }
  31674. }
  31675. this._updateBoundingInfo();
  31676. return this;
  31677. };
  31678. Mesh.prototype._getPositionData = function (applySkeleton) {
  31679. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31680. if (data && applySkeleton && this.skeleton) {
  31681. data = BABYLON.Tools.Slice(data);
  31682. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31683. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31684. if (matricesWeightsData && matricesIndicesData) {
  31685. var needExtras = this.numBoneInfluencers > 4;
  31686. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31687. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31688. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31689. var tempVector = BABYLON.Tmp.Vector3[0];
  31690. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31691. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31692. var matWeightIdx = 0;
  31693. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31694. finalMatrix.reset();
  31695. var inf;
  31696. var weight;
  31697. for (inf = 0; inf < 4; inf++) {
  31698. weight = matricesWeightsData[matWeightIdx + inf];
  31699. if (weight <= 0)
  31700. break;
  31701. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31702. finalMatrix.addToSelf(tempMatrix);
  31703. }
  31704. if (needExtras) {
  31705. for (inf = 0; inf < 4; inf++) {
  31706. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31707. if (weight <= 0)
  31708. break;
  31709. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31710. finalMatrix.addToSelf(tempMatrix);
  31711. }
  31712. }
  31713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31714. tempVector.toArray(data, index);
  31715. }
  31716. }
  31717. }
  31718. return data;
  31719. };
  31720. Mesh.prototype._createGlobalSubMesh = function (force) {
  31721. var totalVertices = this.getTotalVertices();
  31722. if (!totalVertices || !this.getIndices()) {
  31723. return null;
  31724. }
  31725. // Check if we need to recreate the submeshes
  31726. if (this.subMeshes && this.subMeshes.length > 0) {
  31727. var ib = this.getIndices();
  31728. if (!ib) {
  31729. return null;
  31730. }
  31731. var totalIndices = ib.length;
  31732. var needToRecreate = false;
  31733. if (force) {
  31734. needToRecreate = true;
  31735. }
  31736. else {
  31737. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31738. var submesh = _a[_i];
  31739. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31740. needToRecreate = true;
  31741. break;
  31742. }
  31743. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31744. needToRecreate = true;
  31745. break;
  31746. }
  31747. }
  31748. }
  31749. if (!needToRecreate) {
  31750. return this.subMeshes[0];
  31751. }
  31752. }
  31753. this.releaseSubMeshes();
  31754. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31755. };
  31756. Mesh.prototype.subdivide = function (count) {
  31757. if (count < 1) {
  31758. return;
  31759. }
  31760. var totalIndices = this.getTotalIndices();
  31761. var subdivisionSize = (totalIndices / count) | 0;
  31762. var offset = 0;
  31763. // Ensure that subdivisionSize is a multiple of 3
  31764. while (subdivisionSize % 3 !== 0) {
  31765. subdivisionSize++;
  31766. }
  31767. this.releaseSubMeshes();
  31768. for (var index = 0; index < count; index++) {
  31769. if (offset >= totalIndices) {
  31770. break;
  31771. }
  31772. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31773. offset += subdivisionSize;
  31774. }
  31775. this.synchronizeInstances();
  31776. };
  31777. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31778. if (updatable === void 0) { updatable = false; }
  31779. if (!this._geometry) {
  31780. var vertexData = new BABYLON.VertexData();
  31781. vertexData.set(data, kind);
  31782. var scene = this.getScene();
  31783. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31784. }
  31785. else {
  31786. this._geometry.setVerticesData(kind, data, updatable, stride);
  31787. }
  31788. return this;
  31789. };
  31790. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31791. if (updatable === void 0) { updatable = true; }
  31792. var vb = this.getVertexBuffer(kind);
  31793. if (!vb || vb.isUpdatable() === updatable) {
  31794. return;
  31795. }
  31796. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31797. };
  31798. /**
  31799. * Sets the mesh VertexBuffer.
  31800. * Returns the Mesh.
  31801. */
  31802. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31803. if (!this._geometry) {
  31804. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31805. }
  31806. this._geometry.setVerticesBuffer(buffer);
  31807. return this;
  31808. };
  31809. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31810. if (!this._geometry) {
  31811. return this;
  31812. }
  31813. if (!makeItUnique) {
  31814. this._geometry.updateVerticesData(kind, data, updateExtends);
  31815. }
  31816. else {
  31817. this.makeGeometryUnique();
  31818. this.updateVerticesData(kind, data, updateExtends, false);
  31819. }
  31820. return this;
  31821. };
  31822. /**
  31823. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31824. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31825. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31826. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31827. * Returns the Mesh.
  31828. */
  31829. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31830. if (computeNormals === void 0) { computeNormals = true; }
  31831. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31832. if (!positions) {
  31833. return this;
  31834. }
  31835. positionFunction(positions);
  31836. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31837. if (computeNormals) {
  31838. var indices = this.getIndices();
  31839. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31840. if (!normals) {
  31841. return this;
  31842. }
  31843. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31844. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31845. }
  31846. return this;
  31847. };
  31848. /**
  31849. * Creates a un-shared specific occurence of the geometry for the mesh.
  31850. * Returns the Mesh.
  31851. */
  31852. Mesh.prototype.makeGeometryUnique = function () {
  31853. if (!this._geometry) {
  31854. return this;
  31855. }
  31856. var oldGeometry = this._geometry;
  31857. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31858. oldGeometry.releaseForMesh(this, true);
  31859. geometry.applyToMesh(this);
  31860. return this;
  31861. };
  31862. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31863. if (totalVertices === void 0) { totalVertices = null; }
  31864. if (updatable === void 0) { updatable = false; }
  31865. if (!this._geometry) {
  31866. var vertexData = new BABYLON.VertexData();
  31867. vertexData.indices = indices;
  31868. var scene = this.getScene();
  31869. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31870. }
  31871. else {
  31872. this._geometry.setIndices(indices, totalVertices, updatable);
  31873. }
  31874. return this;
  31875. };
  31876. /**
  31877. * Update the current index buffer
  31878. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31879. * Returns the Mesh.
  31880. */
  31881. Mesh.prototype.updateIndices = function (indices, offset) {
  31882. if (!this._geometry) {
  31883. return this;
  31884. }
  31885. this._geometry.updateIndices(indices, offset);
  31886. return this;
  31887. };
  31888. /**
  31889. * Invert the geometry to move from a right handed system to a left handed one.
  31890. * Returns the Mesh.
  31891. */
  31892. Mesh.prototype.toLeftHanded = function () {
  31893. if (!this._geometry) {
  31894. return this;
  31895. }
  31896. this._geometry.toLeftHanded();
  31897. return this;
  31898. };
  31899. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31900. if (!this._geometry) {
  31901. return this;
  31902. }
  31903. var engine = this.getScene().getEngine();
  31904. // Wireframe
  31905. var indexToBind;
  31906. if (this._unIndexed) {
  31907. indexToBind = null;
  31908. }
  31909. else {
  31910. switch (fillMode) {
  31911. case BABYLON.Material.PointFillMode:
  31912. indexToBind = null;
  31913. break;
  31914. case BABYLON.Material.WireFrameFillMode:
  31915. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31916. break;
  31917. default:
  31918. case BABYLON.Material.TriangleFillMode:
  31919. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31920. break;
  31921. }
  31922. }
  31923. // VBOs
  31924. this._geometry._bind(effect, indexToBind);
  31925. return this;
  31926. };
  31927. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31928. if (alternate === void 0) { alternate = false; }
  31929. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31930. return this;
  31931. }
  31932. this.onBeforeDrawObservable.notifyObservers(this);
  31933. var scene = this.getScene();
  31934. var engine = scene.getEngine();
  31935. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31936. // or triangles as points
  31937. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31938. }
  31939. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31940. // Triangles as wireframe
  31941. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31942. }
  31943. else {
  31944. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31945. }
  31946. if (scene._isAlternateRenderingEnabled && !alternate) {
  31947. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31948. if (!effect || !scene.activeCamera) {
  31949. return this;
  31950. }
  31951. scene._switchToAlternateCameraConfiguration(true);
  31952. this._effectiveMaterial.bindView(effect);
  31953. this._effectiveMaterial.bindViewProjection(effect);
  31954. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31955. this._draw(subMesh, fillMode, instancesCount, true);
  31956. engine.setViewport(scene.activeCamera.viewport);
  31957. scene._switchToAlternateCameraConfiguration(false);
  31958. this._effectiveMaterial.bindView(effect);
  31959. this._effectiveMaterial.bindViewProjection(effect);
  31960. }
  31961. return this;
  31962. };
  31963. /**
  31964. * Registers for this mesh a javascript function called just before the rendering process.
  31965. * This function is passed the current mesh.
  31966. * Return the Mesh.
  31967. */
  31968. Mesh.prototype.registerBeforeRender = function (func) {
  31969. this.onBeforeRenderObservable.add(func);
  31970. return this;
  31971. };
  31972. /**
  31973. * Disposes a previously registered javascript function called before the rendering.
  31974. * This function is passed the current mesh.
  31975. * Returns the Mesh.
  31976. */
  31977. Mesh.prototype.unregisterBeforeRender = function (func) {
  31978. this.onBeforeRenderObservable.removeCallback(func);
  31979. return this;
  31980. };
  31981. /**
  31982. * Registers for this mesh a javascript function called just after the rendering is complete.
  31983. * This function is passed the current mesh.
  31984. * Returns the Mesh.
  31985. */
  31986. Mesh.prototype.registerAfterRender = function (func) {
  31987. this.onAfterRenderObservable.add(func);
  31988. return this;
  31989. };
  31990. /**
  31991. * Disposes a previously registered javascript function called after the rendering.
  31992. * This function is passed the current mesh.
  31993. * Return the Mesh.
  31994. */
  31995. Mesh.prototype.unregisterAfterRender = function (func) {
  31996. this.onAfterRenderObservable.removeCallback(func);
  31997. return this;
  31998. };
  31999. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32000. var scene = this.getScene();
  32001. this._batchCache.mustReturn = false;
  32002. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32003. this._batchCache.visibleInstances[subMeshId] = null;
  32004. if (this._visibleInstances) {
  32005. var currentRenderId = scene.getRenderId();
  32006. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32007. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32008. var selfRenderId = this._renderId;
  32009. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32010. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32011. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32012. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32013. }
  32014. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32015. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32016. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32017. this._batchCache.mustReturn = true;
  32018. return this._batchCache;
  32019. }
  32020. if (currentRenderId !== selfRenderId) {
  32021. this._batchCache.renderSelf[subMeshId] = false;
  32022. }
  32023. }
  32024. this._renderIdForInstances[subMeshId] = currentRenderId;
  32025. }
  32026. return this._batchCache;
  32027. };
  32028. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32029. var visibleInstances = batch.visibleInstances[subMesh._id];
  32030. if (!visibleInstances) {
  32031. return this;
  32032. }
  32033. var matricesCount = visibleInstances.length + 1;
  32034. var bufferSize = matricesCount * 16 * 4;
  32035. var currentInstancesBufferSize = this._instancesBufferSize;
  32036. var instancesBuffer = this._instancesBuffer;
  32037. while (this._instancesBufferSize < bufferSize) {
  32038. this._instancesBufferSize *= 2;
  32039. }
  32040. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32041. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32042. }
  32043. var offset = 0;
  32044. var instancesCount = 0;
  32045. var world = this.getWorldMatrix();
  32046. if (batch.renderSelf[subMesh._id]) {
  32047. world.copyToArray(this._instancesData, offset);
  32048. offset += 16;
  32049. instancesCount++;
  32050. }
  32051. if (visibleInstances) {
  32052. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32053. var instance = visibleInstances[instanceIndex];
  32054. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32055. offset += 16;
  32056. instancesCount++;
  32057. }
  32058. }
  32059. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32060. if (instancesBuffer) {
  32061. instancesBuffer.dispose();
  32062. }
  32063. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32064. this._instancesBuffer = instancesBuffer;
  32065. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32066. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32067. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32068. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32069. }
  32070. else {
  32071. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32072. }
  32073. this._bind(subMesh, effect, fillMode);
  32074. this._draw(subMesh, fillMode, instancesCount);
  32075. engine.unbindInstanceAttributes();
  32076. return this;
  32077. };
  32078. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32079. var scene = this.getScene();
  32080. var engine = scene.getEngine();
  32081. if (hardwareInstancedRendering) {
  32082. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32083. }
  32084. else {
  32085. if (batch.renderSelf[subMesh._id]) {
  32086. // Draw
  32087. if (onBeforeDraw) {
  32088. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32089. }
  32090. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32091. }
  32092. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32093. if (visibleInstancesForSubMesh) {
  32094. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32095. var instance = visibleInstancesForSubMesh[instanceIndex];
  32096. // World
  32097. var world = instance.getWorldMatrix();
  32098. if (onBeforeDraw) {
  32099. onBeforeDraw(true, world, effectiveMaterial);
  32100. }
  32101. // Draw
  32102. this._draw(subMesh, fillMode);
  32103. }
  32104. }
  32105. }
  32106. return this;
  32107. };
  32108. /**
  32109. * Triggers the draw call for the mesh.
  32110. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32111. * Returns the Mesh.
  32112. */
  32113. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32114. this._checkOcclusionQuery();
  32115. if (this._isOccluded) {
  32116. return this;
  32117. }
  32118. var scene = this.getScene();
  32119. // Managing instances
  32120. var batch = this._getInstancesRenderList(subMesh._id);
  32121. if (batch.mustReturn) {
  32122. return this;
  32123. }
  32124. // Checking geometry state
  32125. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32126. return this;
  32127. }
  32128. this.onBeforeRenderObservable.notifyObservers(this);
  32129. var engine = scene.getEngine();
  32130. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32131. // Material
  32132. var material = subMesh.getMaterial();
  32133. if (!material) {
  32134. return this;
  32135. }
  32136. this._effectiveMaterial = material;
  32137. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32138. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32139. return this;
  32140. }
  32141. }
  32142. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32143. return this;
  32144. }
  32145. // Alpha mode
  32146. if (enableAlphaMode) {
  32147. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32148. }
  32149. // Outline - step 1
  32150. var savedDepthWrite = engine.getDepthWrite();
  32151. if (this.renderOutline) {
  32152. engine.setDepthWrite(false);
  32153. scene.getOutlineRenderer().render(subMesh, batch);
  32154. engine.setDepthWrite(savedDepthWrite);
  32155. }
  32156. var effect;
  32157. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32158. effect = subMesh.effect;
  32159. }
  32160. else {
  32161. effect = this._effectiveMaterial.getEffect();
  32162. }
  32163. if (!effect) {
  32164. return this;
  32165. }
  32166. var sideOrientation = this.overrideMaterialSideOrientation;
  32167. if (sideOrientation == null) {
  32168. sideOrientation = this._effectiveMaterial.sideOrientation;
  32169. if (this._getWorldMatrixDeterminant() < 0) {
  32170. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32171. }
  32172. }
  32173. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32174. if (this._effectiveMaterial.forceDepthWrite) {
  32175. engine.setDepthWrite(true);
  32176. }
  32177. // Bind
  32178. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32179. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32180. this._bind(subMesh, effect, fillMode);
  32181. }
  32182. var world = this.getWorldMatrix();
  32183. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32184. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32185. }
  32186. else {
  32187. this._effectiveMaterial.bind(world, this);
  32188. }
  32189. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32190. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32191. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32192. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32193. }
  32194. // Draw
  32195. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32196. // Unbind
  32197. this._effectiveMaterial.unbind();
  32198. // Outline - step 2
  32199. if (this.renderOutline && savedDepthWrite) {
  32200. engine.setDepthWrite(true);
  32201. engine.setColorWrite(false);
  32202. scene.getOutlineRenderer().render(subMesh, batch);
  32203. engine.setColorWrite(true);
  32204. }
  32205. // Overlay
  32206. if (this.renderOverlay) {
  32207. var currentMode = engine.getAlphaMode();
  32208. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32209. scene.getOutlineRenderer().render(subMesh, batch, true);
  32210. engine.setAlphaMode(currentMode);
  32211. }
  32212. this.onAfterRenderObservable.notifyObservers(this);
  32213. return this;
  32214. };
  32215. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32216. if (isInstance && effectiveMaterial) {
  32217. effectiveMaterial.bindOnlyWorldMatrix(world);
  32218. }
  32219. };
  32220. /**
  32221. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32222. */
  32223. Mesh.prototype.getEmittedParticleSystems = function () {
  32224. var results = new Array();
  32225. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32226. var particleSystem = this.getScene().particleSystems[index];
  32227. if (particleSystem.emitter === this) {
  32228. results.push(particleSystem);
  32229. }
  32230. }
  32231. return results;
  32232. };
  32233. /**
  32234. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32235. */
  32236. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32237. var results = new Array();
  32238. var descendants = this.getDescendants();
  32239. descendants.push(this);
  32240. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32241. var particleSystem = this.getScene().particleSystems[index];
  32242. var emitter = particleSystem.emitter;
  32243. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32244. results.push(particleSystem);
  32245. }
  32246. }
  32247. return results;
  32248. };
  32249. /**
  32250. * Normalize matrix weights so that all vertices have a total weight set to 1
  32251. */
  32252. Mesh.prototype.cleanMatrixWeights = function () {
  32253. var epsilon = 1e-3;
  32254. var noInfluenceBoneIndex = 0.0;
  32255. if (this.skeleton) {
  32256. noInfluenceBoneIndex = this.skeleton.bones.length;
  32257. }
  32258. else {
  32259. return;
  32260. }
  32261. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32262. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32263. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32264. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32265. var influencers = this.numBoneInfluencers;
  32266. var size = matricesWeights.length;
  32267. for (var i = 0; i < size; i += 4) {
  32268. var weight = 0.0;
  32269. var firstZeroWeight = -1;
  32270. for (var j = 0; j < 4; j++) {
  32271. var w = matricesWeights[i + j];
  32272. weight += w;
  32273. if (w < epsilon && firstZeroWeight < 0) {
  32274. firstZeroWeight = j;
  32275. }
  32276. }
  32277. if (matricesWeightsExtra) {
  32278. for (var j = 0; j < 4; j++) {
  32279. var w = matricesWeightsExtra[i + j];
  32280. weight += w;
  32281. if (w < epsilon && firstZeroWeight < 0) {
  32282. firstZeroWeight = j + 4;
  32283. }
  32284. }
  32285. }
  32286. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32287. firstZeroWeight = influencers - 1;
  32288. }
  32289. if (weight > epsilon) {
  32290. var mweight = 1.0 / weight;
  32291. for (var j = 0; j < 4; j++) {
  32292. matricesWeights[i + j] *= mweight;
  32293. }
  32294. if (matricesWeightsExtra) {
  32295. for (var j = 0; j < 4; j++) {
  32296. matricesWeightsExtra[i + j] *= mweight;
  32297. }
  32298. }
  32299. }
  32300. else {
  32301. if (firstZeroWeight >= 4) {
  32302. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32303. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32304. }
  32305. else {
  32306. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32307. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32308. }
  32309. }
  32310. }
  32311. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32312. if (matricesIndicesExtra) {
  32313. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32314. }
  32315. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32316. if (matricesWeightsExtra) {
  32317. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32318. }
  32319. };
  32320. Mesh.prototype._checkDelayState = function () {
  32321. var scene = this.getScene();
  32322. if (this._geometry) {
  32323. this._geometry.load(scene);
  32324. }
  32325. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32327. this._queueLoad(scene);
  32328. }
  32329. return this;
  32330. };
  32331. Mesh.prototype._queueLoad = function (scene) {
  32332. var _this = this;
  32333. scene._addPendingData(this);
  32334. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32335. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32336. if (data instanceof ArrayBuffer) {
  32337. _this._delayLoadingFunction(data, _this);
  32338. }
  32339. else {
  32340. _this._delayLoadingFunction(JSON.parse(data), _this);
  32341. }
  32342. _this.instances.forEach(function (instance) {
  32343. instance._syncSubMeshes();
  32344. });
  32345. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32346. scene._removePendingData(_this);
  32347. }, function () { }, scene.database, getBinaryData);
  32348. return this;
  32349. };
  32350. /**
  32351. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32352. */
  32353. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32354. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32355. return false;
  32356. }
  32357. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32358. return false;
  32359. }
  32360. this._checkDelayState();
  32361. return true;
  32362. };
  32363. /**
  32364. * Sets the mesh material by the material or multiMaterial `id` property.
  32365. * The material `id` is a string identifying the material or the multiMaterial.
  32366. * This method returns the Mesh.
  32367. */
  32368. Mesh.prototype.setMaterialByID = function (id) {
  32369. var materials = this.getScene().materials;
  32370. var index;
  32371. for (index = materials.length - 1; index > -1; index--) {
  32372. if (materials[index].id === id) {
  32373. this.material = materials[index];
  32374. return this;
  32375. }
  32376. }
  32377. // Multi
  32378. var multiMaterials = this.getScene().multiMaterials;
  32379. for (index = multiMaterials.length - 1; index > -1; index--) {
  32380. if (multiMaterials[index].id === id) {
  32381. this.material = multiMaterials[index];
  32382. return this;
  32383. }
  32384. }
  32385. return this;
  32386. };
  32387. /**
  32388. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32389. */
  32390. Mesh.prototype.getAnimatables = function () {
  32391. var results = new Array();
  32392. if (this.material) {
  32393. results.push(this.material);
  32394. }
  32395. if (this.skeleton) {
  32396. results.push(this.skeleton);
  32397. }
  32398. return results;
  32399. };
  32400. /**
  32401. * Modifies the mesh geometry according to the passed transformation matrix.
  32402. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32403. * The mesh normals are modified accordingly the same transformation.
  32404. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32405. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32406. * Returns the Mesh.
  32407. */
  32408. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32409. // Position
  32410. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32411. return this;
  32412. }
  32413. var submeshes = this.subMeshes.splice(0);
  32414. this._resetPointsArrayCache();
  32415. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32416. var temp = new Array();
  32417. var index;
  32418. for (index = 0; index < data.length; index += 3) {
  32419. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32420. }
  32421. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32422. // Normals
  32423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32424. return this;
  32425. }
  32426. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32427. temp = [];
  32428. for (index = 0; index < data.length; index += 3) {
  32429. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32430. }
  32431. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32432. // flip faces?
  32433. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32434. this.flipFaces();
  32435. }
  32436. // Restore submeshes
  32437. this.releaseSubMeshes();
  32438. this.subMeshes = submeshes;
  32439. return this;
  32440. };
  32441. /**
  32442. * Modifies the mesh geometry according to its own current World Matrix.
  32443. * The mesh World Matrix is then reset.
  32444. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32445. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32446. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32447. * Returns the Mesh.
  32448. */
  32449. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32450. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32451. this.scaling.copyFromFloats(1, 1, 1);
  32452. this.position.copyFromFloats(0, 0, 0);
  32453. this.rotation.copyFromFloats(0, 0, 0);
  32454. //only if quaternion is already set
  32455. if (this.rotationQuaternion) {
  32456. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32457. }
  32458. this._worldMatrix = BABYLON.Matrix.Identity();
  32459. return this;
  32460. };
  32461. Object.defineProperty(Mesh.prototype, "_positions", {
  32462. // Cache
  32463. get: function () {
  32464. if (this._geometry) {
  32465. return this._geometry._positions;
  32466. }
  32467. return null;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. Mesh.prototype._resetPointsArrayCache = function () {
  32473. if (this._geometry) {
  32474. this._geometry._resetPointsArrayCache();
  32475. }
  32476. return this;
  32477. };
  32478. Mesh.prototype._generatePointsArray = function () {
  32479. if (this._geometry) {
  32480. return this._geometry._generatePointsArray();
  32481. }
  32482. return false;
  32483. };
  32484. /**
  32485. * Returns a new Mesh object generated from the current mesh properties.
  32486. * This method must not get confused with createInstance().
  32487. * The parameter `name` is a string, the name given to the new mesh.
  32488. * The optional parameter `newParent` can be any Node object (default `null`).
  32489. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32490. * 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.
  32491. */
  32492. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32493. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32494. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32495. };
  32496. /**
  32497. * Releases resources associated with this mesh.
  32498. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32499. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32500. */
  32501. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32502. var _this = this;
  32503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32504. this.morphTargetManager = null;
  32505. if (this._geometry) {
  32506. this._geometry.releaseForMesh(this, true);
  32507. }
  32508. // Sources
  32509. var meshes = this.getScene().meshes;
  32510. meshes.forEach(function (abstractMesh) {
  32511. var mesh = abstractMesh;
  32512. if (mesh._source && mesh._source === _this) {
  32513. mesh._source = null;
  32514. }
  32515. });
  32516. this._source = null;
  32517. // Instances
  32518. if (this._instancesBuffer) {
  32519. this._instancesBuffer.dispose();
  32520. this._instancesBuffer = null;
  32521. }
  32522. while (this.instances.length) {
  32523. this.instances[0].dispose();
  32524. }
  32525. // Effect layers.
  32526. var effectLayers = this.getScene().effectLayers;
  32527. for (var i = 0; i < effectLayers.length; i++) {
  32528. var effectLayer = effectLayers[i];
  32529. if (effectLayer) {
  32530. effectLayer._disposeMesh(this);
  32531. }
  32532. }
  32533. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32534. };
  32535. /**
  32536. * Modifies the mesh geometry according to a displacement map.
  32537. * 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.
  32538. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32539. * This method returns nothing.
  32540. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32541. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32542. * 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.
  32543. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32544. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32545. *
  32546. * Returns the Mesh.
  32547. */
  32548. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32549. var _this = this;
  32550. var scene = this.getScene();
  32551. var onload = function (img) {
  32552. // Getting height map data
  32553. var canvas = document.createElement("canvas");
  32554. var context = canvas.getContext("2d");
  32555. var heightMapWidth = img.width;
  32556. var heightMapHeight = img.height;
  32557. canvas.width = heightMapWidth;
  32558. canvas.height = heightMapHeight;
  32559. context.drawImage(img, 0, 0);
  32560. // Create VertexData from map data
  32561. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32562. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32563. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32564. //execute success callback, if set
  32565. if (onSuccess) {
  32566. onSuccess(_this);
  32567. }
  32568. };
  32569. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32570. return this;
  32571. };
  32572. /**
  32573. * Modifies the mesh geometry according to a displacementMap buffer.
  32574. * 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.
  32575. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32576. * This method returns nothing.
  32577. * 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.
  32578. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32579. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32580. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32581. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32582. *
  32583. * Returns the Mesh.
  32584. */
  32585. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32586. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32587. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32588. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32589. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32590. return this;
  32591. }
  32592. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32593. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32594. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32595. var position = BABYLON.Vector3.Zero();
  32596. var normal = BABYLON.Vector3.Zero();
  32597. var uv = BABYLON.Vector2.Zero();
  32598. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32599. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32600. for (var index = 0; index < positions.length; index += 3) {
  32601. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32602. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32603. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32604. // Compute height
  32605. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32606. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32607. var pos = (u + v * heightMapWidth) * 4;
  32608. var r = buffer[pos] / 255.0;
  32609. var g = buffer[pos + 1] / 255.0;
  32610. var b = buffer[pos + 2] / 255.0;
  32611. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32612. normal.normalize();
  32613. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32614. position = position.add(normal);
  32615. position.toArray(positions, index);
  32616. }
  32617. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32618. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32619. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32620. return this;
  32621. };
  32622. /**
  32623. * Modify the mesh to get a flat shading rendering.
  32624. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32625. * This method returns the Mesh.
  32626. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32627. */
  32628. Mesh.prototype.convertToFlatShadedMesh = function () {
  32629. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32630. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32631. var kinds = this.getVerticesDataKinds();
  32632. var vbs = {};
  32633. var data = {};
  32634. var newdata = {};
  32635. var updatableNormals = false;
  32636. var kindIndex;
  32637. var kind;
  32638. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32639. kind = kinds[kindIndex];
  32640. var vertexBuffer = this.getVertexBuffer(kind);
  32641. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32642. updatableNormals = vertexBuffer.isUpdatable();
  32643. kinds.splice(kindIndex, 1);
  32644. kindIndex--;
  32645. continue;
  32646. }
  32647. vbs[kind] = vertexBuffer;
  32648. data[kind] = vbs[kind].getData();
  32649. newdata[kind] = [];
  32650. }
  32651. // Save previous submeshes
  32652. var previousSubmeshes = this.subMeshes.slice(0);
  32653. var indices = this.getIndices();
  32654. var totalIndices = this.getTotalIndices();
  32655. // Generating unique vertices per face
  32656. var index;
  32657. for (index = 0; index < totalIndices; index++) {
  32658. var vertexIndex = indices[index];
  32659. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32660. kind = kinds[kindIndex];
  32661. var stride = vbs[kind].getStrideSize();
  32662. for (var offset = 0; offset < stride; offset++) {
  32663. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32664. }
  32665. }
  32666. }
  32667. // Updating faces & normal
  32668. var normals = [];
  32669. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32670. for (index = 0; index < totalIndices; index += 3) {
  32671. indices[index] = index;
  32672. indices[index + 1] = index + 1;
  32673. indices[index + 2] = index + 2;
  32674. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32675. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32676. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32677. var p1p2 = p1.subtract(p2);
  32678. var p3p2 = p3.subtract(p2);
  32679. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32680. // Store same normals for every vertex
  32681. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32682. normals.push(normal.x);
  32683. normals.push(normal.y);
  32684. normals.push(normal.z);
  32685. }
  32686. }
  32687. this.setIndices(indices);
  32688. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32689. // Updating vertex buffers
  32690. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32691. kind = kinds[kindIndex];
  32692. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32693. }
  32694. // Updating submeshes
  32695. this.releaseSubMeshes();
  32696. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32697. var previousOne = previousSubmeshes[submeshIndex];
  32698. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32699. }
  32700. this.synchronizeInstances();
  32701. return this;
  32702. };
  32703. /**
  32704. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32705. * In other words, more vertices, no more indices and a single bigger VBO.
  32706. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32707. * Returns the Mesh.
  32708. */
  32709. Mesh.prototype.convertToUnIndexedMesh = function () {
  32710. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32711. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32712. var kinds = this.getVerticesDataKinds();
  32713. var vbs = {};
  32714. var data = {};
  32715. var newdata = {};
  32716. var kindIndex;
  32717. var kind;
  32718. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32719. kind = kinds[kindIndex];
  32720. var vertexBuffer = this.getVertexBuffer(kind);
  32721. vbs[kind] = vertexBuffer;
  32722. data[kind] = vbs[kind].getData();
  32723. newdata[kind] = [];
  32724. }
  32725. // Save previous submeshes
  32726. var previousSubmeshes = this.subMeshes.slice(0);
  32727. var indices = this.getIndices();
  32728. var totalIndices = this.getTotalIndices();
  32729. // Generating unique vertices per face
  32730. var index;
  32731. for (index = 0; index < totalIndices; index++) {
  32732. var vertexIndex = indices[index];
  32733. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32734. kind = kinds[kindIndex];
  32735. var stride = vbs[kind].getStrideSize();
  32736. for (var offset = 0; offset < stride; offset++) {
  32737. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32738. }
  32739. }
  32740. }
  32741. // Updating indices
  32742. for (index = 0; index < totalIndices; index += 3) {
  32743. indices[index] = index;
  32744. indices[index + 1] = index + 1;
  32745. indices[index + 2] = index + 2;
  32746. }
  32747. this.setIndices(indices);
  32748. // Updating vertex buffers
  32749. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32750. kind = kinds[kindIndex];
  32751. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32752. }
  32753. // Updating submeshes
  32754. this.releaseSubMeshes();
  32755. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32756. var previousOne = previousSubmeshes[submeshIndex];
  32757. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32758. }
  32759. this._unIndexed = true;
  32760. this.synchronizeInstances();
  32761. return this;
  32762. };
  32763. /**
  32764. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32765. * This method returns the Mesh.
  32766. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32767. */
  32768. Mesh.prototype.flipFaces = function (flipNormals) {
  32769. if (flipNormals === void 0) { flipNormals = false; }
  32770. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32771. var i;
  32772. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32773. for (i = 0; i < vertex_data.normals.length; i++) {
  32774. vertex_data.normals[i] *= -1;
  32775. }
  32776. }
  32777. if (vertex_data.indices) {
  32778. var temp;
  32779. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32780. // reassign indices
  32781. temp = vertex_data.indices[i + 1];
  32782. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32783. vertex_data.indices[i + 2] = temp;
  32784. }
  32785. }
  32786. vertex_data.applyToMesh(this);
  32787. return this;
  32788. };
  32789. // Instances
  32790. /**
  32791. * Creates a new InstancedMesh object from the mesh model.
  32792. * An instance shares the same properties and the same material than its model.
  32793. * Only these properties of each instance can then be set individually :
  32794. * - position
  32795. * - rotation
  32796. * - rotationQuaternion
  32797. * - setPivotMatrix
  32798. * - scaling
  32799. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32800. * Warning : this method is not supported for Line mesh and LineSystem
  32801. */
  32802. Mesh.prototype.createInstance = function (name) {
  32803. return new BABYLON.InstancedMesh(name, this);
  32804. };
  32805. /**
  32806. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32807. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32808. * This method returns the Mesh.
  32809. */
  32810. Mesh.prototype.synchronizeInstances = function () {
  32811. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32812. var instance = this.instances[instanceIndex];
  32813. instance._syncSubMeshes();
  32814. }
  32815. return this;
  32816. };
  32817. /**
  32818. * Simplify the mesh according to the given array of settings.
  32819. * Function will return immediately and will simplify async. It returns the Mesh.
  32820. * @param settings a collection of simplification settings.
  32821. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32822. * @param type the type of simplification to run.
  32823. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32824. */
  32825. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32826. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32827. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32828. this.getScene().simplificationQueue.addTask({
  32829. settings: settings,
  32830. parallelProcessing: parallelProcessing,
  32831. mesh: this,
  32832. simplificationType: simplificationType,
  32833. successCallback: successCallback
  32834. });
  32835. return this;
  32836. };
  32837. /**
  32838. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32839. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32840. * This should be used together with the simplification to avoid disappearing triangles.
  32841. * Returns the Mesh.
  32842. * @param successCallback an optional success callback to be called after the optimization finished.
  32843. */
  32844. Mesh.prototype.optimizeIndices = function (successCallback) {
  32845. var _this = this;
  32846. var indices = this.getIndices();
  32847. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32848. if (!positions || !indices) {
  32849. return this;
  32850. }
  32851. var vectorPositions = new Array();
  32852. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32853. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32854. }
  32855. var dupes = new Array();
  32856. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32857. var realPos = vectorPositions.length - 1 - iteration;
  32858. var testedPosition = vectorPositions[realPos];
  32859. for (var j = 0; j < realPos; ++j) {
  32860. var againstPosition = vectorPositions[j];
  32861. if (testedPosition.equals(againstPosition)) {
  32862. dupes[realPos] = j;
  32863. break;
  32864. }
  32865. }
  32866. }, function () {
  32867. for (var i = 0; i < indices.length; ++i) {
  32868. indices[i] = dupes[indices[i]] || indices[i];
  32869. }
  32870. //indices are now reordered
  32871. var originalSubMeshes = _this.subMeshes.slice(0);
  32872. _this.setIndices(indices);
  32873. _this.subMeshes = originalSubMeshes;
  32874. if (successCallback) {
  32875. successCallback(_this);
  32876. }
  32877. });
  32878. return this;
  32879. };
  32880. Mesh.prototype.serialize = function (serializationObject) {
  32881. serializationObject.name = this.name;
  32882. serializationObject.id = this.id;
  32883. serializationObject.type = this.getClassName();
  32884. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32885. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32886. }
  32887. serializationObject.position = this.position.asArray();
  32888. if (this.rotationQuaternion) {
  32889. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32890. }
  32891. else if (this.rotation) {
  32892. serializationObject.rotation = this.rotation.asArray();
  32893. }
  32894. serializationObject.scaling = this.scaling.asArray();
  32895. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32896. serializationObject.isEnabled = this.isEnabled(false);
  32897. serializationObject.isVisible = this.isVisible;
  32898. serializationObject.infiniteDistance = this.infiniteDistance;
  32899. serializationObject.pickable = this.isPickable;
  32900. serializationObject.receiveShadows = this.receiveShadows;
  32901. serializationObject.billboardMode = this.billboardMode;
  32902. serializationObject.visibility = this.visibility;
  32903. serializationObject.checkCollisions = this.checkCollisions;
  32904. serializationObject.isBlocker = this.isBlocker;
  32905. // Parent
  32906. if (this.parent) {
  32907. serializationObject.parentId = this.parent.id;
  32908. }
  32909. // Geometry
  32910. serializationObject.isUnIndexed = this.isUnIndexed;
  32911. var geometry = this._geometry;
  32912. if (geometry) {
  32913. var geometryId = geometry.id;
  32914. serializationObject.geometryId = geometryId;
  32915. // SubMeshes
  32916. serializationObject.subMeshes = [];
  32917. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32918. var subMesh = this.subMeshes[subIndex];
  32919. serializationObject.subMeshes.push({
  32920. materialIndex: subMesh.materialIndex,
  32921. verticesStart: subMesh.verticesStart,
  32922. verticesCount: subMesh.verticesCount,
  32923. indexStart: subMesh.indexStart,
  32924. indexCount: subMesh.indexCount
  32925. });
  32926. }
  32927. }
  32928. // Material
  32929. if (this.material) {
  32930. serializationObject.materialId = this.material.id;
  32931. }
  32932. else {
  32933. this.material = null;
  32934. }
  32935. // Morph targets
  32936. if (this.morphTargetManager) {
  32937. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32938. }
  32939. // Skeleton
  32940. if (this.skeleton) {
  32941. serializationObject.skeletonId = this.skeleton.id;
  32942. }
  32943. // Physics
  32944. //TODO implement correct serialization for physics impostors.
  32945. var impostor = this.getPhysicsImpostor();
  32946. if (impostor) {
  32947. serializationObject.physicsMass = impostor.getParam("mass");
  32948. serializationObject.physicsFriction = impostor.getParam("friction");
  32949. serializationObject.physicsRestitution = impostor.getParam("mass");
  32950. serializationObject.physicsImpostor = impostor.type;
  32951. }
  32952. // Metadata
  32953. if (this.metadata) {
  32954. serializationObject.metadata = this.metadata;
  32955. }
  32956. // Instances
  32957. serializationObject.instances = [];
  32958. for (var index = 0; index < this.instances.length; index++) {
  32959. var instance = this.instances[index];
  32960. var serializationInstance = {
  32961. name: instance.name,
  32962. id: instance.id,
  32963. position: instance.position.asArray(),
  32964. scaling: instance.scaling.asArray()
  32965. };
  32966. if (instance.rotationQuaternion) {
  32967. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32968. }
  32969. else if (instance.rotation) {
  32970. serializationInstance.rotation = instance.rotation.asArray();
  32971. }
  32972. serializationObject.instances.push(serializationInstance);
  32973. // Animations
  32974. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32975. serializationInstance.ranges = instance.serializeAnimationRanges();
  32976. }
  32977. //
  32978. // Animations
  32979. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32980. serializationObject.ranges = this.serializeAnimationRanges();
  32981. // Layer mask
  32982. serializationObject.layerMask = this.layerMask;
  32983. // Alpha
  32984. serializationObject.alphaIndex = this.alphaIndex;
  32985. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32986. // Overlay
  32987. serializationObject.overlayAlpha = this.overlayAlpha;
  32988. serializationObject.overlayColor = this.overlayColor.asArray();
  32989. serializationObject.renderOverlay = this.renderOverlay;
  32990. // Fog
  32991. serializationObject.applyFog = this.applyFog;
  32992. // Action Manager
  32993. if (this.actionManager) {
  32994. serializationObject.actions = this.actionManager.serialize(this.name);
  32995. }
  32996. };
  32997. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32998. if (!this.geometry) {
  32999. return;
  33000. }
  33001. this._markSubMeshesAsAttributesDirty();
  33002. var morphTargetManager = this._morphTargetManager;
  33003. if (morphTargetManager && morphTargetManager.vertexCount) {
  33004. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33005. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33006. this.morphTargetManager = null;
  33007. return;
  33008. }
  33009. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33010. var morphTarget = morphTargetManager.getActiveTarget(index);
  33011. var positions = morphTarget.getPositions();
  33012. if (!positions) {
  33013. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33014. return;
  33015. }
  33016. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33017. var normals = morphTarget.getNormals();
  33018. if (normals) {
  33019. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33020. }
  33021. var tangents = morphTarget.getTangents();
  33022. if (tangents) {
  33023. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33024. }
  33025. }
  33026. }
  33027. else {
  33028. var index = 0;
  33029. // Positions
  33030. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33031. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33032. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33033. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33034. }
  33035. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33036. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33037. }
  33038. index++;
  33039. }
  33040. }
  33041. };
  33042. // Statics
  33043. /**
  33044. * Returns a new Mesh object parsed from the source provided.
  33045. * The parameter `parsedMesh` is the source.
  33046. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33047. */
  33048. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33049. var mesh;
  33050. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33051. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33052. }
  33053. else {
  33054. mesh = new Mesh(parsedMesh.name, scene);
  33055. }
  33056. mesh.id = parsedMesh.id;
  33057. if (BABYLON.Tags) {
  33058. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33059. }
  33060. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33061. if (parsedMesh.metadata !== undefined) {
  33062. mesh.metadata = parsedMesh.metadata;
  33063. }
  33064. if (parsedMesh.rotationQuaternion) {
  33065. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33066. }
  33067. else if (parsedMesh.rotation) {
  33068. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33069. }
  33070. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33071. if (parsedMesh.localMatrix) {
  33072. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33073. }
  33074. else if (parsedMesh.pivotMatrix) {
  33075. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33076. }
  33077. mesh.setEnabled(parsedMesh.isEnabled);
  33078. mesh.isVisible = parsedMesh.isVisible;
  33079. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33080. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33081. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33082. if (parsedMesh.applyFog !== undefined) {
  33083. mesh.applyFog = parsedMesh.applyFog;
  33084. }
  33085. if (parsedMesh.pickable !== undefined) {
  33086. mesh.isPickable = parsedMesh.pickable;
  33087. }
  33088. if (parsedMesh.alphaIndex !== undefined) {
  33089. mesh.alphaIndex = parsedMesh.alphaIndex;
  33090. }
  33091. mesh.receiveShadows = parsedMesh.receiveShadows;
  33092. mesh.billboardMode = parsedMesh.billboardMode;
  33093. if (parsedMesh.visibility !== undefined) {
  33094. mesh.visibility = parsedMesh.visibility;
  33095. }
  33096. mesh.checkCollisions = parsedMesh.checkCollisions;
  33097. if (parsedMesh.isBlocker !== undefined) {
  33098. mesh.isBlocker = parsedMesh.isBlocker;
  33099. }
  33100. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33101. // freezeWorldMatrix
  33102. if (parsedMesh.freezeWorldMatrix) {
  33103. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33104. }
  33105. // Parent
  33106. if (parsedMesh.parentId) {
  33107. mesh._waitingParentId = parsedMesh.parentId;
  33108. }
  33109. // Actions
  33110. if (parsedMesh.actions !== undefined) {
  33111. mesh._waitingActions = parsedMesh.actions;
  33112. }
  33113. // Overlay
  33114. if (parsedMesh.overlayAlpha !== undefined) {
  33115. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33116. }
  33117. if (parsedMesh.overlayColor !== undefined) {
  33118. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33119. }
  33120. if (parsedMesh.renderOverlay !== undefined) {
  33121. mesh.renderOverlay = parsedMesh.renderOverlay;
  33122. }
  33123. // Geometry
  33124. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33125. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33126. if (parsedMesh.delayLoadingFile) {
  33127. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33128. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33129. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33130. if (parsedMesh._binaryInfo) {
  33131. mesh._binaryInfo = parsedMesh._binaryInfo;
  33132. }
  33133. mesh._delayInfo = [];
  33134. if (parsedMesh.hasUVs) {
  33135. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33136. }
  33137. if (parsedMesh.hasUVs2) {
  33138. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33139. }
  33140. if (parsedMesh.hasUVs3) {
  33141. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33142. }
  33143. if (parsedMesh.hasUVs4) {
  33144. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33145. }
  33146. if (parsedMesh.hasUVs5) {
  33147. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33148. }
  33149. if (parsedMesh.hasUVs6) {
  33150. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33151. }
  33152. if (parsedMesh.hasColors) {
  33153. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33154. }
  33155. if (parsedMesh.hasMatricesIndices) {
  33156. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33157. }
  33158. if (parsedMesh.hasMatricesWeights) {
  33159. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33160. }
  33161. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33162. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33163. mesh._checkDelayState();
  33164. }
  33165. }
  33166. else {
  33167. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33168. }
  33169. // Material
  33170. if (parsedMesh.materialId) {
  33171. mesh.setMaterialByID(parsedMesh.materialId);
  33172. }
  33173. else {
  33174. mesh.material = null;
  33175. }
  33176. // Morph targets
  33177. if (parsedMesh.morphTargetManagerId > -1) {
  33178. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33179. }
  33180. // Skeleton
  33181. if (parsedMesh.skeletonId > -1) {
  33182. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33183. if (parsedMesh.numBoneInfluencers) {
  33184. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33185. }
  33186. }
  33187. // Animations
  33188. if (parsedMesh.animations) {
  33189. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33190. var parsedAnimation = parsedMesh.animations[animationIndex];
  33191. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33192. }
  33193. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33194. }
  33195. if (parsedMesh.autoAnimate) {
  33196. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33197. }
  33198. // Layer Mask
  33199. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33200. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33201. }
  33202. else {
  33203. mesh.layerMask = 0x0FFFFFFF;
  33204. }
  33205. // Physics
  33206. if (parsedMesh.physicsImpostor) {
  33207. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33208. mass: parsedMesh.physicsMass,
  33209. friction: parsedMesh.physicsFriction,
  33210. restitution: parsedMesh.physicsRestitution
  33211. }, scene);
  33212. }
  33213. // Instances
  33214. if (parsedMesh.instances) {
  33215. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33216. var parsedInstance = parsedMesh.instances[index];
  33217. var instance = mesh.createInstance(parsedInstance.name);
  33218. if (parsedInstance.id) {
  33219. instance.id = parsedInstance.id;
  33220. }
  33221. if (BABYLON.Tags) {
  33222. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33223. }
  33224. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33225. if (parsedInstance.parentId) {
  33226. instance._waitingParentId = parsedInstance.parentId;
  33227. }
  33228. if (parsedInstance.rotationQuaternion) {
  33229. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33230. }
  33231. else if (parsedInstance.rotation) {
  33232. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33233. }
  33234. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33235. instance.checkCollisions = mesh.checkCollisions;
  33236. if (parsedMesh.animations) {
  33237. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33238. parsedAnimation = parsedMesh.animations[animationIndex];
  33239. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33240. }
  33241. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33242. }
  33243. }
  33244. }
  33245. return mesh;
  33246. };
  33247. /**
  33248. * Creates a ribbon mesh.
  33249. * Please consider using the same method from the MeshBuilder class instead.
  33250. * 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.
  33251. *
  33252. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33253. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33254. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33255. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33256. * 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.
  33257. * 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.
  33258. * 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
  33259. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33260. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33262. */
  33263. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33264. if (closeArray === void 0) { closeArray = false; }
  33265. if (updatable === void 0) { updatable = false; }
  33266. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33267. pathArray: pathArray,
  33268. closeArray: closeArray,
  33269. closePath: closePath,
  33270. offset: offset,
  33271. updatable: updatable,
  33272. sideOrientation: sideOrientation,
  33273. instance: instance
  33274. }, scene);
  33275. };
  33276. /**
  33277. * Creates a plane polygonal mesh. By default, this is a disc.
  33278. * Please consider using the same method from the MeshBuilder class instead.
  33279. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33280. * 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.
  33281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33282. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33284. */
  33285. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33286. if (scene === void 0) { scene = null; }
  33287. var options = {
  33288. radius: radius,
  33289. tessellation: tessellation,
  33290. sideOrientation: sideOrientation,
  33291. updatable: updatable
  33292. };
  33293. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33294. };
  33295. /**
  33296. * Creates a box mesh.
  33297. * Please consider using the same method from the MeshBuilder class instead.
  33298. * The parameter `size` sets the size (float) of each box side (default 1).
  33299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33300. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33302. */
  33303. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33304. if (scene === void 0) { scene = null; }
  33305. var options = {
  33306. size: size,
  33307. sideOrientation: sideOrientation,
  33308. updatable: updatable
  33309. };
  33310. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33311. };
  33312. /**
  33313. * Creates a sphere mesh.
  33314. * Please consider using the same method from the MeshBuilder class instead.
  33315. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33316. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33318. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33319. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33320. */
  33321. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33322. var options = {
  33323. segments: segments,
  33324. diameterX: diameter,
  33325. diameterY: diameter,
  33326. diameterZ: diameter,
  33327. sideOrientation: sideOrientation,
  33328. updatable: updatable
  33329. };
  33330. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33331. };
  33332. /**
  33333. * Creates a cylinder or a cone mesh.
  33334. * Please consider using the same method from the MeshBuilder class instead.
  33335. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33336. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33337. * 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.
  33338. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33339. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33341. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33343. */
  33344. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33345. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33346. if (scene !== undefined) {
  33347. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33348. updatable = scene;
  33349. }
  33350. scene = subdivisions;
  33351. subdivisions = 1;
  33352. }
  33353. var options = {
  33354. height: height,
  33355. diameterTop: diameterTop,
  33356. diameterBottom: diameterBottom,
  33357. tessellation: tessellation,
  33358. subdivisions: subdivisions,
  33359. sideOrientation: sideOrientation,
  33360. updatable: updatable
  33361. };
  33362. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33363. };
  33364. // Torus (Code from SharpDX.org)
  33365. /**
  33366. * Creates a torus mesh.
  33367. * Please consider using the same method from the MeshBuilder class instead.
  33368. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33369. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33370. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33372. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33374. */
  33375. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33376. var options = {
  33377. diameter: diameter,
  33378. thickness: thickness,
  33379. tessellation: tessellation,
  33380. sideOrientation: sideOrientation,
  33381. updatable: updatable
  33382. };
  33383. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33384. };
  33385. /**
  33386. * Creates a torus knot mesh.
  33387. * Please consider using the same method from the MeshBuilder class instead.
  33388. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33389. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33390. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33391. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33393. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33395. */
  33396. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33397. var options = {
  33398. radius: radius,
  33399. tube: tube,
  33400. radialSegments: radialSegments,
  33401. tubularSegments: tubularSegments,
  33402. p: p,
  33403. q: q,
  33404. sideOrientation: sideOrientation,
  33405. updatable: updatable
  33406. };
  33407. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33408. };
  33409. /**
  33410. * Creates a line mesh.
  33411. * Please consider using the same method from the MeshBuilder class instead.
  33412. * 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.
  33413. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33414. * The parameter `points` is an array successive Vector3.
  33415. * 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
  33416. * When updating an instance, remember that only point positions can change, not the number of points.
  33417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33418. */
  33419. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33420. if (scene === void 0) { scene = null; }
  33421. if (updatable === void 0) { updatable = false; }
  33422. if (instance === void 0) { instance = null; }
  33423. var options = {
  33424. points: points,
  33425. updatable: updatable,
  33426. instance: instance
  33427. };
  33428. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33429. };
  33430. /**
  33431. * Creates a dashed line mesh.
  33432. * Please consider using the same method from the MeshBuilder class instead.
  33433. * 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.
  33434. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33435. * The parameter `points` is an array successive Vector3.
  33436. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33437. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33438. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33439. * 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
  33440. * When updating an instance, remember that only point positions can change, not the number of points.
  33441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33442. */
  33443. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33444. if (scene === void 0) { scene = null; }
  33445. var options = {
  33446. points: points,
  33447. dashSize: dashSize,
  33448. gapSize: gapSize,
  33449. dashNb: dashNb,
  33450. updatable: updatable,
  33451. instance: instance
  33452. };
  33453. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33454. };
  33455. /**
  33456. * Creates a polygon mesh.
  33457. * Please consider using the same method from the MeshBuilder class instead.
  33458. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33459. * 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.
  33460. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33462. * Remember you can only change the shape positions, not their number when updating a polygon.
  33463. */
  33464. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33465. var options = {
  33466. shape: shape,
  33467. holes: holes,
  33468. updatable: updatable,
  33469. sideOrientation: sideOrientation
  33470. };
  33471. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33472. };
  33473. /**
  33474. * Creates an extruded polygon mesh, with depth in the Y direction.
  33475. * Please consider using the same method from the MeshBuilder class instead.
  33476. */
  33477. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33478. var options = {
  33479. shape: shape,
  33480. holes: holes,
  33481. depth: depth,
  33482. updatable: updatable,
  33483. sideOrientation: sideOrientation
  33484. };
  33485. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33486. };
  33487. /**
  33488. * Creates an extruded shape mesh.
  33489. * 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.
  33490. * Please consider using the same method from the MeshBuilder class instead.
  33491. *
  33492. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33493. * 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
  33494. * extruded along the Z axis.
  33495. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33496. * 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.
  33497. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33498. * 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
  33499. * 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
  33500. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33502. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33504. */
  33505. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33506. if (scene === void 0) { scene = null; }
  33507. var options = {
  33508. shape: shape,
  33509. path: path,
  33510. scale: scale,
  33511. rotation: rotation,
  33512. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33513. sideOrientation: sideOrientation,
  33514. instance: instance,
  33515. updatable: updatable
  33516. };
  33517. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33518. };
  33519. /**
  33520. * Creates an custom extruded shape mesh.
  33521. * 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.
  33522. * Please consider using the same method from the MeshBuilder class instead.
  33523. *
  33524. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33525. * 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
  33526. * extruded along the Z axis.
  33527. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33528. * 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
  33529. * and the distance of this point from the begining of the path :
  33530. * ```javascript
  33531. * var rotationFunction = function(i, distance) {
  33532. * // do things
  33533. * return rotationValue; }
  33534. * ```
  33535. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33536. * 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
  33537. * and the distance of this point from the begining of the path :
  33538. * ```javascript
  33539. * var scaleFunction = function(i, distance) {
  33540. * // do things
  33541. * return scaleValue;}
  33542. * ```
  33543. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33544. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33545. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33546. * 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
  33547. * 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
  33548. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33550. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33552. */
  33553. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33554. var options = {
  33555. shape: shape,
  33556. path: path,
  33557. scaleFunction: scaleFunction,
  33558. rotationFunction: rotationFunction,
  33559. ribbonCloseArray: ribbonCloseArray,
  33560. ribbonClosePath: ribbonClosePath,
  33561. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33562. sideOrientation: sideOrientation,
  33563. instance: instance,
  33564. updatable: updatable
  33565. };
  33566. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33567. };
  33568. /**
  33569. * Creates lathe mesh.
  33570. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33571. * Please consider using the same method from the MeshBuilder class instead.
  33572. * 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
  33573. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33574. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33575. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33577. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33579. */
  33580. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33581. var options = {
  33582. shape: shape,
  33583. radius: radius,
  33584. tessellation: tessellation,
  33585. sideOrientation: sideOrientation,
  33586. updatable: updatable
  33587. };
  33588. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33589. };
  33590. /**
  33591. * Creates a plane mesh.
  33592. * Please consider using the same method from the MeshBuilder class instead.
  33593. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33595. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33597. */
  33598. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33599. var options = {
  33600. size: size,
  33601. width: size,
  33602. height: size,
  33603. sideOrientation: sideOrientation,
  33604. updatable: updatable
  33605. };
  33606. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33607. };
  33608. /**
  33609. * Creates a ground mesh.
  33610. * Please consider using the same method from the MeshBuilder class instead.
  33611. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33612. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33614. */
  33615. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33616. var options = {
  33617. width: width,
  33618. height: height,
  33619. subdivisions: subdivisions,
  33620. updatable: updatable
  33621. };
  33622. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33623. };
  33624. /**
  33625. * Creates a tiled ground mesh.
  33626. * Please consider using the same method from the MeshBuilder class instead.
  33627. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33628. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33629. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33630. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33631. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33632. * numbers of subdivisions on the ground width and height of each tile.
  33633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33634. */
  33635. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33636. var options = {
  33637. xmin: xmin,
  33638. zmin: zmin,
  33639. xmax: xmax,
  33640. zmax: zmax,
  33641. subdivisions: subdivisions,
  33642. precision: precision,
  33643. updatable: updatable
  33644. };
  33645. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33646. };
  33647. /**
  33648. * Creates a ground mesh from a height map.
  33649. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33650. * Please consider using the same method from the MeshBuilder class instead.
  33651. * The parameter `url` sets the URL of the height map image resource.
  33652. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33653. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33654. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33655. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33656. * 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).
  33657. * This function is passed the newly built mesh :
  33658. * ```javascript
  33659. * function(mesh) { // do things
  33660. * return; }
  33661. * ```
  33662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33663. */
  33664. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33665. var options = {
  33666. width: width,
  33667. height: height,
  33668. subdivisions: subdivisions,
  33669. minHeight: minHeight,
  33670. maxHeight: maxHeight,
  33671. updatable: updatable,
  33672. onReady: onReady
  33673. };
  33674. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33675. };
  33676. /**
  33677. * Creates a tube mesh.
  33678. * 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.
  33679. * Please consider using the same method from the MeshBuilder class instead.
  33680. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33681. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33682. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33683. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33684. * 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.
  33685. * It must return a radius value (positive float) :
  33686. * ```javascript
  33687. * var radiusFunction = function(i, distance) {
  33688. * // do things
  33689. * return radius; }
  33690. * ```
  33691. * 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
  33692. * 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
  33693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33694. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33696. */
  33697. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33698. var options = {
  33699. path: path,
  33700. radius: radius,
  33701. tessellation: tessellation,
  33702. radiusFunction: radiusFunction,
  33703. arc: 1,
  33704. cap: cap,
  33705. updatable: updatable,
  33706. sideOrientation: sideOrientation,
  33707. instance: instance
  33708. };
  33709. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33710. };
  33711. /**
  33712. * Creates a polyhedron mesh.
  33713. * Please consider using the same method from the MeshBuilder class instead.
  33714. * 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
  33715. * to choose the wanted type.
  33716. * The parameter `size` (positive float, default 1) sets the polygon size.
  33717. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33718. * 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`.
  33719. * 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
  33720. * 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)`).
  33721. * 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
  33722. * 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.
  33723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33724. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33726. */
  33727. Mesh.CreatePolyhedron = function (name, options, scene) {
  33728. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33729. };
  33730. /**
  33731. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33732. * Please consider using the same method from the MeshBuilder class instead.
  33733. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33734. * 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`).
  33735. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33736. * 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.
  33737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33738. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33740. */
  33741. Mesh.CreateIcoSphere = function (name, options, scene) {
  33742. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33743. };
  33744. /**
  33745. * Creates a decal mesh.
  33746. * Please consider using the same method from the MeshBuilder class instead.
  33747. * 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.
  33748. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33749. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33750. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33751. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33752. */
  33753. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33754. var options = {
  33755. position: position,
  33756. normal: normal,
  33757. size: size,
  33758. angle: angle
  33759. };
  33760. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33761. };
  33762. // Skeletons
  33763. /**
  33764. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33765. */
  33766. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33767. if (!this._sourcePositions) {
  33768. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33769. if (!source) {
  33770. return this._sourcePositions;
  33771. }
  33772. this._sourcePositions = new Float32Array(source);
  33773. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33774. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33775. }
  33776. }
  33777. return this._sourcePositions;
  33778. };
  33779. /**
  33780. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33781. */
  33782. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33783. if (!this._sourceNormals) {
  33784. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33785. if (!source) {
  33786. return this._sourceNormals;
  33787. }
  33788. this._sourceNormals = new Float32Array(source);
  33789. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33790. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33791. }
  33792. }
  33793. return this._sourceNormals;
  33794. };
  33795. /**
  33796. * Updates the vertex buffer by applying transformation from the bones.
  33797. * Returns the Mesh.
  33798. *
  33799. * @param {skeleton} skeleton to apply
  33800. */
  33801. Mesh.prototype.applySkeleton = function (skeleton) {
  33802. if (!this.geometry) {
  33803. return this;
  33804. }
  33805. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33806. return this;
  33807. }
  33808. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33809. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33810. return this;
  33811. }
  33812. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33813. return this;
  33814. }
  33815. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33816. return this;
  33817. }
  33818. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33819. return this;
  33820. }
  33821. if (!this._sourcePositions) {
  33822. var submeshes = this.subMeshes.slice();
  33823. this.setPositionsForCPUSkinning();
  33824. this.subMeshes = submeshes;
  33825. }
  33826. if (!this._sourceNormals) {
  33827. this.setNormalsForCPUSkinning();
  33828. }
  33829. // positionsData checks for not being Float32Array will only pass at most once
  33830. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33831. if (!positionsData) {
  33832. return this;
  33833. }
  33834. if (!(positionsData instanceof Float32Array)) {
  33835. positionsData = new Float32Array(positionsData);
  33836. }
  33837. // normalsData checks for not being Float32Array will only pass at most once
  33838. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33839. if (!normalsData) {
  33840. return this;
  33841. }
  33842. if (!(normalsData instanceof Float32Array)) {
  33843. normalsData = new Float32Array(normalsData);
  33844. }
  33845. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33846. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33847. if (!matricesWeightsData || !matricesIndicesData) {
  33848. return this;
  33849. }
  33850. var needExtras = this.numBoneInfluencers > 4;
  33851. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33852. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33853. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33854. var tempVector3 = BABYLON.Vector3.Zero();
  33855. var finalMatrix = new BABYLON.Matrix();
  33856. var tempMatrix = new BABYLON.Matrix();
  33857. var matWeightIdx = 0;
  33858. var inf;
  33859. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33860. var weight;
  33861. for (inf = 0; inf < 4; inf++) {
  33862. weight = matricesWeightsData[matWeightIdx + inf];
  33863. if (weight > 0) {
  33864. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33865. finalMatrix.addToSelf(tempMatrix);
  33866. }
  33867. else
  33868. break;
  33869. }
  33870. if (needExtras) {
  33871. for (inf = 0; inf < 4; inf++) {
  33872. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33873. if (weight > 0) {
  33874. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33875. finalMatrix.addToSelf(tempMatrix);
  33876. }
  33877. else
  33878. break;
  33879. }
  33880. }
  33881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33882. tempVector3.toArray(positionsData, index);
  33883. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33884. tempVector3.toArray(normalsData, index);
  33885. finalMatrix.reset();
  33886. }
  33887. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33888. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33889. return this;
  33890. };
  33891. // Tools
  33892. /**
  33893. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33894. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33895. */
  33896. Mesh.MinMax = function (meshes) {
  33897. var minVector = null;
  33898. var maxVector = null;
  33899. meshes.forEach(function (mesh, index, array) {
  33900. var boundingInfo = mesh.getBoundingInfo();
  33901. var boundingBox = boundingInfo.boundingBox;
  33902. if (!minVector || !maxVector) {
  33903. minVector = boundingBox.minimumWorld;
  33904. maxVector = boundingBox.maximumWorld;
  33905. }
  33906. else {
  33907. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33908. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33909. }
  33910. });
  33911. if (!minVector || !maxVector) {
  33912. return {
  33913. min: BABYLON.Vector3.Zero(),
  33914. max: BABYLON.Vector3.Zero()
  33915. };
  33916. }
  33917. return {
  33918. min: minVector,
  33919. max: maxVector
  33920. };
  33921. };
  33922. /**
  33923. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33924. */
  33925. Mesh.Center = function (meshesOrMinMaxVector) {
  33926. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33927. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33928. };
  33929. /**
  33930. * Merge the array of meshes into a single mesh for performance reasons.
  33931. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33932. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33933. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33934. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33935. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33936. */
  33937. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33938. if (disposeSource === void 0) { disposeSource = true; }
  33939. var index;
  33940. if (!allow32BitsIndices) {
  33941. var totalVertices = 0;
  33942. // Counting vertices
  33943. for (index = 0; index < meshes.length; index++) {
  33944. if (meshes[index]) {
  33945. totalVertices += meshes[index].getTotalVertices();
  33946. if (totalVertices > 65536) {
  33947. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33948. return null;
  33949. }
  33950. }
  33951. }
  33952. }
  33953. // Merge
  33954. var vertexData = null;
  33955. var otherVertexData;
  33956. var indiceArray = new Array();
  33957. var source = null;
  33958. for (index = 0; index < meshes.length; index++) {
  33959. if (meshes[index]) {
  33960. meshes[index].computeWorldMatrix(true);
  33961. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33962. otherVertexData.transform(meshes[index].getWorldMatrix());
  33963. if (vertexData) {
  33964. vertexData.merge(otherVertexData);
  33965. }
  33966. else {
  33967. vertexData = otherVertexData;
  33968. source = meshes[index];
  33969. }
  33970. if (subdivideWithSubMeshes) {
  33971. indiceArray.push(meshes[index].getTotalIndices());
  33972. }
  33973. }
  33974. }
  33975. source = source;
  33976. if (!meshSubclass) {
  33977. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33978. }
  33979. vertexData.applyToMesh(meshSubclass);
  33980. // Setting properties
  33981. meshSubclass.material = source.material;
  33982. meshSubclass.checkCollisions = source.checkCollisions;
  33983. // Cleaning
  33984. if (disposeSource) {
  33985. for (index = 0; index < meshes.length; index++) {
  33986. if (meshes[index]) {
  33987. meshes[index].dispose();
  33988. }
  33989. }
  33990. }
  33991. // Subdivide
  33992. if (subdivideWithSubMeshes) {
  33993. //-- Suppresions du submesh global
  33994. meshSubclass.releaseSubMeshes();
  33995. index = 0;
  33996. var offset = 0;
  33997. //-- aplique la subdivision en fonction du tableau d'indices
  33998. while (index < indiceArray.length) {
  33999. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34000. offset += indiceArray[index];
  34001. index++;
  34002. }
  34003. }
  34004. return meshSubclass;
  34005. };
  34006. // Consts
  34007. Mesh._FRONTSIDE = 0;
  34008. Mesh._BACKSIDE = 1;
  34009. Mesh._DOUBLESIDE = 2;
  34010. Mesh._DEFAULTSIDE = 0;
  34011. Mesh._NO_CAP = 0;
  34012. Mesh._CAP_START = 1;
  34013. Mesh._CAP_END = 2;
  34014. Mesh._CAP_ALL = 3;
  34015. return Mesh;
  34016. }(BABYLON.AbstractMesh));
  34017. BABYLON.Mesh = Mesh;
  34018. })(BABYLON || (BABYLON = {}));
  34019. //# sourceMappingURL=babylon.mesh.js.map
  34020. var BABYLON;
  34021. (function (BABYLON) {
  34022. var BaseSubMesh = /** @class */ (function () {
  34023. function BaseSubMesh() {
  34024. }
  34025. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34026. get: function () {
  34027. return this._materialEffect;
  34028. },
  34029. enumerable: true,
  34030. configurable: true
  34031. });
  34032. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34033. if (defines === void 0) { defines = null; }
  34034. if (this._materialEffect === effect) {
  34035. if (!effect) {
  34036. this._materialDefines = null;
  34037. }
  34038. return;
  34039. }
  34040. this._materialDefines = defines;
  34041. this._materialEffect = effect;
  34042. };
  34043. return BaseSubMesh;
  34044. }());
  34045. BABYLON.BaseSubMesh = BaseSubMesh;
  34046. var SubMesh = /** @class */ (function (_super) {
  34047. __extends(SubMesh, _super);
  34048. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34049. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34050. var _this = _super.call(this) || this;
  34051. _this.materialIndex = materialIndex;
  34052. _this.verticesStart = verticesStart;
  34053. _this.verticesCount = verticesCount;
  34054. _this.indexStart = indexStart;
  34055. _this.indexCount = indexCount;
  34056. _this._renderId = 0;
  34057. _this._mesh = mesh;
  34058. _this._renderingMesh = renderingMesh || mesh;
  34059. mesh.subMeshes.push(_this);
  34060. _this._trianglePlanes = [];
  34061. _this._id = mesh.subMeshes.length - 1;
  34062. if (createBoundingBox) {
  34063. _this.refreshBoundingInfo();
  34064. mesh.computeWorldMatrix(true);
  34065. }
  34066. return _this;
  34067. }
  34068. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34069. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34070. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34071. };
  34072. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34073. get: function () {
  34074. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34075. },
  34076. enumerable: true,
  34077. configurable: true
  34078. });
  34079. /**
  34080. * Returns the submesh BoudingInfo object.
  34081. */
  34082. SubMesh.prototype.getBoundingInfo = function () {
  34083. if (this.IsGlobal) {
  34084. return this._mesh.getBoundingInfo();
  34085. }
  34086. return this._boundingInfo;
  34087. };
  34088. /**
  34089. * Sets the submesh BoundingInfo.
  34090. * Return the SubMesh.
  34091. */
  34092. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34093. this._boundingInfo = boundingInfo;
  34094. return this;
  34095. };
  34096. /**
  34097. * Returns the mesh of the current submesh.
  34098. */
  34099. SubMesh.prototype.getMesh = function () {
  34100. return this._mesh;
  34101. };
  34102. /**
  34103. * Returns the rendering mesh of the submesh.
  34104. */
  34105. SubMesh.prototype.getRenderingMesh = function () {
  34106. return this._renderingMesh;
  34107. };
  34108. /**
  34109. * Returns the submesh material.
  34110. */
  34111. SubMesh.prototype.getMaterial = function () {
  34112. var rootMaterial = this._renderingMesh.material;
  34113. if (rootMaterial === null || rootMaterial === undefined) {
  34114. return this._mesh.getScene().defaultMaterial;
  34115. }
  34116. else if (rootMaterial.getSubMaterial) {
  34117. var multiMaterial = rootMaterial;
  34118. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34119. if (this._currentMaterial !== effectiveMaterial) {
  34120. this._currentMaterial = effectiveMaterial;
  34121. this._materialDefines = null;
  34122. }
  34123. return effectiveMaterial;
  34124. }
  34125. return rootMaterial;
  34126. };
  34127. // Methods
  34128. /**
  34129. * Sets a new updated BoundingInfo object to the submesh.
  34130. * Returns the SubMesh.
  34131. */
  34132. SubMesh.prototype.refreshBoundingInfo = function () {
  34133. this._lastColliderWorldVertices = null;
  34134. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34135. return this;
  34136. }
  34137. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34138. if (!data) {
  34139. this._boundingInfo = this._mesh.getBoundingInfo();
  34140. return this;
  34141. }
  34142. var indices = this._renderingMesh.getIndices();
  34143. var extend;
  34144. //is this the only submesh?
  34145. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34146. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34147. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34148. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34149. }
  34150. else {
  34151. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34152. }
  34153. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34154. return this;
  34155. };
  34156. SubMesh.prototype._checkCollision = function (collider) {
  34157. var boundingInfo = this.getBoundingInfo();
  34158. return boundingInfo._checkCollision(collider);
  34159. };
  34160. /**
  34161. * Updates the submesh BoundingInfo.
  34162. * Returns the Submesh.
  34163. */
  34164. SubMesh.prototype.updateBoundingInfo = function (world) {
  34165. var boundingInfo = this.getBoundingInfo();
  34166. if (!boundingInfo) {
  34167. this.refreshBoundingInfo();
  34168. boundingInfo = this.getBoundingInfo();
  34169. }
  34170. boundingInfo.update(world);
  34171. return this;
  34172. };
  34173. /**
  34174. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34175. * Boolean returned.
  34176. */
  34177. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34178. var boundingInfo = this.getBoundingInfo();
  34179. if (!boundingInfo) {
  34180. return false;
  34181. }
  34182. return boundingInfo.isInFrustum(frustumPlanes);
  34183. };
  34184. /**
  34185. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34186. * Boolean returned.
  34187. */
  34188. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34189. var boundingInfo = this.getBoundingInfo();
  34190. if (!boundingInfo) {
  34191. return false;
  34192. }
  34193. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34194. };
  34195. /**
  34196. * Renders the submesh.
  34197. * Returns it.
  34198. */
  34199. SubMesh.prototype.render = function (enableAlphaMode) {
  34200. this._renderingMesh.render(this, enableAlphaMode);
  34201. return this;
  34202. };
  34203. /**
  34204. * Returns a new Index Buffer.
  34205. * Type returned : WebGLBuffer.
  34206. */
  34207. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34208. if (!this._linesIndexBuffer) {
  34209. var linesIndices = [];
  34210. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34211. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34212. }
  34213. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34214. this.linesIndexCount = linesIndices.length;
  34215. }
  34216. return this._linesIndexBuffer;
  34217. };
  34218. /**
  34219. * True is the passed Ray intersects the submesh bounding box.
  34220. * Boolean returned.
  34221. */
  34222. SubMesh.prototype.canIntersects = function (ray) {
  34223. var boundingInfo = this.getBoundingInfo();
  34224. if (!boundingInfo) {
  34225. return false;
  34226. }
  34227. return ray.intersectsBox(boundingInfo.boundingBox);
  34228. };
  34229. /**
  34230. * Returns an object IntersectionInfo.
  34231. */
  34232. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34233. var intersectInfo = null;
  34234. var material = this.getMaterial();
  34235. if (!material) {
  34236. return null;
  34237. }
  34238. switch (material.fillMode) {
  34239. case BABYLON.Material.PointListDrawMode:
  34240. case BABYLON.Material.LineListDrawMode:
  34241. case BABYLON.Material.LineLoopDrawMode:
  34242. case BABYLON.Material.LineStripDrawMode:
  34243. case BABYLON.Material.TriangleFanDrawMode:
  34244. case BABYLON.Material.TriangleStripDrawMode:
  34245. return null;
  34246. }
  34247. // LineMesh first as it's also a Mesh...
  34248. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34249. var lineMesh = this._mesh;
  34250. // Line test
  34251. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34252. var p0 = positions[indices[index]];
  34253. var p1 = positions[indices[index + 1]];
  34254. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34255. if (length < 0) {
  34256. continue;
  34257. }
  34258. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34259. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34260. if (fastCheck) {
  34261. break;
  34262. }
  34263. }
  34264. }
  34265. }
  34266. else {
  34267. // Triangles test
  34268. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34269. var p0 = positions[indices[index]];
  34270. var p1 = positions[indices[index + 1]];
  34271. var p2 = positions[indices[index + 2]];
  34272. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34273. if (currentIntersectInfo) {
  34274. if (currentIntersectInfo.distance < 0) {
  34275. continue;
  34276. }
  34277. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34278. intersectInfo = currentIntersectInfo;
  34279. intersectInfo.faceId = index / 3;
  34280. if (fastCheck) {
  34281. break;
  34282. }
  34283. }
  34284. }
  34285. }
  34286. }
  34287. return intersectInfo;
  34288. };
  34289. SubMesh.prototype._rebuild = function () {
  34290. if (this._linesIndexBuffer) {
  34291. this._linesIndexBuffer = null;
  34292. }
  34293. };
  34294. // Clone
  34295. /**
  34296. * Creates a new Submesh from the passed Mesh.
  34297. */
  34298. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34299. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34300. if (!this.IsGlobal) {
  34301. var boundingInfo = this.getBoundingInfo();
  34302. if (!boundingInfo) {
  34303. return result;
  34304. }
  34305. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34306. }
  34307. return result;
  34308. };
  34309. // Dispose
  34310. /**
  34311. * Disposes the Submesh.
  34312. * Returns nothing.
  34313. */
  34314. SubMesh.prototype.dispose = function () {
  34315. if (this._linesIndexBuffer) {
  34316. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34317. this._linesIndexBuffer = null;
  34318. }
  34319. // Remove from mesh
  34320. var index = this._mesh.subMeshes.indexOf(this);
  34321. this._mesh.subMeshes.splice(index, 1);
  34322. };
  34323. // Statics
  34324. /**
  34325. * Creates a new Submesh from the passed parameters :
  34326. * - materialIndex (integer) : the index of the main mesh material.
  34327. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34328. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34329. * - mesh (Mesh) : the main mesh to create the submesh from.
  34330. * - renderingMesh (optional Mesh) : rendering mesh.
  34331. */
  34332. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34333. var minVertexIndex = Number.MAX_VALUE;
  34334. var maxVertexIndex = -Number.MAX_VALUE;
  34335. renderingMesh = (renderingMesh || mesh);
  34336. var indices = renderingMesh.getIndices();
  34337. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34338. var vertexIndex = indices[index];
  34339. if (vertexIndex < minVertexIndex)
  34340. minVertexIndex = vertexIndex;
  34341. if (vertexIndex > maxVertexIndex)
  34342. maxVertexIndex = vertexIndex;
  34343. }
  34344. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34345. };
  34346. return SubMesh;
  34347. }(BaseSubMesh));
  34348. BABYLON.SubMesh = SubMesh;
  34349. })(BABYLON || (BABYLON = {}));
  34350. //# sourceMappingURL=babylon.subMesh.js.map
  34351. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34352. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34353. s = arguments[i];
  34354. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34355. t[p] = s[p];
  34356. }
  34357. return t;
  34358. };
  34359. var BABYLON;
  34360. (function (BABYLON) {
  34361. /**
  34362. * Manages the defines for the Material
  34363. */
  34364. var MaterialDefines = /** @class */ (function () {
  34365. function MaterialDefines() {
  34366. this._isDirty = true;
  34367. /** @hidden */
  34368. this._areLightsDirty = true;
  34369. /** @hidden */
  34370. this._areAttributesDirty = true;
  34371. /** @hidden */
  34372. this._areTexturesDirty = true;
  34373. /** @hidden */
  34374. this._areFresnelDirty = true;
  34375. /** @hidden */
  34376. this._areMiscDirty = true;
  34377. /** @hidden */
  34378. this._areImageProcessingDirty = true;
  34379. /** @hidden */
  34380. this._normals = false;
  34381. /** @hidden */
  34382. this._uvs = false;
  34383. /** @hidden */
  34384. this._needNormals = false;
  34385. /** @hidden */
  34386. this._needUVs = false;
  34387. }
  34388. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34389. /**
  34390. * Specifies if the material needs to be re-calculated
  34391. */
  34392. get: function () {
  34393. return this._isDirty;
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. /**
  34399. * Marks the material to indicate that it has been re-calculated
  34400. */
  34401. MaterialDefines.prototype.markAsProcessed = function () {
  34402. this._isDirty = false;
  34403. this._areAttributesDirty = false;
  34404. this._areTexturesDirty = false;
  34405. this._areFresnelDirty = false;
  34406. this._areLightsDirty = false;
  34407. this._areMiscDirty = false;
  34408. this._areImageProcessingDirty = false;
  34409. };
  34410. /**
  34411. * Marks the material to indicate that it needs to be re-calculated
  34412. */
  34413. MaterialDefines.prototype.markAsUnprocessed = function () {
  34414. this._isDirty = true;
  34415. };
  34416. /**
  34417. * Marks the material to indicate all of its defines need to be re-calculated
  34418. */
  34419. MaterialDefines.prototype.markAllAsDirty = function () {
  34420. this._areTexturesDirty = true;
  34421. this._areAttributesDirty = true;
  34422. this._areLightsDirty = true;
  34423. this._areFresnelDirty = true;
  34424. this._areMiscDirty = true;
  34425. this._areImageProcessingDirty = true;
  34426. this._isDirty = true;
  34427. };
  34428. /**
  34429. * Marks the material to indicate that image processing needs to be re-calculated
  34430. */
  34431. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34432. this._areImageProcessingDirty = true;
  34433. this._isDirty = true;
  34434. };
  34435. /**
  34436. * Marks the material to indicate the lights need to be re-calculated
  34437. */
  34438. MaterialDefines.prototype.markAsLightDirty = function () {
  34439. this._areLightsDirty = true;
  34440. this._isDirty = true;
  34441. };
  34442. /**
  34443. * Marks the attribute state as changed
  34444. */
  34445. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34446. this._areAttributesDirty = true;
  34447. this._isDirty = true;
  34448. };
  34449. /**
  34450. * Marks the texture state as changed
  34451. */
  34452. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34453. this._areTexturesDirty = true;
  34454. this._isDirty = true;
  34455. };
  34456. /**
  34457. * Marks the fresnel state as changed
  34458. */
  34459. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34460. this._areFresnelDirty = true;
  34461. this._isDirty = true;
  34462. };
  34463. /**
  34464. * Marks the misc state as changed
  34465. */
  34466. MaterialDefines.prototype.markAsMiscDirty = function () {
  34467. this._areMiscDirty = true;
  34468. this._isDirty = true;
  34469. };
  34470. /**
  34471. * Rebuilds the material defines
  34472. */
  34473. MaterialDefines.prototype.rebuild = function () {
  34474. if (this._keys) {
  34475. delete this._keys;
  34476. }
  34477. this._keys = [];
  34478. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34479. var key = _a[_i];
  34480. if (key[0] === "_") {
  34481. continue;
  34482. }
  34483. this._keys.push(key);
  34484. }
  34485. };
  34486. /**
  34487. * Specifies if two material defines are equal
  34488. * @param other - A material define instance to compare to
  34489. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34490. */
  34491. MaterialDefines.prototype.isEqual = function (other) {
  34492. if (this._keys.length !== other._keys.length) {
  34493. return false;
  34494. }
  34495. for (var index = 0; index < this._keys.length; index++) {
  34496. var prop = this._keys[index];
  34497. if (this[prop] !== other[prop]) {
  34498. return false;
  34499. }
  34500. }
  34501. return true;
  34502. };
  34503. /**
  34504. * Clones this instance's defines to another instance
  34505. * @param other - material defines to clone values to
  34506. */
  34507. MaterialDefines.prototype.cloneTo = function (other) {
  34508. if (this._keys.length !== other._keys.length) {
  34509. other._keys = this._keys.slice(0);
  34510. }
  34511. for (var index = 0; index < this._keys.length; index++) {
  34512. var prop = this._keys[index];
  34513. other[prop] = this[prop];
  34514. }
  34515. };
  34516. /**
  34517. * Resets the material define values
  34518. */
  34519. MaterialDefines.prototype.reset = function () {
  34520. for (var index = 0; index < this._keys.length; index++) {
  34521. var prop = this._keys[index];
  34522. var type = typeof this[prop];
  34523. switch (type) {
  34524. case "number":
  34525. this[prop] = 0;
  34526. break;
  34527. case "string":
  34528. this[prop] = "";
  34529. break;
  34530. default:
  34531. this[prop] = false;
  34532. break;
  34533. }
  34534. }
  34535. };
  34536. /**
  34537. * Converts the material define values to a string
  34538. * @returns - String of material define information
  34539. */
  34540. MaterialDefines.prototype.toString = function () {
  34541. var result = "";
  34542. for (var index = 0; index < this._keys.length; index++) {
  34543. var prop = this._keys[index];
  34544. var value = this[prop];
  34545. var type = typeof value;
  34546. switch (type) {
  34547. case "number":
  34548. case "string":
  34549. result += "#define " + prop + " " + value + "\n";
  34550. break;
  34551. default:
  34552. if (value) {
  34553. result += "#define " + prop + "\n";
  34554. }
  34555. break;
  34556. }
  34557. }
  34558. return result;
  34559. };
  34560. return MaterialDefines;
  34561. }());
  34562. BABYLON.MaterialDefines = MaterialDefines;
  34563. /**
  34564. * Base class for the main features of a material in Babylon.js
  34565. */
  34566. var Material = /** @class */ (function () {
  34567. /**
  34568. * Creates a material instance
  34569. * @param name defines the name of the material
  34570. * @param scene defines the scene to reference
  34571. * @param doNotAdd specifies if the material should be added to the scene
  34572. */
  34573. function Material(name, scene, doNotAdd) {
  34574. /**
  34575. * Specifies if the ready state should be checked on each call
  34576. */
  34577. this.checkReadyOnEveryCall = false;
  34578. /**
  34579. * Specifies if the ready state should be checked once
  34580. */
  34581. this.checkReadyOnlyOnce = false;
  34582. /**
  34583. * The state of the material
  34584. */
  34585. this.state = "";
  34586. /**
  34587. * The alpha value of the material
  34588. */
  34589. this._alpha = 1.0;
  34590. /**
  34591. * Specifies if back face culling is enabled
  34592. */
  34593. this._backFaceCulling = true;
  34594. /**
  34595. * Specifies if the material should be serialized
  34596. */
  34597. this.doNotSerialize = false;
  34598. /**
  34599. * Specifies if the effect should be stored on sub meshes
  34600. */
  34601. this.storeEffectOnSubMeshes = false;
  34602. /**
  34603. * An event triggered when the material is disposed
  34604. */
  34605. this.onDisposeObservable = new BABYLON.Observable();
  34606. /**
  34607. * An event triggered when the material is bound
  34608. */
  34609. this.onBindObservable = new BABYLON.Observable();
  34610. /**
  34611. * An event triggered when the material is unbound
  34612. */
  34613. this.onUnBindObservable = new BABYLON.Observable();
  34614. /**
  34615. * Stores the value of the alpha mode
  34616. */
  34617. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34618. /**
  34619. * Stores the state of the need depth pre-pass value
  34620. */
  34621. this._needDepthPrePass = false;
  34622. /**
  34623. * Specifies if depth writing should be disabled
  34624. */
  34625. this.disableDepthWrite = false;
  34626. /**
  34627. * Specifies if depth writing should be forced
  34628. */
  34629. this.forceDepthWrite = false;
  34630. /**
  34631. * Specifies if there should be a separate pass for culling
  34632. */
  34633. this.separateCullingPass = false;
  34634. /**
  34635. * Stores the state specifing if fog should be enabled
  34636. */
  34637. this._fogEnabled = true;
  34638. /**
  34639. * Stores the size of points
  34640. */
  34641. this.pointSize = 1.0;
  34642. /**
  34643. * Stores the z offset value
  34644. */
  34645. this.zOffset = 0;
  34646. /**
  34647. * Specifies if the material was previously ready
  34648. */
  34649. this._wasPreviouslyReady = false;
  34650. /**
  34651. * Stores the fill mode state
  34652. */
  34653. this._fillMode = Material.TriangleFillMode;
  34654. this.name = name;
  34655. this.id = name || BABYLON.Tools.RandomId();
  34656. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34657. if (this._scene.useRightHandedSystem) {
  34658. this.sideOrientation = Material.ClockWiseSideOrientation;
  34659. }
  34660. else {
  34661. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34662. }
  34663. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34664. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34665. if (!doNotAdd) {
  34666. this._scene.materials.push(this);
  34667. }
  34668. }
  34669. Object.defineProperty(Material, "TriangleFillMode", {
  34670. /**
  34671. * Returns the triangle fill mode
  34672. */
  34673. get: function () {
  34674. return Material._TriangleFillMode;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material, "WireFrameFillMode", {
  34680. /**
  34681. * Returns the wireframe mode
  34682. */
  34683. get: function () {
  34684. return Material._WireFrameFillMode;
  34685. },
  34686. enumerable: true,
  34687. configurable: true
  34688. });
  34689. Object.defineProperty(Material, "PointFillMode", {
  34690. /**
  34691. * Returns the point fill mode
  34692. */
  34693. get: function () {
  34694. return Material._PointFillMode;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "PointListDrawMode", {
  34700. /**
  34701. * Returns the point list draw mode
  34702. */
  34703. get: function () {
  34704. return Material._PointListDrawMode;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "LineListDrawMode", {
  34710. /**
  34711. * Returns the line list draw mode
  34712. */
  34713. get: function () {
  34714. return Material._LineListDrawMode;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material, "LineLoopDrawMode", {
  34720. /**
  34721. * Returns the line loop draw mode
  34722. */
  34723. get: function () {
  34724. return Material._LineLoopDrawMode;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(Material, "LineStripDrawMode", {
  34730. /**
  34731. * Returns the line strip draw mode
  34732. */
  34733. get: function () {
  34734. return Material._LineStripDrawMode;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34740. /**
  34741. * Returns the triangle strip draw mode
  34742. */
  34743. get: function () {
  34744. return Material._TriangleStripDrawMode;
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34750. /**
  34751. * Returns the triangle fan draw mode
  34752. */
  34753. get: function () {
  34754. return Material._TriangleFanDrawMode;
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34760. /**
  34761. * Returns the clock-wise side orientation
  34762. */
  34763. get: function () {
  34764. return Material._ClockWiseSideOrientation;
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34770. /**
  34771. * Returns the counter clock-wise side orientation
  34772. */
  34773. get: function () {
  34774. return Material._CounterClockWiseSideOrientation;
  34775. },
  34776. enumerable: true,
  34777. configurable: true
  34778. });
  34779. Object.defineProperty(Material, "TextureDirtyFlag", {
  34780. /**
  34781. * Returns the dirty texture flag value
  34782. */
  34783. get: function () {
  34784. return Material._TextureDirtyFlag;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. Object.defineProperty(Material, "LightDirtyFlag", {
  34790. /**
  34791. * Returns the dirty light flag value
  34792. */
  34793. get: function () {
  34794. return Material._LightDirtyFlag;
  34795. },
  34796. enumerable: true,
  34797. configurable: true
  34798. });
  34799. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34800. /**
  34801. * Returns the dirty fresnel flag value
  34802. */
  34803. get: function () {
  34804. return Material._FresnelDirtyFlag;
  34805. },
  34806. enumerable: true,
  34807. configurable: true
  34808. });
  34809. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34810. /**
  34811. * Returns the dirty attributes flag value
  34812. */
  34813. get: function () {
  34814. return Material._AttributesDirtyFlag;
  34815. },
  34816. enumerable: true,
  34817. configurable: true
  34818. });
  34819. Object.defineProperty(Material, "MiscDirtyFlag", {
  34820. /**
  34821. * Returns the dirty misc flag value
  34822. */
  34823. get: function () {
  34824. return Material._MiscDirtyFlag;
  34825. },
  34826. enumerable: true,
  34827. configurable: true
  34828. });
  34829. Object.defineProperty(Material.prototype, "alpha", {
  34830. /**
  34831. * Gets the alpha value of the material
  34832. */
  34833. get: function () {
  34834. return this._alpha;
  34835. },
  34836. /**
  34837. * Sets the alpha value of the material
  34838. */
  34839. set: function (value) {
  34840. if (this._alpha === value) {
  34841. return;
  34842. }
  34843. this._alpha = value;
  34844. this.markAsDirty(Material.MiscDirtyFlag);
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34850. /**
  34851. * Gets the back-face culling state
  34852. */
  34853. get: function () {
  34854. return this._backFaceCulling;
  34855. },
  34856. /**
  34857. * Sets the back-face culling state
  34858. */
  34859. set: function (value) {
  34860. if (this._backFaceCulling === value) {
  34861. return;
  34862. }
  34863. this._backFaceCulling = value;
  34864. this.markAsDirty(Material.TextureDirtyFlag);
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(Material.prototype, "onDispose", {
  34870. /**
  34871. * Called during a dispose event
  34872. */
  34873. set: function (callback) {
  34874. if (this._onDisposeObserver) {
  34875. this.onDisposeObservable.remove(this._onDisposeObserver);
  34876. }
  34877. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(Material.prototype, "onBind", {
  34883. /**
  34884. * Called during a bind event
  34885. */
  34886. set: function (callback) {
  34887. if (this._onBindObserver) {
  34888. this.onBindObservable.remove(this._onBindObserver);
  34889. }
  34890. this._onBindObserver = this.onBindObservable.add(callback);
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material.prototype, "alphaMode", {
  34896. /**
  34897. * Gets the value of the alpha mode
  34898. */
  34899. get: function () {
  34900. return this._alphaMode;
  34901. },
  34902. /**
  34903. * Sets the value of the alpha mode.
  34904. *
  34905. * | Value | Type | Description |
  34906. * | --- | --- | --- |
  34907. * | 0 | ALPHA_DISABLE | |
  34908. * | 1 | ALPHA_ADD | |
  34909. * | 2 | ALPHA_COMBINE | |
  34910. * | 3 | ALPHA_SUBTRACT | |
  34911. * | 4 | ALPHA_MULTIPLY | |
  34912. * | 5 | ALPHA_MAXIMIZED | |
  34913. * | 6 | ALPHA_ONEONE | |
  34914. * | 7 | ALPHA_PREMULTIPLIED | |
  34915. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34916. * | 9 | ALPHA_INTERPOLATE | |
  34917. * | 10 | ALPHA_SCREENMODE | |
  34918. *
  34919. */
  34920. set: function (value) {
  34921. if (this._alphaMode === value) {
  34922. return;
  34923. }
  34924. this._alphaMode = value;
  34925. this.markAsDirty(Material.TextureDirtyFlag);
  34926. },
  34927. enumerable: true,
  34928. configurable: true
  34929. });
  34930. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34931. /**
  34932. * Gets the depth pre-pass value
  34933. */
  34934. get: function () {
  34935. return this._needDepthPrePass;
  34936. },
  34937. /**
  34938. * Sets the need depth pre-pass value
  34939. */
  34940. set: function (value) {
  34941. if (this._needDepthPrePass === value) {
  34942. return;
  34943. }
  34944. this._needDepthPrePass = value;
  34945. if (this._needDepthPrePass) {
  34946. this.checkReadyOnEveryCall = true;
  34947. }
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(Material.prototype, "fogEnabled", {
  34953. /**
  34954. * Gets the value of the fog enabled state
  34955. */
  34956. get: function () {
  34957. return this._fogEnabled;
  34958. },
  34959. /**
  34960. * Sets the state for enabling fog
  34961. */
  34962. set: function (value) {
  34963. if (this._fogEnabled === value) {
  34964. return;
  34965. }
  34966. this._fogEnabled = value;
  34967. this.markAsDirty(Material.MiscDirtyFlag);
  34968. },
  34969. enumerable: true,
  34970. configurable: true
  34971. });
  34972. Object.defineProperty(Material.prototype, "wireframe", {
  34973. /**
  34974. * Gets a value specifying if wireframe mode is enabled
  34975. */
  34976. get: function () {
  34977. switch (this._fillMode) {
  34978. case Material.WireFrameFillMode:
  34979. case Material.LineListDrawMode:
  34980. case Material.LineLoopDrawMode:
  34981. case Material.LineStripDrawMode:
  34982. return true;
  34983. }
  34984. return this._scene.forceWireframe;
  34985. },
  34986. /**
  34987. * Sets the state of wireframe mode
  34988. */
  34989. set: function (value) {
  34990. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. Object.defineProperty(Material.prototype, "pointsCloud", {
  34996. /**
  34997. * Gets the value specifying if point clouds are enabled
  34998. */
  34999. get: function () {
  35000. switch (this._fillMode) {
  35001. case Material.PointFillMode:
  35002. case Material.PointListDrawMode:
  35003. return true;
  35004. }
  35005. return this._scene.forcePointsCloud;
  35006. },
  35007. /**
  35008. * Sets the state of point cloud mode
  35009. */
  35010. set: function (value) {
  35011. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35012. },
  35013. enumerable: true,
  35014. configurable: true
  35015. });
  35016. Object.defineProperty(Material.prototype, "fillMode", {
  35017. /**
  35018. * Gets the material fill mode
  35019. */
  35020. get: function () {
  35021. return this._fillMode;
  35022. },
  35023. /**
  35024. * Sets the material fill mode
  35025. */
  35026. set: function (value) {
  35027. if (this._fillMode === value) {
  35028. return;
  35029. }
  35030. this._fillMode = value;
  35031. this.markAsDirty(Material.MiscDirtyFlag);
  35032. },
  35033. enumerable: true,
  35034. configurable: true
  35035. });
  35036. /**
  35037. * Returns a string representation of the current material
  35038. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35039. * @returns a string with material information
  35040. */
  35041. Material.prototype.toString = function (fullDetails) {
  35042. var ret = "Name: " + this.name;
  35043. if (fullDetails) {
  35044. }
  35045. return ret;
  35046. };
  35047. /**
  35048. * Gets the class name of the material
  35049. * @returns a string with the class name of the material
  35050. */
  35051. Material.prototype.getClassName = function () {
  35052. return "Material";
  35053. };
  35054. Object.defineProperty(Material.prototype, "isFrozen", {
  35055. /**
  35056. * Specifies if updates for the material been locked
  35057. */
  35058. get: function () {
  35059. return this.checkReadyOnlyOnce;
  35060. },
  35061. enumerable: true,
  35062. configurable: true
  35063. });
  35064. /**
  35065. * Locks updates for the material
  35066. */
  35067. Material.prototype.freeze = function () {
  35068. this.checkReadyOnlyOnce = true;
  35069. };
  35070. /**
  35071. * Unlocks updates for the material
  35072. */
  35073. Material.prototype.unfreeze = function () {
  35074. this.checkReadyOnlyOnce = false;
  35075. };
  35076. /**
  35077. * Specifies if the material is ready to be used
  35078. * @param mesh defines the mesh to check
  35079. * @param useInstances specifies if instances should be used
  35080. * @returns a boolean indicating if the material is ready to be used
  35081. */
  35082. Material.prototype.isReady = function (mesh, useInstances) {
  35083. return true;
  35084. };
  35085. /**
  35086. * Specifies that the submesh is ready to be used
  35087. * @param mesh defines the mesh to check
  35088. * @param subMesh defines which submesh to check
  35089. * @param useInstances specifies that instances should be used
  35090. * @returns a boolean indicating that the submesh is ready or not
  35091. */
  35092. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35093. return false;
  35094. };
  35095. /**
  35096. * Returns the material effect
  35097. * @returns the effect associated with the material
  35098. */
  35099. Material.prototype.getEffect = function () {
  35100. return this._effect;
  35101. };
  35102. /**
  35103. * Returns the current scene
  35104. * @returns a Scene
  35105. */
  35106. Material.prototype.getScene = function () {
  35107. return this._scene;
  35108. };
  35109. /**
  35110. * Specifies if the material will require alpha blending
  35111. * @returns a boolean specifying if alpha blending is needed
  35112. */
  35113. Material.prototype.needAlphaBlending = function () {
  35114. return (this.alpha < 1.0);
  35115. };
  35116. /**
  35117. * Specifies if the mesh will require alpha blending
  35118. * @param mesh defines the mesh to check
  35119. * @returns a boolean specifying if alpha blending is needed for the mesh
  35120. */
  35121. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35122. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35123. };
  35124. /**
  35125. * Specifies if this material should be rendered in alpha test mode
  35126. * @returns a boolean specifying if an alpha test is needed.
  35127. */
  35128. Material.prototype.needAlphaTesting = function () {
  35129. return false;
  35130. };
  35131. /**
  35132. * Gets the texture used for the alpha test
  35133. * @returns the texture to use for alpha testing
  35134. */
  35135. Material.prototype.getAlphaTestTexture = function () {
  35136. return null;
  35137. };
  35138. /**
  35139. * Marks the material to indicate that it needs to be re-calculated
  35140. */
  35141. Material.prototype.markDirty = function () {
  35142. this._wasPreviouslyReady = false;
  35143. };
  35144. /** @hidden */
  35145. Material.prototype._preBind = function (effect, overrideOrientation) {
  35146. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35147. var engine = this._scene.getEngine();
  35148. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35149. var reverse = orientation === Material.ClockWiseSideOrientation;
  35150. engine.enableEffect(effect ? effect : this._effect);
  35151. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35152. return reverse;
  35153. };
  35154. /**
  35155. * Binds the material to the mesh
  35156. * @param world defines the world transformation matrix
  35157. * @param mesh defines the mesh to bind the material to
  35158. */
  35159. Material.prototype.bind = function (world, mesh) {
  35160. };
  35161. /**
  35162. * Binds the submesh to the material
  35163. * @param world defines the world transformation matrix
  35164. * @param mesh defines the mesh containing the submesh
  35165. * @param subMesh defines the submesh to bind the material to
  35166. */
  35167. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35168. };
  35169. /**
  35170. * Binds the world matrix to the material
  35171. * @param world defines the world transformation matrix
  35172. */
  35173. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35174. };
  35175. /**
  35176. * Binds the scene's uniform buffer to the effect.
  35177. * @param effect defines the effect to bind to the scene uniform buffer
  35178. * @param sceneUbo defines the uniform buffer storing scene data
  35179. */
  35180. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35181. sceneUbo.bindToEffect(effect, "Scene");
  35182. };
  35183. /**
  35184. * Binds the view matrix to the effect
  35185. * @param effect defines the effect to bind the view matrix to
  35186. */
  35187. Material.prototype.bindView = function (effect) {
  35188. if (!this._useUBO) {
  35189. effect.setMatrix("view", this.getScene().getViewMatrix());
  35190. }
  35191. else {
  35192. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35193. }
  35194. };
  35195. /**
  35196. * Binds the view projection matrix to the effect
  35197. * @param effect defines the effect to bind the view projection matrix to
  35198. */
  35199. Material.prototype.bindViewProjection = function (effect) {
  35200. if (!this._useUBO) {
  35201. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35202. }
  35203. else {
  35204. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35205. }
  35206. };
  35207. /**
  35208. * Specifies if material alpha testing should be turned on for the mesh
  35209. * @param mesh defines the mesh to check
  35210. */
  35211. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35212. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35213. };
  35214. /**
  35215. * Processes to execute after binding the material to a mesh
  35216. * @param mesh defines the rendered mesh
  35217. */
  35218. Material.prototype._afterBind = function (mesh) {
  35219. this._scene._cachedMaterial = this;
  35220. if (mesh) {
  35221. this._scene._cachedVisibility = mesh.visibility;
  35222. }
  35223. else {
  35224. this._scene._cachedVisibility = 1;
  35225. }
  35226. if (mesh) {
  35227. this.onBindObservable.notifyObservers(mesh);
  35228. }
  35229. if (this.disableDepthWrite) {
  35230. var engine = this._scene.getEngine();
  35231. this._cachedDepthWriteState = engine.getDepthWrite();
  35232. engine.setDepthWrite(false);
  35233. }
  35234. };
  35235. /**
  35236. * Unbinds the material from the mesh
  35237. */
  35238. Material.prototype.unbind = function () {
  35239. this.onUnBindObservable.notifyObservers(this);
  35240. if (this.disableDepthWrite) {
  35241. var engine = this._scene.getEngine();
  35242. engine.setDepthWrite(this._cachedDepthWriteState);
  35243. }
  35244. };
  35245. /**
  35246. * Gets the active textures from the material
  35247. * @returns an array of textures
  35248. */
  35249. Material.prototype.getActiveTextures = function () {
  35250. return [];
  35251. };
  35252. /**
  35253. * Specifies if the material uses a texture
  35254. * @param texture defines the texture to check against the material
  35255. * @returns a boolean specifying if the material uses the texture
  35256. */
  35257. Material.prototype.hasTexture = function (texture) {
  35258. return false;
  35259. };
  35260. /**
  35261. * Makes a duplicate of the material, and gives it a new name
  35262. * @param name defines the new name for the duplicated material
  35263. * @returns the cloned material
  35264. */
  35265. Material.prototype.clone = function (name) {
  35266. return null;
  35267. };
  35268. /**
  35269. * Gets the meshes bound to the material
  35270. * @returns an array of meshes bound to the material
  35271. */
  35272. Material.prototype.getBindedMeshes = function () {
  35273. var result = new Array();
  35274. for (var index = 0; index < this._scene.meshes.length; index++) {
  35275. var mesh = this._scene.meshes[index];
  35276. if (mesh.material === this) {
  35277. result.push(mesh);
  35278. }
  35279. }
  35280. return result;
  35281. };
  35282. /**
  35283. * Force shader compilation
  35284. * @param mesh defines the mesh associated with this material
  35285. * @param onCompiled defines a function to execute once the material is compiled
  35286. * @param options defines the options to configure the compilation
  35287. */
  35288. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35289. var _this = this;
  35290. var localOptions = __assign({ clipPlane: false }, options);
  35291. var subMesh = new BABYLON.BaseSubMesh();
  35292. var scene = this.getScene();
  35293. var checkReady = function () {
  35294. if (!_this._scene || !_this._scene.getEngine()) {
  35295. return;
  35296. }
  35297. if (subMesh._materialDefines) {
  35298. subMesh._materialDefines._renderId = -1;
  35299. }
  35300. var clipPlaneState = scene.clipPlane;
  35301. if (localOptions.clipPlane) {
  35302. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35303. }
  35304. if (_this.storeEffectOnSubMeshes) {
  35305. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35306. if (onCompiled) {
  35307. onCompiled(_this);
  35308. }
  35309. }
  35310. else {
  35311. setTimeout(checkReady, 16);
  35312. }
  35313. }
  35314. else {
  35315. if (_this.isReady(mesh)) {
  35316. if (onCompiled) {
  35317. onCompiled(_this);
  35318. }
  35319. }
  35320. else {
  35321. setTimeout(checkReady, 16);
  35322. }
  35323. }
  35324. if (localOptions.clipPlane) {
  35325. scene.clipPlane = clipPlaneState;
  35326. }
  35327. };
  35328. checkReady();
  35329. };
  35330. /**
  35331. * Force shader compilation
  35332. * @param mesh defines the mesh that will use this material
  35333. * @param options defines additional options for compiling the shaders
  35334. * @returns a promise that resolves when the compilation completes
  35335. */
  35336. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35337. var _this = this;
  35338. return new Promise(function (resolve) {
  35339. _this.forceCompilation(mesh, function () {
  35340. resolve();
  35341. }, options);
  35342. });
  35343. };
  35344. /**
  35345. * Marks a define in the material to indicate that it needs to be re-computed
  35346. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35347. */
  35348. Material.prototype.markAsDirty = function (flag) {
  35349. if (flag & Material.TextureDirtyFlag) {
  35350. this._markAllSubMeshesAsTexturesDirty();
  35351. }
  35352. if (flag & Material.LightDirtyFlag) {
  35353. this._markAllSubMeshesAsLightsDirty();
  35354. }
  35355. if (flag & Material.FresnelDirtyFlag) {
  35356. this._markAllSubMeshesAsFresnelDirty();
  35357. }
  35358. if (flag & Material.AttributesDirtyFlag) {
  35359. this._markAllSubMeshesAsAttributesDirty();
  35360. }
  35361. if (flag & Material.MiscDirtyFlag) {
  35362. this._markAllSubMeshesAsMiscDirty();
  35363. }
  35364. this.getScene().resetCachedMaterial();
  35365. };
  35366. /**
  35367. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35368. * @param func defines a function which checks material defines against the submeshes
  35369. */
  35370. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35371. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35372. var mesh = _a[_i];
  35373. if (!mesh.subMeshes) {
  35374. continue;
  35375. }
  35376. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35377. var subMesh = _c[_b];
  35378. if (subMesh.getMaterial() !== this) {
  35379. continue;
  35380. }
  35381. if (!subMesh._materialDefines) {
  35382. continue;
  35383. }
  35384. func(subMesh._materialDefines);
  35385. }
  35386. }
  35387. };
  35388. /**
  35389. * Indicates that image processing needs to be re-calculated for all submeshes
  35390. */
  35391. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35392. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35393. };
  35394. /**
  35395. * Indicates that textures need to be re-calculated for all submeshes
  35396. */
  35397. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35398. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35399. };
  35400. /**
  35401. * Indicates that fresnel needs to be re-calculated for all submeshes
  35402. */
  35403. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35404. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35405. };
  35406. /**
  35407. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35408. */
  35409. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35410. this._markAllSubMeshesAsDirty(function (defines) {
  35411. defines.markAsFresnelDirty();
  35412. defines.markAsMiscDirty();
  35413. });
  35414. };
  35415. /**
  35416. * Indicates that lights need to be re-calculated for all submeshes
  35417. */
  35418. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35420. };
  35421. /**
  35422. * Indicates that attributes need to be re-calculated for all submeshes
  35423. */
  35424. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35426. };
  35427. /**
  35428. * Indicates that misc needs to be re-calculated for all submeshes
  35429. */
  35430. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35431. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35432. };
  35433. /**
  35434. * Indicates that textures and misc need to be re-calculated for all submeshes
  35435. */
  35436. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35437. this._markAllSubMeshesAsDirty(function (defines) {
  35438. defines.markAsTexturesDirty();
  35439. defines.markAsMiscDirty();
  35440. });
  35441. };
  35442. /**
  35443. * Disposes the material
  35444. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35445. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35446. */
  35447. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35448. // Animations
  35449. this.getScene().stopAnimation(this);
  35450. this.getScene().freeProcessedMaterials();
  35451. // Remove from scene
  35452. var index = this._scene.materials.indexOf(this);
  35453. if (index >= 0) {
  35454. this._scene.materials.splice(index, 1);
  35455. }
  35456. // Remove from meshes
  35457. for (index = 0; index < this._scene.meshes.length; index++) {
  35458. var mesh = this._scene.meshes[index];
  35459. if (mesh.material === this) {
  35460. mesh.material = null;
  35461. if (mesh.geometry) {
  35462. var geometry = (mesh.geometry);
  35463. if (this.storeEffectOnSubMeshes) {
  35464. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35465. var subMesh = _a[_i];
  35466. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35467. if (forceDisposeEffect && subMesh._materialEffect) {
  35468. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35469. }
  35470. }
  35471. }
  35472. else {
  35473. geometry._releaseVertexArrayObject(this._effect);
  35474. }
  35475. }
  35476. }
  35477. }
  35478. this._uniformBuffer.dispose();
  35479. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35480. if (forceDisposeEffect && this._effect) {
  35481. if (!this.storeEffectOnSubMeshes) {
  35482. this._scene.getEngine()._releaseEffect(this._effect);
  35483. }
  35484. this._effect = null;
  35485. }
  35486. // Callback
  35487. this.onDisposeObservable.notifyObservers(this);
  35488. this.onDisposeObservable.clear();
  35489. this.onBindObservable.clear();
  35490. this.onUnBindObservable.clear();
  35491. };
  35492. /**
  35493. * Serializes this material
  35494. * @returns the serialized material object
  35495. */
  35496. Material.prototype.serialize = function () {
  35497. return BABYLON.SerializationHelper.Serialize(this);
  35498. };
  35499. /**
  35500. * Creates a MultiMaterial from parsed MultiMaterial data.
  35501. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35502. * @param scene defines the hosting scene
  35503. * @returns a new MultiMaterial
  35504. */
  35505. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35506. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35507. multiMaterial.id = parsedMultiMaterial.id;
  35508. if (BABYLON.Tags) {
  35509. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35510. }
  35511. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35512. var subMatId = parsedMultiMaterial.materials[matIndex];
  35513. if (subMatId) {
  35514. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35515. }
  35516. else {
  35517. multiMaterial.subMaterials.push(null);
  35518. }
  35519. }
  35520. return multiMaterial;
  35521. };
  35522. /**
  35523. * Creates a material from parsed material data
  35524. * @param parsedMaterial defines parsed material data
  35525. * @param scene defines the hosting scene
  35526. * @param rootUrl defines the root URL to use to load textures
  35527. * @returns a new material
  35528. */
  35529. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35530. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35531. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35532. }
  35533. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35534. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35535. if (!BABYLON.LegacyPBRMaterial) {
  35536. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35537. return;
  35538. }
  35539. }
  35540. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35541. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35542. };
  35543. // Triangle views
  35544. Material._TriangleFillMode = 0;
  35545. Material._WireFrameFillMode = 1;
  35546. Material._PointFillMode = 2;
  35547. // Draw modes
  35548. Material._PointListDrawMode = 3;
  35549. Material._LineListDrawMode = 4;
  35550. Material._LineLoopDrawMode = 5;
  35551. Material._LineStripDrawMode = 6;
  35552. Material._TriangleStripDrawMode = 7;
  35553. Material._TriangleFanDrawMode = 8;
  35554. /**
  35555. * Stores the clock-wise side orientation
  35556. */
  35557. Material._ClockWiseSideOrientation = 0;
  35558. /**
  35559. * Stores the counter clock-wise side orientation
  35560. */
  35561. Material._CounterClockWiseSideOrientation = 1;
  35562. /**
  35563. * The dirty texture flag value
  35564. */
  35565. Material._TextureDirtyFlag = 1;
  35566. /**
  35567. * The dirty light flag value
  35568. */
  35569. Material._LightDirtyFlag = 2;
  35570. /**
  35571. * The dirty fresnel flag value
  35572. */
  35573. Material._FresnelDirtyFlag = 4;
  35574. /**
  35575. * The dirty attribute flag value
  35576. */
  35577. Material._AttributesDirtyFlag = 8;
  35578. /**
  35579. * The dirty misc flag value
  35580. */
  35581. Material._MiscDirtyFlag = 16;
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], Material.prototype, "id", void 0);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], Material.prototype, "name", void 0);
  35588. __decorate([
  35589. BABYLON.serialize()
  35590. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35591. __decorate([
  35592. BABYLON.serialize()
  35593. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35594. __decorate([
  35595. BABYLON.serialize()
  35596. ], Material.prototype, "state", void 0);
  35597. __decorate([
  35598. BABYLON.serialize("alpha")
  35599. ], Material.prototype, "_alpha", void 0);
  35600. __decorate([
  35601. BABYLON.serialize("backFaceCulling")
  35602. ], Material.prototype, "_backFaceCulling", void 0);
  35603. __decorate([
  35604. BABYLON.serialize()
  35605. ], Material.prototype, "sideOrientation", void 0);
  35606. __decorate([
  35607. BABYLON.serialize("alphaMode")
  35608. ], Material.prototype, "_alphaMode", void 0);
  35609. __decorate([
  35610. BABYLON.serialize()
  35611. ], Material.prototype, "_needDepthPrePass", void 0);
  35612. __decorate([
  35613. BABYLON.serialize()
  35614. ], Material.prototype, "disableDepthWrite", void 0);
  35615. __decorate([
  35616. BABYLON.serialize()
  35617. ], Material.prototype, "forceDepthWrite", void 0);
  35618. __decorate([
  35619. BABYLON.serialize()
  35620. ], Material.prototype, "separateCullingPass", void 0);
  35621. __decorate([
  35622. BABYLON.serialize("fogEnabled")
  35623. ], Material.prototype, "_fogEnabled", void 0);
  35624. __decorate([
  35625. BABYLON.serialize()
  35626. ], Material.prototype, "pointSize", void 0);
  35627. __decorate([
  35628. BABYLON.serialize()
  35629. ], Material.prototype, "zOffset", void 0);
  35630. __decorate([
  35631. BABYLON.serialize()
  35632. ], Material.prototype, "wireframe", null);
  35633. __decorate([
  35634. BABYLON.serialize()
  35635. ], Material.prototype, "pointsCloud", null);
  35636. __decorate([
  35637. BABYLON.serialize()
  35638. ], Material.prototype, "fillMode", null);
  35639. return Material;
  35640. }());
  35641. BABYLON.Material = Material;
  35642. })(BABYLON || (BABYLON = {}));
  35643. //# sourceMappingURL=babylon.material.js.map
  35644. var BABYLON;
  35645. (function (BABYLON) {
  35646. var UniformBuffer = /** @class */ (function () {
  35647. /**
  35648. * Uniform buffer objects.
  35649. *
  35650. * Handles blocks of uniform on the GPU.
  35651. *
  35652. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35653. *
  35654. * For more information, please refer to :
  35655. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35656. */
  35657. function UniformBuffer(engine, data, dynamic) {
  35658. this._engine = engine;
  35659. this._noUBO = !engine.supportsUniformBuffers;
  35660. this._dynamic = dynamic;
  35661. this._data = data || [];
  35662. this._uniformLocations = {};
  35663. this._uniformSizes = {};
  35664. this._uniformLocationPointer = 0;
  35665. this._needSync = false;
  35666. if (this._noUBO) {
  35667. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35668. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35669. this.updateFloat = this._updateFloatForEffect;
  35670. this.updateFloat2 = this._updateFloat2ForEffect;
  35671. this.updateFloat3 = this._updateFloat3ForEffect;
  35672. this.updateFloat4 = this._updateFloat4ForEffect;
  35673. this.updateMatrix = this._updateMatrixForEffect;
  35674. this.updateVector3 = this._updateVector3ForEffect;
  35675. this.updateVector4 = this._updateVector4ForEffect;
  35676. this.updateColor3 = this._updateColor3ForEffect;
  35677. this.updateColor4 = this._updateColor4ForEffect;
  35678. }
  35679. else {
  35680. this._engine._uniformBuffers.push(this);
  35681. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35682. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35683. this.updateFloat = this._updateFloatForUniform;
  35684. this.updateFloat2 = this._updateFloat2ForUniform;
  35685. this.updateFloat3 = this._updateFloat3ForUniform;
  35686. this.updateFloat4 = this._updateFloat4ForUniform;
  35687. this.updateMatrix = this._updateMatrixForUniform;
  35688. this.updateVector3 = this._updateVector3ForUniform;
  35689. this.updateVector4 = this._updateVector4ForUniform;
  35690. this.updateColor3 = this._updateColor3ForUniform;
  35691. this.updateColor4 = this._updateColor4ForUniform;
  35692. }
  35693. }
  35694. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35695. // Properties
  35696. /**
  35697. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35698. * or just falling back on setUniformXXX calls.
  35699. */
  35700. get: function () {
  35701. return !this._noUBO;
  35702. },
  35703. enumerable: true,
  35704. configurable: true
  35705. });
  35706. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35707. /**
  35708. * Indicates if the WebGL underlying uniform buffer is in sync
  35709. * with the javascript cache data.
  35710. */
  35711. get: function () {
  35712. return !this._needSync;
  35713. },
  35714. enumerable: true,
  35715. configurable: true
  35716. });
  35717. /**
  35718. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35719. * Also, a dynamic UniformBuffer will disable cache verification and always
  35720. * update the underlying WebGL uniform buffer to the GPU.
  35721. */
  35722. UniformBuffer.prototype.isDynamic = function () {
  35723. return this._dynamic !== undefined;
  35724. };
  35725. /**
  35726. * The data cache on JS side.
  35727. */
  35728. UniformBuffer.prototype.getData = function () {
  35729. return this._bufferData;
  35730. };
  35731. /**
  35732. * The underlying WebGL Uniform buffer.
  35733. */
  35734. UniformBuffer.prototype.getBuffer = function () {
  35735. return this._buffer;
  35736. };
  35737. /**
  35738. * std140 layout specifies how to align data within an UBO structure.
  35739. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35740. * for specs.
  35741. */
  35742. UniformBuffer.prototype._fillAlignment = function (size) {
  35743. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35744. // and 4x4 matrices
  35745. // TODO : change if other types are used
  35746. var alignment;
  35747. if (size <= 2) {
  35748. alignment = size;
  35749. }
  35750. else {
  35751. alignment = 4;
  35752. }
  35753. if ((this._uniformLocationPointer % alignment) !== 0) {
  35754. var oldPointer = this._uniformLocationPointer;
  35755. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35756. var diff = this._uniformLocationPointer - oldPointer;
  35757. for (var i = 0; i < diff; i++) {
  35758. this._data.push(0);
  35759. }
  35760. }
  35761. };
  35762. /**
  35763. * Adds an uniform in the buffer.
  35764. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35765. * for the layout to be correct !
  35766. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35767. * @param {number|number[]} size Data size, or data directly.
  35768. */
  35769. UniformBuffer.prototype.addUniform = function (name, size) {
  35770. if (this._noUBO) {
  35771. return;
  35772. }
  35773. if (this._uniformLocations[name] !== undefined) {
  35774. // Already existing uniform
  35775. return;
  35776. }
  35777. // This function must be called in the order of the shader layout !
  35778. // size can be the size of the uniform, or data directly
  35779. var data;
  35780. if (size instanceof Array) {
  35781. data = size;
  35782. size = data.length;
  35783. }
  35784. else {
  35785. size = size;
  35786. data = [];
  35787. // Fill with zeros
  35788. for (var i = 0; i < size; i++) {
  35789. data.push(0);
  35790. }
  35791. }
  35792. this._fillAlignment(size);
  35793. this._uniformSizes[name] = size;
  35794. this._uniformLocations[name] = this._uniformLocationPointer;
  35795. this._uniformLocationPointer += size;
  35796. for (var i = 0; i < size; i++) {
  35797. this._data.push(data[i]);
  35798. }
  35799. this._needSync = true;
  35800. };
  35801. /**
  35802. * Wrapper for addUniform.
  35803. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35804. * @param {Matrix} mat A 4x4 matrix.
  35805. */
  35806. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35807. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35808. };
  35809. /**
  35810. * Wrapper for addUniform.
  35811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35812. * @param {number} x
  35813. * @param {number} y
  35814. */
  35815. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35816. var temp = [x, y];
  35817. this.addUniform(name, temp);
  35818. };
  35819. /**
  35820. * Wrapper for addUniform.
  35821. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35822. * @param {number} x
  35823. * @param {number} y
  35824. * @param {number} z
  35825. */
  35826. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35827. var temp = [x, y, z];
  35828. this.addUniform(name, temp);
  35829. };
  35830. /**
  35831. * Wrapper for addUniform.
  35832. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35833. * @param {Color3} color
  35834. */
  35835. UniformBuffer.prototype.addColor3 = function (name, color) {
  35836. var temp = new Array();
  35837. color.toArray(temp);
  35838. this.addUniform(name, temp);
  35839. };
  35840. /**
  35841. * Wrapper for addUniform.
  35842. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35843. * @param {Color3} color
  35844. * @param {number} alpha
  35845. */
  35846. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35847. var temp = new Array();
  35848. color.toArray(temp);
  35849. temp.push(alpha);
  35850. this.addUniform(name, temp);
  35851. };
  35852. /**
  35853. * Wrapper for addUniform.
  35854. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35855. * @param {Vector3} vector
  35856. */
  35857. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35858. var temp = new Array();
  35859. vector.toArray(temp);
  35860. this.addUniform(name, temp);
  35861. };
  35862. /**
  35863. * Wrapper for addUniform.
  35864. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35865. */
  35866. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35867. this.addUniform(name, 12);
  35868. };
  35869. /**
  35870. * Wrapper for addUniform.
  35871. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35872. */
  35873. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35874. this.addUniform(name, 8);
  35875. };
  35876. /**
  35877. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35878. */
  35879. UniformBuffer.prototype.create = function () {
  35880. if (this._noUBO) {
  35881. return;
  35882. }
  35883. if (this._buffer) {
  35884. return; // nothing to do
  35885. }
  35886. // See spec, alignment must be filled as a vec4
  35887. this._fillAlignment(4);
  35888. this._bufferData = new Float32Array(this._data);
  35889. this._rebuild();
  35890. this._needSync = true;
  35891. };
  35892. UniformBuffer.prototype._rebuild = function () {
  35893. if (this._noUBO) {
  35894. return;
  35895. }
  35896. if (this._dynamic) {
  35897. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35898. }
  35899. else {
  35900. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35901. }
  35902. };
  35903. /**
  35904. * Updates the WebGL Uniform Buffer on the GPU.
  35905. * If the `dynamic` flag is set to true, no cache comparison is done.
  35906. * Otherwise, the buffer will be updated only if the cache differs.
  35907. */
  35908. UniformBuffer.prototype.update = function () {
  35909. if (!this._buffer) {
  35910. this.create();
  35911. return;
  35912. }
  35913. if (!this._dynamic && !this._needSync) {
  35914. return;
  35915. }
  35916. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35917. this._needSync = false;
  35918. };
  35919. /**
  35920. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35921. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35922. * @param {number[]|Float32Array} data Flattened data
  35923. * @param {number} size Size of the data.
  35924. */
  35925. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35926. var location = this._uniformLocations[uniformName];
  35927. if (location === undefined) {
  35928. if (this._buffer) {
  35929. // Cannot add an uniform if the buffer is already created
  35930. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35931. return;
  35932. }
  35933. this.addUniform(uniformName, size);
  35934. location = this._uniformLocations[uniformName];
  35935. }
  35936. if (!this._buffer) {
  35937. this.create();
  35938. }
  35939. if (!this._dynamic) {
  35940. // Cache for static uniform buffers
  35941. var changed = false;
  35942. for (var i = 0; i < size; i++) {
  35943. if (this._bufferData[location + i] !== data[i]) {
  35944. changed = true;
  35945. this._bufferData[location + i] = data[i];
  35946. }
  35947. }
  35948. this._needSync = this._needSync || changed;
  35949. }
  35950. else {
  35951. // No cache for dynamic
  35952. for (var i = 0; i < size; i++) {
  35953. this._bufferData[location + i] = data[i];
  35954. }
  35955. }
  35956. };
  35957. // Update methods
  35958. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35959. // To match std140, matrix must be realigned
  35960. for (var i = 0; i < 3; i++) {
  35961. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35962. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35963. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35964. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35965. }
  35966. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35967. };
  35968. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35969. this._currentEffect.setMatrix3x3(name, matrix);
  35970. };
  35971. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35972. this._currentEffect.setMatrix2x2(name, matrix);
  35973. };
  35974. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35975. // To match std140, matrix must be realigned
  35976. for (var i = 0; i < 2; i++) {
  35977. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35978. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35979. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35980. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35981. }
  35982. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35983. };
  35984. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35985. this._currentEffect.setFloat(name, x);
  35986. };
  35987. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35988. UniformBuffer._tempBuffer[0] = x;
  35989. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35990. };
  35991. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35992. if (suffix === void 0) { suffix = ""; }
  35993. this._currentEffect.setFloat2(name + suffix, x, y);
  35994. };
  35995. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35996. if (suffix === void 0) { suffix = ""; }
  35997. UniformBuffer._tempBuffer[0] = x;
  35998. UniformBuffer._tempBuffer[1] = y;
  35999. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36000. };
  36001. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36002. if (suffix === void 0) { suffix = ""; }
  36003. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36004. };
  36005. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36006. if (suffix === void 0) { suffix = ""; }
  36007. UniformBuffer._tempBuffer[0] = x;
  36008. UniformBuffer._tempBuffer[1] = y;
  36009. UniformBuffer._tempBuffer[2] = z;
  36010. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36011. };
  36012. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36013. if (suffix === void 0) { suffix = ""; }
  36014. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36015. };
  36016. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36017. if (suffix === void 0) { suffix = ""; }
  36018. UniformBuffer._tempBuffer[0] = x;
  36019. UniformBuffer._tempBuffer[1] = y;
  36020. UniformBuffer._tempBuffer[2] = z;
  36021. UniformBuffer._tempBuffer[3] = w;
  36022. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36023. };
  36024. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36025. this._currentEffect.setMatrix(name, mat);
  36026. };
  36027. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36028. this.updateUniform(name, mat.toArray(), 16);
  36029. };
  36030. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36031. this._currentEffect.setVector3(name, vector);
  36032. };
  36033. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36034. vector.toArray(UniformBuffer._tempBuffer);
  36035. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36036. };
  36037. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36038. this._currentEffect.setVector4(name, vector);
  36039. };
  36040. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36041. vector.toArray(UniformBuffer._tempBuffer);
  36042. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36043. };
  36044. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36045. if (suffix === void 0) { suffix = ""; }
  36046. this._currentEffect.setColor3(name + suffix, color);
  36047. };
  36048. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36049. if (suffix === void 0) { suffix = ""; }
  36050. color.toArray(UniformBuffer._tempBuffer);
  36051. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36052. };
  36053. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36054. if (suffix === void 0) { suffix = ""; }
  36055. this._currentEffect.setColor4(name + suffix, color, alpha);
  36056. };
  36057. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36058. if (suffix === void 0) { suffix = ""; }
  36059. color.toArray(UniformBuffer._tempBuffer);
  36060. UniformBuffer._tempBuffer[3] = alpha;
  36061. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36062. };
  36063. /**
  36064. * Sets a sampler uniform on the effect.
  36065. * @param {string} name Name of the sampler.
  36066. * @param {Texture} texture
  36067. */
  36068. UniformBuffer.prototype.setTexture = function (name, texture) {
  36069. this._currentEffect.setTexture(name, texture);
  36070. };
  36071. /**
  36072. * Directly updates the value of the uniform in the cache AND on the GPU.
  36073. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36074. * @param {number[]|Float32Array} data Flattened data
  36075. */
  36076. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36077. this.updateUniform(uniformName, data, data.length);
  36078. this.update();
  36079. };
  36080. /**
  36081. * Binds this uniform buffer to an effect.
  36082. * @param {Effect} effect
  36083. * @param {string} name Name of the uniform block in the shader.
  36084. */
  36085. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36086. this._currentEffect = effect;
  36087. if (this._noUBO || !this._buffer) {
  36088. return;
  36089. }
  36090. effect.bindUniformBuffer(this._buffer, name);
  36091. };
  36092. /**
  36093. * Disposes the uniform buffer.
  36094. */
  36095. UniformBuffer.prototype.dispose = function () {
  36096. if (this._noUBO) {
  36097. return;
  36098. }
  36099. var index = this._engine._uniformBuffers.indexOf(this);
  36100. if (index !== -1) {
  36101. this._engine._uniformBuffers.splice(index, 1);
  36102. }
  36103. if (!this._buffer) {
  36104. return;
  36105. }
  36106. if (this._engine._releaseBuffer(this._buffer)) {
  36107. this._buffer = null;
  36108. }
  36109. };
  36110. // Pool for avoiding memory leaks
  36111. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36112. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36113. return UniformBuffer;
  36114. }());
  36115. BABYLON.UniformBuffer = UniformBuffer;
  36116. })(BABYLON || (BABYLON = {}));
  36117. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36118. var BABYLON;
  36119. (function (BABYLON) {
  36120. /**
  36121. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36122. */
  36123. var VertexData = /** @class */ (function () {
  36124. function VertexData() {
  36125. }
  36126. /**
  36127. * Uses the passed data array to set the set the values for the specified kind of data
  36128. * @param data a linear array of floating numbers
  36129. * @param kind the type of data that is being set, eg positions, colors etc
  36130. */
  36131. VertexData.prototype.set = function (data, kind) {
  36132. switch (kind) {
  36133. case BABYLON.VertexBuffer.PositionKind:
  36134. this.positions = data;
  36135. break;
  36136. case BABYLON.VertexBuffer.NormalKind:
  36137. this.normals = data;
  36138. break;
  36139. case BABYLON.VertexBuffer.TangentKind:
  36140. this.tangents = data;
  36141. break;
  36142. case BABYLON.VertexBuffer.UVKind:
  36143. this.uvs = data;
  36144. break;
  36145. case BABYLON.VertexBuffer.UV2Kind:
  36146. this.uvs2 = data;
  36147. break;
  36148. case BABYLON.VertexBuffer.UV3Kind:
  36149. this.uvs3 = data;
  36150. break;
  36151. case BABYLON.VertexBuffer.UV4Kind:
  36152. this.uvs4 = data;
  36153. break;
  36154. case BABYLON.VertexBuffer.UV5Kind:
  36155. this.uvs5 = data;
  36156. break;
  36157. case BABYLON.VertexBuffer.UV6Kind:
  36158. this.uvs6 = data;
  36159. break;
  36160. case BABYLON.VertexBuffer.ColorKind:
  36161. this.colors = data;
  36162. break;
  36163. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36164. this.matricesIndices = data;
  36165. break;
  36166. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36167. this.matricesWeights = data;
  36168. break;
  36169. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36170. this.matricesIndicesExtra = data;
  36171. break;
  36172. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36173. this.matricesWeightsExtra = data;
  36174. break;
  36175. }
  36176. };
  36177. /**
  36178. * Associates the vertexData to the passed Mesh.
  36179. * Sets it as updatable or not (default `false`)
  36180. * @param mesh the mesh the vertexData is applied to
  36181. * @param updatable when used and having the value true allows new data to update the vertexData
  36182. * @returns the VertexData
  36183. */
  36184. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36185. this._applyTo(mesh, updatable);
  36186. return this;
  36187. };
  36188. /**
  36189. * Associates the vertexData to the passed Geometry.
  36190. * Sets it as updatable or not (default `false`)
  36191. * @param geometry the geometry the vertexData is applied to
  36192. * @param updatable when used and having the value true allows new data to update the vertexData
  36193. * @returns VertexData
  36194. */
  36195. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36196. this._applyTo(geometry, updatable);
  36197. return this;
  36198. };
  36199. /**
  36200. * Updates the associated mesh
  36201. * @param mesh the mesh to be updated
  36202. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36203. * @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
  36204. * @returns VertexData
  36205. */
  36206. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36207. this._update(mesh);
  36208. return this;
  36209. };
  36210. /**
  36211. * Updates the associated geometry
  36212. * @param geometry the geometry to be updated
  36213. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36214. * @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
  36215. * @returns VertexData.
  36216. */
  36217. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36218. this._update(geometry);
  36219. return this;
  36220. };
  36221. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36222. if (updatable === void 0) { updatable = false; }
  36223. if (this.positions) {
  36224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36225. }
  36226. if (this.normals) {
  36227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36228. }
  36229. if (this.tangents) {
  36230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36231. }
  36232. if (this.uvs) {
  36233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36234. }
  36235. if (this.uvs2) {
  36236. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36237. }
  36238. if (this.uvs3) {
  36239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36240. }
  36241. if (this.uvs4) {
  36242. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36243. }
  36244. if (this.uvs5) {
  36245. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36246. }
  36247. if (this.uvs6) {
  36248. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36249. }
  36250. if (this.colors) {
  36251. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36252. }
  36253. if (this.matricesIndices) {
  36254. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36255. }
  36256. if (this.matricesWeights) {
  36257. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36258. }
  36259. if (this.matricesIndicesExtra) {
  36260. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36261. }
  36262. if (this.matricesWeightsExtra) {
  36263. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36264. }
  36265. if (this.indices) {
  36266. meshOrGeometry.setIndices(this.indices, null, updatable);
  36267. }
  36268. return this;
  36269. };
  36270. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36271. if (this.positions) {
  36272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36273. }
  36274. if (this.normals) {
  36275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36276. }
  36277. if (this.tangents) {
  36278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36279. }
  36280. if (this.uvs) {
  36281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36282. }
  36283. if (this.uvs2) {
  36284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36285. }
  36286. if (this.uvs3) {
  36287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36288. }
  36289. if (this.uvs4) {
  36290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36291. }
  36292. if (this.uvs5) {
  36293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36294. }
  36295. if (this.uvs6) {
  36296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36297. }
  36298. if (this.colors) {
  36299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36300. }
  36301. if (this.matricesIndices) {
  36302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36303. }
  36304. if (this.matricesWeights) {
  36305. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36306. }
  36307. if (this.matricesIndicesExtra) {
  36308. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36309. }
  36310. if (this.matricesWeightsExtra) {
  36311. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36312. }
  36313. if (this.indices) {
  36314. meshOrGeometry.setIndices(this.indices, null);
  36315. }
  36316. return this;
  36317. };
  36318. /**
  36319. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36320. * @param matrix the transforming matrix
  36321. * @returns the VertexData
  36322. */
  36323. VertexData.prototype.transform = function (matrix) {
  36324. var transformed = BABYLON.Vector3.Zero();
  36325. var index;
  36326. if (this.positions) {
  36327. var position = BABYLON.Vector3.Zero();
  36328. for (index = 0; index < this.positions.length; index += 3) {
  36329. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36330. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36331. this.positions[index] = transformed.x;
  36332. this.positions[index + 1] = transformed.y;
  36333. this.positions[index + 2] = transformed.z;
  36334. }
  36335. }
  36336. if (this.normals) {
  36337. var normal = BABYLON.Vector3.Zero();
  36338. for (index = 0; index < this.normals.length; index += 3) {
  36339. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36340. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36341. this.normals[index] = transformed.x;
  36342. this.normals[index + 1] = transformed.y;
  36343. this.normals[index + 2] = transformed.z;
  36344. }
  36345. }
  36346. if (this.tangents) {
  36347. var tangent = BABYLON.Vector4.Zero();
  36348. var tangentTransformed = BABYLON.Vector4.Zero();
  36349. for (index = 0; index < this.tangents.length; index += 4) {
  36350. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36351. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36352. this.tangents[index] = tangentTransformed.x;
  36353. this.tangents[index + 1] = tangentTransformed.y;
  36354. this.tangents[index + 2] = tangentTransformed.z;
  36355. this.tangents[index + 3] = tangentTransformed.w;
  36356. }
  36357. }
  36358. return this;
  36359. };
  36360. /**
  36361. * Merges the passed VertexData into the current one
  36362. * @param other the VertexData to be merged into the current one
  36363. * @returns the modified VertexData
  36364. */
  36365. VertexData.prototype.merge = function (other) {
  36366. this._validate();
  36367. other._validate();
  36368. if (!this.normals !== !other.normals ||
  36369. !this.tangents !== !other.tangents ||
  36370. !this.uvs !== !other.uvs ||
  36371. !this.uvs2 !== !other.uvs2 ||
  36372. !this.uvs3 !== !other.uvs3 ||
  36373. !this.uvs4 !== !other.uvs4 ||
  36374. !this.uvs5 !== !other.uvs5 ||
  36375. !this.uvs6 !== !other.uvs6 ||
  36376. !this.colors !== !other.colors ||
  36377. !this.matricesIndices !== !other.matricesIndices ||
  36378. !this.matricesWeights !== !other.matricesWeights ||
  36379. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36380. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36381. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36382. }
  36383. if (other.indices) {
  36384. if (!this.indices) {
  36385. this.indices = [];
  36386. }
  36387. var offset = this.positions ? this.positions.length / 3 : 0;
  36388. for (var index = 0; index < other.indices.length; index++) {
  36389. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36390. this.indices.push(other.indices[index] + offset);
  36391. }
  36392. }
  36393. this.positions = this._mergeElement(this.positions, other.positions);
  36394. this.normals = this._mergeElement(this.normals, other.normals);
  36395. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36396. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36397. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36398. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36399. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36400. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36401. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36402. this.colors = this._mergeElement(this.colors, other.colors);
  36403. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36404. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36405. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36406. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36407. return this;
  36408. };
  36409. VertexData.prototype._mergeElement = function (source, other) {
  36410. if (!source) {
  36411. return other;
  36412. }
  36413. if (!other) {
  36414. return source;
  36415. }
  36416. var len = other.length + source.length;
  36417. var isSrcTypedArray = source instanceof Float32Array;
  36418. var isOthTypedArray = other instanceof Float32Array;
  36419. // use non-loop method when the source is Float32Array
  36420. if (isSrcTypedArray) {
  36421. var ret32 = new Float32Array(len);
  36422. ret32.set(source);
  36423. ret32.set(other, source.length);
  36424. return ret32;
  36425. // source is number[], when other is also use concat
  36426. }
  36427. else if (!isOthTypedArray) {
  36428. return source.concat(other);
  36429. // source is a number[], but other is a Float32Array, loop required
  36430. }
  36431. else {
  36432. var ret = source.slice(0); // copy source to a separate array
  36433. for (var i = 0, len = other.length; i < len; i++) {
  36434. ret.push(other[i]);
  36435. }
  36436. return ret;
  36437. }
  36438. };
  36439. VertexData.prototype._validate = function () {
  36440. if (!this.positions) {
  36441. throw new Error("Positions are required");
  36442. }
  36443. var getElementCount = function (kind, values) {
  36444. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36445. if ((values.length % stride) !== 0) {
  36446. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36447. }
  36448. return values.length / stride;
  36449. };
  36450. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36451. var validateElementCount = function (kind, values) {
  36452. var elementCount = getElementCount(kind, values);
  36453. if (elementCount !== positionsElementCount) {
  36454. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36455. }
  36456. };
  36457. if (this.normals)
  36458. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36459. if (this.tangents)
  36460. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36461. if (this.uvs)
  36462. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36463. if (this.uvs2)
  36464. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36465. if (this.uvs3)
  36466. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36467. if (this.uvs4)
  36468. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36469. if (this.uvs5)
  36470. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36471. if (this.uvs6)
  36472. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36473. if (this.colors)
  36474. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36475. if (this.matricesIndices)
  36476. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36477. if (this.matricesWeights)
  36478. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36479. if (this.matricesIndicesExtra)
  36480. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36481. if (this.matricesWeightsExtra)
  36482. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36483. };
  36484. /**
  36485. * Serializes the VertexData
  36486. * @returns a serialized object
  36487. */
  36488. VertexData.prototype.serialize = function () {
  36489. var serializationObject = this.serialize();
  36490. if (this.positions) {
  36491. serializationObject.positions = this.positions;
  36492. }
  36493. if (this.normals) {
  36494. serializationObject.normals = this.normals;
  36495. }
  36496. if (this.tangents) {
  36497. serializationObject.tangents = this.tangents;
  36498. }
  36499. if (this.uvs) {
  36500. serializationObject.uvs = this.uvs;
  36501. }
  36502. if (this.uvs2) {
  36503. serializationObject.uvs2 = this.uvs2;
  36504. }
  36505. if (this.uvs3) {
  36506. serializationObject.uvs3 = this.uvs3;
  36507. }
  36508. if (this.uvs4) {
  36509. serializationObject.uvs4 = this.uvs4;
  36510. }
  36511. if (this.uvs5) {
  36512. serializationObject.uvs5 = this.uvs5;
  36513. }
  36514. if (this.uvs6) {
  36515. serializationObject.uvs6 = this.uvs6;
  36516. }
  36517. if (this.colors) {
  36518. serializationObject.colors = this.colors;
  36519. }
  36520. if (this.matricesIndices) {
  36521. serializationObject.matricesIndices = this.matricesIndices;
  36522. serializationObject.matricesIndices._isExpanded = true;
  36523. }
  36524. if (this.matricesWeights) {
  36525. serializationObject.matricesWeights = this.matricesWeights;
  36526. }
  36527. if (this.matricesIndicesExtra) {
  36528. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36529. serializationObject.matricesIndicesExtra._isExpanded = true;
  36530. }
  36531. if (this.matricesWeightsExtra) {
  36532. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36533. }
  36534. serializationObject.indices = this.indices;
  36535. return serializationObject;
  36536. };
  36537. // Statics
  36538. /**
  36539. * Extracts the vertexData from a mesh
  36540. * @param mesh the mesh from which to extract the VertexData
  36541. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36542. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36543. * @returns the object VertexData associated to the passed mesh
  36544. */
  36545. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36546. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36547. };
  36548. /**
  36549. * Extracts the vertexData from the geometry
  36550. * @param geometry the geometry from which to extract the VertexData
  36551. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36552. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36553. * @returns the object VertexData associated to the passed mesh
  36554. */
  36555. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36556. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36557. };
  36558. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36559. var result = new VertexData();
  36560. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36561. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36562. }
  36563. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36564. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36565. }
  36566. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36567. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36568. }
  36569. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36570. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36571. }
  36572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36573. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36574. }
  36575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36576. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36577. }
  36578. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36579. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36580. }
  36581. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36582. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36583. }
  36584. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36585. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36586. }
  36587. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36588. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36589. }
  36590. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36591. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36592. }
  36593. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36594. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36595. }
  36596. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36597. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36598. }
  36599. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36600. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36601. }
  36602. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36603. return result;
  36604. };
  36605. /**
  36606. * Creates the VertexData for a Ribbon
  36607. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36608. * * pathArray array of paths, each of which an array of successive Vector3
  36609. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36610. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36611. * * 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
  36612. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36613. * * 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)
  36614. * * 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)
  36615. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36616. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36617. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36618. * @returns the VertexData of the ribbon
  36619. */
  36620. VertexData.CreateRibbon = function (options) {
  36621. var pathArray = options.pathArray;
  36622. var closeArray = options.closeArray || false;
  36623. var closePath = options.closePath || false;
  36624. var invertUV = options.invertUV || false;
  36625. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36626. var offset = options.offset || defaultOffset;
  36627. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36628. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36629. var customUV = options.uvs;
  36630. var customColors = options.colors;
  36631. var positions = [];
  36632. var indices = [];
  36633. var normals = [];
  36634. var uvs = [];
  36635. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36636. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36637. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36638. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36639. var minlg; // minimal length among all paths from pathArray
  36640. var lg = []; // array of path lengths : nb of vertex per path
  36641. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36642. var p; // path iterator
  36643. var i; // point iterator
  36644. var j; // point iterator
  36645. // if single path in pathArray
  36646. if (pathArray.length < 2) {
  36647. var ar1 = [];
  36648. var ar2 = [];
  36649. for (i = 0; i < pathArray[0].length - offset; i++) {
  36650. ar1.push(pathArray[0][i]);
  36651. ar2.push(pathArray[0][i + offset]);
  36652. }
  36653. pathArray = [ar1, ar2];
  36654. }
  36655. // positions and horizontal distances (u)
  36656. var idc = 0;
  36657. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36658. var path;
  36659. var l;
  36660. minlg = pathArray[0].length;
  36661. var vectlg;
  36662. var dist;
  36663. for (p = 0; p < pathArray.length; p++) {
  36664. uTotalDistance[p] = 0;
  36665. us[p] = [0];
  36666. path = pathArray[p];
  36667. l = path.length;
  36668. minlg = (minlg < l) ? minlg : l;
  36669. j = 0;
  36670. while (j < l) {
  36671. positions.push(path[j].x, path[j].y, path[j].z);
  36672. if (j > 0) {
  36673. vectlg = path[j].subtract(path[j - 1]).length();
  36674. dist = vectlg + uTotalDistance[p];
  36675. us[p].push(dist);
  36676. uTotalDistance[p] = dist;
  36677. }
  36678. j++;
  36679. }
  36680. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36681. j--;
  36682. positions.push(path[0].x, path[0].y, path[0].z);
  36683. vectlg = path[j].subtract(path[0]).length();
  36684. dist = vectlg + uTotalDistance[p];
  36685. us[p].push(dist);
  36686. uTotalDistance[p] = dist;
  36687. }
  36688. lg[p] = l + closePathCorr;
  36689. idx[p] = idc;
  36690. idc += (l + closePathCorr);
  36691. }
  36692. // vertical distances (v)
  36693. var path1;
  36694. var path2;
  36695. var vertex1 = null;
  36696. var vertex2 = null;
  36697. for (i = 0; i < minlg + closePathCorr; i++) {
  36698. vTotalDistance[i] = 0;
  36699. vs[i] = [0];
  36700. for (p = 0; p < pathArray.length - 1; p++) {
  36701. path1 = pathArray[p];
  36702. path2 = pathArray[p + 1];
  36703. if (i === minlg) { // closePath
  36704. vertex1 = path1[0];
  36705. vertex2 = path2[0];
  36706. }
  36707. else {
  36708. vertex1 = path1[i];
  36709. vertex2 = path2[i];
  36710. }
  36711. vectlg = vertex2.subtract(vertex1).length();
  36712. dist = vectlg + vTotalDistance[i];
  36713. vs[i].push(dist);
  36714. vTotalDistance[i] = dist;
  36715. }
  36716. if (closeArray && vertex2 && vertex1) {
  36717. path1 = pathArray[p];
  36718. path2 = pathArray[0];
  36719. if (i === minlg) { // closePath
  36720. vertex2 = path2[0];
  36721. }
  36722. vectlg = vertex2.subtract(vertex1).length();
  36723. dist = vectlg + vTotalDistance[i];
  36724. vTotalDistance[i] = dist;
  36725. }
  36726. }
  36727. // uvs
  36728. var u;
  36729. var v;
  36730. if (customUV) {
  36731. for (p = 0; p < customUV.length; p++) {
  36732. uvs.push(customUV[p].x, customUV[p].y);
  36733. }
  36734. }
  36735. else {
  36736. for (p = 0; p < pathArray.length; p++) {
  36737. for (i = 0; i < minlg + closePathCorr; i++) {
  36738. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36739. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36740. if (invertUV) {
  36741. uvs.push(v, u);
  36742. }
  36743. else {
  36744. uvs.push(u, v);
  36745. }
  36746. }
  36747. }
  36748. }
  36749. // indices
  36750. p = 0; // path index
  36751. var pi = 0; // positions array index
  36752. var l1 = lg[p] - 1; // path1 length
  36753. var l2 = lg[p + 1] - 1; // path2 length
  36754. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36755. var shft = idx[1] - idx[0]; // shift
  36756. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36757. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36758. // 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
  36759. indices.push(pi, pi + shft, pi + 1);
  36760. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36761. pi += 1;
  36762. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36763. p++;
  36764. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36765. shft = idx[0] - idx[p];
  36766. l1 = lg[p] - 1;
  36767. l2 = lg[0] - 1;
  36768. }
  36769. else {
  36770. shft = idx[p + 1] - idx[p];
  36771. l1 = lg[p] - 1;
  36772. l2 = lg[p + 1] - 1;
  36773. }
  36774. pi = idx[p];
  36775. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36776. }
  36777. }
  36778. // normals
  36779. VertexData.ComputeNormals(positions, indices, normals);
  36780. if (closePath) { // update both the first and last vertex normals to their average value
  36781. var indexFirst = 0;
  36782. var indexLast = 0;
  36783. for (p = 0; p < pathArray.length; p++) {
  36784. indexFirst = idx[p] * 3;
  36785. if (p + 1 < pathArray.length) {
  36786. indexLast = (idx[p + 1] - 1) * 3;
  36787. }
  36788. else {
  36789. indexLast = normals.length - 3;
  36790. }
  36791. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36792. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36793. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36794. normals[indexLast] = normals[indexFirst];
  36795. normals[indexLast + 1] = normals[indexFirst + 1];
  36796. normals[indexLast + 2] = normals[indexFirst + 2];
  36797. }
  36798. }
  36799. // sides
  36800. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36801. // Colors
  36802. var colors = null;
  36803. if (customColors) {
  36804. colors = new Float32Array(customColors.length * 4);
  36805. for (var c = 0; c < customColors.length; c++) {
  36806. colors[c * 4] = customColors[c].r;
  36807. colors[c * 4 + 1] = customColors[c].g;
  36808. colors[c * 4 + 2] = customColors[c].b;
  36809. colors[c * 4 + 3] = customColors[c].a;
  36810. }
  36811. }
  36812. // Result
  36813. var vertexData = new VertexData();
  36814. var positions32 = new Float32Array(positions);
  36815. var normals32 = new Float32Array(normals);
  36816. var uvs32 = new Float32Array(uvs);
  36817. vertexData.indices = indices;
  36818. vertexData.positions = positions32;
  36819. vertexData.normals = normals32;
  36820. vertexData.uvs = uvs32;
  36821. if (colors) {
  36822. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36823. }
  36824. if (closePath) {
  36825. vertexData._idx = idx;
  36826. }
  36827. return vertexData;
  36828. };
  36829. /**
  36830. * Creates the VertexData for a box
  36831. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36832. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36833. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36834. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36835. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36836. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36837. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36838. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36839. * * 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)
  36840. * * 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)
  36841. * @returns the VertexData of the box
  36842. */
  36843. VertexData.CreateBox = function (options) {
  36844. var normalsSource = [
  36845. new BABYLON.Vector3(0, 0, 1),
  36846. new BABYLON.Vector3(0, 0, -1),
  36847. new BABYLON.Vector3(1, 0, 0),
  36848. new BABYLON.Vector3(-1, 0, 0),
  36849. new BABYLON.Vector3(0, 1, 0),
  36850. new BABYLON.Vector3(0, -1, 0)
  36851. ];
  36852. var indices = [];
  36853. var positions = [];
  36854. var normals = [];
  36855. var uvs = [];
  36856. var width = options.width || options.size || 1;
  36857. var height = options.height || options.size || 1;
  36858. var depth = options.depth || options.size || 1;
  36859. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36860. var faceUV = options.faceUV || new Array(6);
  36861. var faceColors = options.faceColors;
  36862. var colors = [];
  36863. // default face colors and UV if undefined
  36864. for (var f = 0; f < 6; f++) {
  36865. if (faceUV[f] === undefined) {
  36866. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36867. }
  36868. if (faceColors && faceColors[f] === undefined) {
  36869. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36870. }
  36871. }
  36872. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36873. // Create each face in turn.
  36874. for (var index = 0; index < normalsSource.length; index++) {
  36875. var normal = normalsSource[index];
  36876. // Get two vectors perpendicular to the face normal and to each other.
  36877. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36878. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36879. // Six indices (two triangles) per face.
  36880. var verticesLength = positions.length / 3;
  36881. indices.push(verticesLength);
  36882. indices.push(verticesLength + 1);
  36883. indices.push(verticesLength + 2);
  36884. indices.push(verticesLength);
  36885. indices.push(verticesLength + 2);
  36886. indices.push(verticesLength + 3);
  36887. // Four vertices per face.
  36888. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36889. positions.push(vertex.x, vertex.y, vertex.z);
  36890. normals.push(normal.x, normal.y, normal.z);
  36891. uvs.push(faceUV[index].z, faceUV[index].w);
  36892. if (faceColors) {
  36893. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36894. }
  36895. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36896. positions.push(vertex.x, vertex.y, vertex.z);
  36897. normals.push(normal.x, normal.y, normal.z);
  36898. uvs.push(faceUV[index].x, faceUV[index].w);
  36899. if (faceColors) {
  36900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36901. }
  36902. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36903. positions.push(vertex.x, vertex.y, vertex.z);
  36904. normals.push(normal.x, normal.y, normal.z);
  36905. uvs.push(faceUV[index].x, faceUV[index].y);
  36906. if (faceColors) {
  36907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36908. }
  36909. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36910. positions.push(vertex.x, vertex.y, vertex.z);
  36911. normals.push(normal.x, normal.y, normal.z);
  36912. uvs.push(faceUV[index].z, faceUV[index].y);
  36913. if (faceColors) {
  36914. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36915. }
  36916. }
  36917. // sides
  36918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36919. // Result
  36920. var vertexData = new VertexData();
  36921. vertexData.indices = indices;
  36922. vertexData.positions = positions;
  36923. vertexData.normals = normals;
  36924. vertexData.uvs = uvs;
  36925. if (faceColors) {
  36926. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36927. vertexData.colors = totalColors;
  36928. }
  36929. return vertexData;
  36930. };
  36931. /**
  36932. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36933. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36934. * * segments sets the number of horizontal strips optional, default 32
  36935. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36936. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36937. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36938. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36939. * * 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
  36940. * * 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
  36941. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36942. * * 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)
  36943. * * 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)
  36944. * @returns the VertexData of the ellipsoid
  36945. */
  36946. VertexData.CreateSphere = function (options) {
  36947. var segments = options.segments || 32;
  36948. var diameterX = options.diameterX || options.diameter || 1;
  36949. var diameterY = options.diameterY || options.diameter || 1;
  36950. var diameterZ = options.diameterZ || options.diameter || 1;
  36951. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36952. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36953. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36954. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36955. var totalZRotationSteps = 2 + segments;
  36956. var totalYRotationSteps = 2 * totalZRotationSteps;
  36957. var indices = [];
  36958. var positions = [];
  36959. var normals = [];
  36960. var uvs = [];
  36961. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36962. var normalizedZ = zRotationStep / totalZRotationSteps;
  36963. var angleZ = normalizedZ * Math.PI * slice;
  36964. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36965. var normalizedY = yRotationStep / totalYRotationSteps;
  36966. var angleY = normalizedY * Math.PI * 2 * arc;
  36967. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36968. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36969. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36970. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36971. var vertex = complete.multiply(radius);
  36972. var normal = complete.divide(radius).normalize();
  36973. positions.push(vertex.x, vertex.y, vertex.z);
  36974. normals.push(normal.x, normal.y, normal.z);
  36975. uvs.push(normalizedY, normalizedZ);
  36976. }
  36977. if (zRotationStep > 0) {
  36978. var verticesCount = positions.length / 3;
  36979. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36980. indices.push((firstIndex));
  36981. indices.push((firstIndex + 1));
  36982. indices.push(firstIndex + totalYRotationSteps + 1);
  36983. indices.push((firstIndex + totalYRotationSteps + 1));
  36984. indices.push((firstIndex + 1));
  36985. indices.push((firstIndex + totalYRotationSteps + 2));
  36986. }
  36987. }
  36988. }
  36989. // Sides
  36990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36991. // Result
  36992. var vertexData = new VertexData();
  36993. vertexData.indices = indices;
  36994. vertexData.positions = positions;
  36995. vertexData.normals = normals;
  36996. vertexData.uvs = uvs;
  36997. return vertexData;
  36998. };
  36999. /**
  37000. * Creates the VertexData for a cylinder, cone or prism
  37001. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37002. * * height sets the height (y direction) of the cylinder, optional, default 2
  37003. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37004. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37005. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37006. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37007. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37008. * * 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
  37009. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37010. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37011. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37012. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37013. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37014. * * 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)
  37015. * * 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)
  37016. * @returns the VertexData of the cylinder, cone or prism
  37017. */
  37018. VertexData.CreateCylinder = function (options) {
  37019. var height = options.height || 2;
  37020. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37021. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37022. var tessellation = options.tessellation || 24;
  37023. var subdivisions = options.subdivisions || 1;
  37024. var hasRings = options.hasRings ? true : false;
  37025. var enclose = options.enclose ? true : false;
  37026. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37027. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37028. var faceUV = options.faceUV || new Array(3);
  37029. var faceColors = options.faceColors;
  37030. // default face colors and UV if undefined
  37031. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37032. var ringNb = (hasRings) ? subdivisions : 1;
  37033. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37034. var f;
  37035. for (f = 0; f < surfaceNb; f++) {
  37036. if (faceColors && faceColors[f] === undefined) {
  37037. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37038. }
  37039. }
  37040. for (f = 0; f < surfaceNb; f++) {
  37041. if (faceUV && faceUV[f] === undefined) {
  37042. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37043. }
  37044. }
  37045. var indices = new Array();
  37046. var positions = new Array();
  37047. var normals = new Array();
  37048. var uvs = new Array();
  37049. var colors = new Array();
  37050. var angle_step = Math.PI * 2 * arc / tessellation;
  37051. var angle;
  37052. var h;
  37053. var radius;
  37054. var tan = (diameterBottom - diameterTop) / 2 / height;
  37055. var ringVertex = BABYLON.Vector3.Zero();
  37056. var ringNormal = BABYLON.Vector3.Zero();
  37057. var ringFirstVertex = BABYLON.Vector3.Zero();
  37058. var ringFirstNormal = BABYLON.Vector3.Zero();
  37059. var quadNormal = BABYLON.Vector3.Zero();
  37060. var Y = BABYLON.Axis.Y;
  37061. // positions, normals, uvs
  37062. var i;
  37063. var j;
  37064. var r;
  37065. var ringIdx = 1;
  37066. var s = 1; // surface index
  37067. var cs = 0;
  37068. var v = 0;
  37069. for (i = 0; i <= subdivisions; i++) {
  37070. h = i / subdivisions;
  37071. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37072. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37073. for (r = 0; r < ringIdx; r++) {
  37074. if (hasRings) {
  37075. s += r;
  37076. }
  37077. if (enclose) {
  37078. s += 2 * r;
  37079. }
  37080. for (j = 0; j <= tessellation; j++) {
  37081. angle = j * angle_step;
  37082. // position
  37083. ringVertex.x = Math.cos(-angle) * radius;
  37084. ringVertex.y = -height / 2 + h * height;
  37085. ringVertex.z = Math.sin(-angle) * radius;
  37086. // normal
  37087. if (diameterTop === 0 && i === subdivisions) {
  37088. // if no top cap, reuse former normals
  37089. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37090. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37091. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37092. }
  37093. else {
  37094. ringNormal.x = ringVertex.x;
  37095. ringNormal.z = ringVertex.z;
  37096. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37097. ringNormal.normalize();
  37098. }
  37099. // keep first ring vertex values for enclose
  37100. if (j === 0) {
  37101. ringFirstVertex.copyFrom(ringVertex);
  37102. ringFirstNormal.copyFrom(ringNormal);
  37103. }
  37104. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37105. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37106. if (hasRings) {
  37107. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37108. }
  37109. else {
  37110. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37111. }
  37112. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37113. if (faceColors) {
  37114. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37115. }
  37116. }
  37117. // if enclose, add four vertices and their dedicated normals
  37118. if (arc !== 1 && enclose) {
  37119. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37120. positions.push(0, ringVertex.y, 0);
  37121. positions.push(0, ringVertex.y, 0);
  37122. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37123. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37124. quadNormal.normalize();
  37125. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37126. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37127. quadNormal.normalize();
  37128. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37129. if (hasRings) {
  37130. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37131. }
  37132. else {
  37133. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37134. }
  37135. uvs.push(faceUV[s + 1].x, v);
  37136. uvs.push(faceUV[s + 1].z, v);
  37137. if (hasRings) {
  37138. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37139. }
  37140. else {
  37141. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37142. }
  37143. uvs.push(faceUV[s + 2].x, v);
  37144. uvs.push(faceUV[s + 2].z, v);
  37145. if (faceColors) {
  37146. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37147. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37148. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37149. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37150. }
  37151. }
  37152. if (cs !== s) {
  37153. cs = s;
  37154. }
  37155. }
  37156. }
  37157. // indices
  37158. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37159. var s;
  37160. i = 0;
  37161. for (s = 0; s < subdivisions; s++) {
  37162. var i0 = 0;
  37163. var i1 = 0;
  37164. var i2 = 0;
  37165. var i3 = 0;
  37166. for (j = 0; j < tessellation; j++) {
  37167. i0 = i * (e + 1) + j;
  37168. i1 = (i + 1) * (e + 1) + j;
  37169. i2 = i * (e + 1) + (j + 1);
  37170. i3 = (i + 1) * (e + 1) + (j + 1);
  37171. indices.push(i0, i1, i2);
  37172. indices.push(i3, i2, i1);
  37173. }
  37174. if (arc !== 1 && enclose) { // if enclose, add two quads
  37175. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37176. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37177. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37178. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37179. }
  37180. i = (hasRings) ? (i + 2) : (i + 1);
  37181. }
  37182. // Caps
  37183. var createCylinderCap = function (isTop) {
  37184. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37185. if (radius === 0) {
  37186. return;
  37187. }
  37188. // Cap positions, normals & uvs
  37189. var angle;
  37190. var circleVector;
  37191. var i;
  37192. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37193. var c = null;
  37194. if (faceColors) {
  37195. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37196. }
  37197. // cap center
  37198. var vbase = positions.length / 3;
  37199. var offset = isTop ? height / 2 : -height / 2;
  37200. var center = new BABYLON.Vector3(0, offset, 0);
  37201. positions.push(center.x, center.y, center.z);
  37202. normals.push(0, isTop ? 1 : -1, 0);
  37203. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37204. if (c) {
  37205. colors.push(c.r, c.g, c.b, c.a);
  37206. }
  37207. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37208. for (i = 0; i <= tessellation; i++) {
  37209. angle = Math.PI * 2 * i * arc / tessellation;
  37210. var cos = Math.cos(-angle);
  37211. var sin = Math.sin(-angle);
  37212. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37213. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37214. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37215. normals.push(0, isTop ? 1 : -1, 0);
  37216. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37217. if (c) {
  37218. colors.push(c.r, c.g, c.b, c.a);
  37219. }
  37220. }
  37221. // Cap indices
  37222. for (i = 0; i < tessellation; i++) {
  37223. if (!isTop) {
  37224. indices.push(vbase);
  37225. indices.push(vbase + (i + 1));
  37226. indices.push(vbase + (i + 2));
  37227. }
  37228. else {
  37229. indices.push(vbase);
  37230. indices.push(vbase + (i + 2));
  37231. indices.push(vbase + (i + 1));
  37232. }
  37233. }
  37234. };
  37235. // add caps to geometry
  37236. createCylinderCap(false);
  37237. createCylinderCap(true);
  37238. // Sides
  37239. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37240. var vertexData = new VertexData();
  37241. vertexData.indices = indices;
  37242. vertexData.positions = positions;
  37243. vertexData.normals = normals;
  37244. vertexData.uvs = uvs;
  37245. if (faceColors) {
  37246. vertexData.colors = colors;
  37247. }
  37248. return vertexData;
  37249. };
  37250. /**
  37251. * Creates the VertexData for a torus
  37252. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37253. * * diameter the diameter of the torus, optional default 1
  37254. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37255. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37256. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37257. * * 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)
  37258. * * 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)
  37259. * @returns the VertexData of the torus
  37260. */
  37261. VertexData.CreateTorus = function (options) {
  37262. var indices = [];
  37263. var positions = [];
  37264. var normals = [];
  37265. var uvs = [];
  37266. var diameter = options.diameter || 1;
  37267. var thickness = options.thickness || 0.5;
  37268. var tessellation = options.tessellation || 16;
  37269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37270. var stride = tessellation + 1;
  37271. for (var i = 0; i <= tessellation; i++) {
  37272. var u = i / tessellation;
  37273. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37274. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37275. for (var j = 0; j <= tessellation; j++) {
  37276. var v = 1 - j / tessellation;
  37277. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37278. var dx = Math.cos(innerAngle);
  37279. var dy = Math.sin(innerAngle);
  37280. // Create a vertex.
  37281. var normal = new BABYLON.Vector3(dx, dy, 0);
  37282. var position = normal.scale(thickness / 2);
  37283. var textureCoordinate = new BABYLON.Vector2(u, v);
  37284. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37285. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37286. positions.push(position.x, position.y, position.z);
  37287. normals.push(normal.x, normal.y, normal.z);
  37288. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37289. // And create indices for two triangles.
  37290. var nextI = (i + 1) % stride;
  37291. var nextJ = (j + 1) % stride;
  37292. indices.push(i * stride + j);
  37293. indices.push(i * stride + nextJ);
  37294. indices.push(nextI * stride + j);
  37295. indices.push(i * stride + nextJ);
  37296. indices.push(nextI * stride + nextJ);
  37297. indices.push(nextI * stride + j);
  37298. }
  37299. }
  37300. // Sides
  37301. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37302. // Result
  37303. var vertexData = new VertexData();
  37304. vertexData.indices = indices;
  37305. vertexData.positions = positions;
  37306. vertexData.normals = normals;
  37307. vertexData.uvs = uvs;
  37308. return vertexData;
  37309. };
  37310. /**
  37311. * Creates the VertexData of the LineSystem
  37312. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37313. * - lines an array of lines, each line being an array of successive Vector3
  37314. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37315. * @returns the VertexData of the LineSystem
  37316. */
  37317. VertexData.CreateLineSystem = function (options) {
  37318. var indices = [];
  37319. var positions = [];
  37320. var lines = options.lines;
  37321. var colors = options.colors;
  37322. var vertexColors = [];
  37323. var idx = 0;
  37324. for (var l = 0; l < lines.length; l++) {
  37325. var points = lines[l];
  37326. for (var index = 0; index < points.length; index++) {
  37327. positions.push(points[index].x, points[index].y, points[index].z);
  37328. if (colors) {
  37329. var color = colors[l];
  37330. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37331. }
  37332. if (index > 0) {
  37333. indices.push(idx - 1);
  37334. indices.push(idx);
  37335. }
  37336. idx++;
  37337. }
  37338. }
  37339. var vertexData = new VertexData();
  37340. vertexData.indices = indices;
  37341. vertexData.positions = positions;
  37342. if (colors) {
  37343. vertexData.colors = vertexColors;
  37344. }
  37345. return vertexData;
  37346. };
  37347. /**
  37348. * Create the VertexData for a DashedLines
  37349. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37350. * - points an array successive Vector3
  37351. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37352. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37353. * - dashNb the intended total number of dashes, optional, default 200
  37354. * @returns the VertexData for the DashedLines
  37355. */
  37356. VertexData.CreateDashedLines = function (options) {
  37357. var dashSize = options.dashSize || 3;
  37358. var gapSize = options.gapSize || 1;
  37359. var dashNb = options.dashNb || 200;
  37360. var points = options.points;
  37361. var positions = new Array();
  37362. var indices = new Array();
  37363. var curvect = BABYLON.Vector3.Zero();
  37364. var lg = 0;
  37365. var nb = 0;
  37366. var shft = 0;
  37367. var dashshft = 0;
  37368. var curshft = 0;
  37369. var idx = 0;
  37370. var i = 0;
  37371. for (i = 0; i < points.length - 1; i++) {
  37372. points[i + 1].subtractToRef(points[i], curvect);
  37373. lg += curvect.length();
  37374. }
  37375. shft = lg / dashNb;
  37376. dashshft = dashSize * shft / (dashSize + gapSize);
  37377. for (i = 0; i < points.length - 1; i++) {
  37378. points[i + 1].subtractToRef(points[i], curvect);
  37379. nb = Math.floor(curvect.length() / shft);
  37380. curvect.normalize();
  37381. for (var j = 0; j < nb; j++) {
  37382. curshft = shft * j;
  37383. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37384. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37385. indices.push(idx, idx + 1);
  37386. idx += 2;
  37387. }
  37388. }
  37389. // Result
  37390. var vertexData = new VertexData();
  37391. vertexData.positions = positions;
  37392. vertexData.indices = indices;
  37393. return vertexData;
  37394. };
  37395. /**
  37396. * Creates the VertexData for a Ground
  37397. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37398. * - width the width (x direction) of the ground, optional, default 1
  37399. * - height the height (z direction) of the ground, optional, default 1
  37400. * - subdivisions the number of subdivisions per side, optional, default 1
  37401. * @returns the VertexData of the Ground
  37402. */
  37403. VertexData.CreateGround = function (options) {
  37404. var indices = [];
  37405. var positions = [];
  37406. var normals = [];
  37407. var uvs = [];
  37408. var row, col;
  37409. var width = options.width || 1;
  37410. var height = options.height || 1;
  37411. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37412. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37413. for (row = 0; row <= subdivisionsY; row++) {
  37414. for (col = 0; col <= subdivisionsX; col++) {
  37415. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37416. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37417. positions.push(position.x, position.y, position.z);
  37418. normals.push(normal.x, normal.y, normal.z);
  37419. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37420. }
  37421. }
  37422. for (row = 0; row < subdivisionsY; row++) {
  37423. for (col = 0; col < subdivisionsX; col++) {
  37424. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37425. indices.push(col + 1 + row * (subdivisionsX + 1));
  37426. indices.push(col + row * (subdivisionsX + 1));
  37427. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37428. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37429. indices.push(col + row * (subdivisionsX + 1));
  37430. }
  37431. }
  37432. // Result
  37433. var vertexData = new VertexData();
  37434. vertexData.indices = indices;
  37435. vertexData.positions = positions;
  37436. vertexData.normals = normals;
  37437. vertexData.uvs = uvs;
  37438. return vertexData;
  37439. };
  37440. /**
  37441. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37442. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37443. * * xmin the ground minimum X coordinate, optional, default -1
  37444. * * zmin the ground minimum Z coordinate, optional, default -1
  37445. * * xmax the ground maximum X coordinate, optional, default 1
  37446. * * zmax the ground maximum Z coordinate, optional, default 1
  37447. * * 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}
  37448. * * 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}
  37449. * @returns the VertexData of the TiledGround
  37450. */
  37451. VertexData.CreateTiledGround = function (options) {
  37452. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37453. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37454. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37455. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37456. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37457. var precision = options.precision || { w: 1, h: 1 };
  37458. var indices = new Array();
  37459. var positions = new Array();
  37460. var normals = new Array();
  37461. var uvs = new Array();
  37462. var row, col, tileRow, tileCol;
  37463. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37464. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37465. precision.w = (precision.w < 1) ? 1 : precision.w;
  37466. precision.h = (precision.h < 1) ? 1 : precision.h;
  37467. var tileSize = {
  37468. 'w': (xmax - xmin) / subdivisions.w,
  37469. 'h': (zmax - zmin) / subdivisions.h
  37470. };
  37471. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37472. // Indices
  37473. var base = positions.length / 3;
  37474. var rowLength = precision.w + 1;
  37475. for (row = 0; row < precision.h; row++) {
  37476. for (col = 0; col < precision.w; col++) {
  37477. var square = [
  37478. base + col + row * rowLength,
  37479. base + (col + 1) + row * rowLength,
  37480. base + (col + 1) + (row + 1) * rowLength,
  37481. base + col + (row + 1) * rowLength
  37482. ];
  37483. indices.push(square[1]);
  37484. indices.push(square[2]);
  37485. indices.push(square[3]);
  37486. indices.push(square[0]);
  37487. indices.push(square[1]);
  37488. indices.push(square[3]);
  37489. }
  37490. }
  37491. // Position, normals and uvs
  37492. var position = BABYLON.Vector3.Zero();
  37493. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37494. for (row = 0; row <= precision.h; row++) {
  37495. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37496. for (col = 0; col <= precision.w; col++) {
  37497. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37498. position.y = 0;
  37499. positions.push(position.x, position.y, position.z);
  37500. normals.push(normal.x, normal.y, normal.z);
  37501. uvs.push(col / precision.w, row / precision.h);
  37502. }
  37503. }
  37504. }
  37505. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37506. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37507. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37508. }
  37509. }
  37510. // Result
  37511. var vertexData = new VertexData();
  37512. vertexData.indices = indices;
  37513. vertexData.positions = positions;
  37514. vertexData.normals = normals;
  37515. vertexData.uvs = uvs;
  37516. return vertexData;
  37517. };
  37518. /**
  37519. * Creates the VertexData of the Ground designed from a heightmap
  37520. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37521. * * width the width (x direction) of the ground
  37522. * * height the height (z direction) of the ground
  37523. * * subdivisions the number of subdivisions per side
  37524. * * minHeight the minimum altitude on the ground, optional, default 0
  37525. * * maxHeight the maximum altitude on the ground, optional default 1
  37526. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37527. * * buffer the array holding the image color data
  37528. * * bufferWidth the width of image
  37529. * * bufferHeight the height of image
  37530. * @returns the VertexData of the Ground designed from a heightmap
  37531. */
  37532. VertexData.CreateGroundFromHeightMap = function (options) {
  37533. var indices = [];
  37534. var positions = [];
  37535. var normals = [];
  37536. var uvs = [];
  37537. var row, col;
  37538. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37539. // Vertices
  37540. for (row = 0; row <= options.subdivisions; row++) {
  37541. for (col = 0; col <= options.subdivisions; col++) {
  37542. 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));
  37543. // Compute height
  37544. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37545. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37546. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37547. var r = options.buffer[pos] / 255.0;
  37548. var g = options.buffer[pos + 1] / 255.0;
  37549. var b = options.buffer[pos + 2] / 255.0;
  37550. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37551. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37552. // Add vertex
  37553. positions.push(position.x, position.y, position.z);
  37554. normals.push(0, 0, 0);
  37555. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37556. }
  37557. }
  37558. // Indices
  37559. for (row = 0; row < options.subdivisions; row++) {
  37560. for (col = 0; col < options.subdivisions; col++) {
  37561. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37562. indices.push(col + 1 + row * (options.subdivisions + 1));
  37563. indices.push(col + row * (options.subdivisions + 1));
  37564. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37565. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37566. indices.push(col + row * (options.subdivisions + 1));
  37567. }
  37568. }
  37569. // Normals
  37570. VertexData.ComputeNormals(positions, indices, normals);
  37571. // Result
  37572. var vertexData = new VertexData();
  37573. vertexData.indices = indices;
  37574. vertexData.positions = positions;
  37575. vertexData.normals = normals;
  37576. vertexData.uvs = uvs;
  37577. return vertexData;
  37578. };
  37579. /**
  37580. * Creates the VertexData for a Plane
  37581. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37582. * * size sets the width and height of the plane to the value of size, optional default 1
  37583. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37584. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37585. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37586. * * 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)
  37587. * * 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)
  37588. * @returns the VertexData of the box
  37589. */
  37590. VertexData.CreatePlane = function (options) {
  37591. var indices = [];
  37592. var positions = [];
  37593. var normals = [];
  37594. var uvs = [];
  37595. var width = options.width || options.size || 1;
  37596. var height = options.height || options.size || 1;
  37597. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37598. // Vertices
  37599. var halfWidth = width / 2.0;
  37600. var halfHeight = height / 2.0;
  37601. positions.push(-halfWidth, -halfHeight, 0);
  37602. normals.push(0, 0, -1.0);
  37603. uvs.push(0.0, 0.0);
  37604. positions.push(halfWidth, -halfHeight, 0);
  37605. normals.push(0, 0, -1.0);
  37606. uvs.push(1.0, 0.0);
  37607. positions.push(halfWidth, halfHeight, 0);
  37608. normals.push(0, 0, -1.0);
  37609. uvs.push(1.0, 1.0);
  37610. positions.push(-halfWidth, halfHeight, 0);
  37611. normals.push(0, 0, -1.0);
  37612. uvs.push(0.0, 1.0);
  37613. // Indices
  37614. indices.push(0);
  37615. indices.push(1);
  37616. indices.push(2);
  37617. indices.push(0);
  37618. indices.push(2);
  37619. indices.push(3);
  37620. // Sides
  37621. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37622. // Result
  37623. var vertexData = new VertexData();
  37624. vertexData.indices = indices;
  37625. vertexData.positions = positions;
  37626. vertexData.normals = normals;
  37627. vertexData.uvs = uvs;
  37628. return vertexData;
  37629. };
  37630. /**
  37631. * Creates the VertexData of the Disc or regular Polygon
  37632. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37633. * * radius the radius of the disc, optional default 0.5
  37634. * * tessellation the number of polygon sides, optional, default 64
  37635. * * 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
  37636. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37637. * * 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)
  37638. * * 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)
  37639. * @returns the VertexData of the box
  37640. */
  37641. VertexData.CreateDisc = function (options) {
  37642. var positions = new Array();
  37643. var indices = new Array();
  37644. var normals = new Array();
  37645. var uvs = new Array();
  37646. var radius = options.radius || 0.5;
  37647. var tessellation = options.tessellation || 64;
  37648. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37650. // positions and uvs
  37651. positions.push(0, 0, 0); // disc center first
  37652. uvs.push(0.5, 0.5);
  37653. var theta = Math.PI * 2 * arc;
  37654. var step = theta / tessellation;
  37655. for (var a = 0; a < theta; a += step) {
  37656. var x = Math.cos(a);
  37657. var y = Math.sin(a);
  37658. var u = (x + 1) / 2;
  37659. var v = (1 - y) / 2;
  37660. positions.push(radius * x, radius * y, 0);
  37661. uvs.push(u, v);
  37662. }
  37663. if (arc === 1) {
  37664. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37665. uvs.push(uvs[2], uvs[3]);
  37666. }
  37667. //indices
  37668. var vertexNb = positions.length / 3;
  37669. for (var i = 1; i < vertexNb - 1; i++) {
  37670. indices.push(i + 1, 0, i);
  37671. }
  37672. // result
  37673. VertexData.ComputeNormals(positions, indices, normals);
  37674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37675. var vertexData = new VertexData();
  37676. vertexData.indices = indices;
  37677. vertexData.positions = positions;
  37678. vertexData.normals = normals;
  37679. vertexData.uvs = uvs;
  37680. return vertexData;
  37681. };
  37682. /**
  37683. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37684. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37685. * @param polygon a mesh built from polygonTriangulation.build()
  37686. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37687. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37688. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37689. * @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)
  37690. * @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)
  37691. * @returns the VertexData of the Polygon
  37692. */
  37693. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37694. var faceUV = fUV || new Array(3);
  37695. var faceColors = fColors;
  37696. var colors = [];
  37697. // default face colors and UV if undefined
  37698. for (var f = 0; f < 3; f++) {
  37699. if (faceUV[f] === undefined) {
  37700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37701. }
  37702. if (faceColors && faceColors[f] === undefined) {
  37703. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37704. }
  37705. }
  37706. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37707. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37708. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37709. var indices = polygon.getIndices();
  37710. // set face colours and textures
  37711. var idx = 0;
  37712. var face = 0;
  37713. for (var index = 0; index < normals.length; index += 3) {
  37714. //Edge Face no. 1
  37715. if (Math.abs(normals[index + 1]) < 0.001) {
  37716. face = 1;
  37717. }
  37718. //Top Face no. 0
  37719. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37720. face = 0;
  37721. }
  37722. //Bottom Face no. 2
  37723. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37724. face = 2;
  37725. }
  37726. idx = index / 3;
  37727. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37728. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37729. if (faceColors) {
  37730. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37731. }
  37732. }
  37733. // sides
  37734. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37735. // Result
  37736. var vertexData = new VertexData();
  37737. vertexData.indices = indices;
  37738. vertexData.positions = positions;
  37739. vertexData.normals = normals;
  37740. vertexData.uvs = uvs;
  37741. if (faceColors) {
  37742. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37743. vertexData.colors = totalColors;
  37744. }
  37745. return vertexData;
  37746. };
  37747. /**
  37748. * Creates the VertexData of the IcoSphere
  37749. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37750. * * radius the radius of the IcoSphere, optional default 1
  37751. * * radiusX allows stretching in the x direction, optional, default radius
  37752. * * radiusY allows stretching in the y direction, optional, default radius
  37753. * * radiusZ allows stretching in the z direction, optional, default radius
  37754. * * flat when true creates a flat shaded mesh, optional, default true
  37755. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37756. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37757. * * 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)
  37758. * * 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)
  37759. * @returns the VertexData of the IcoSphere
  37760. */
  37761. VertexData.CreateIcoSphere = function (options) {
  37762. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37763. var radius = options.radius || 1;
  37764. var flat = (options.flat === undefined) ? true : options.flat;
  37765. var subdivisions = options.subdivisions || 4;
  37766. var radiusX = options.radiusX || radius;
  37767. var radiusY = options.radiusY || radius;
  37768. var radiusZ = options.radiusZ || radius;
  37769. var t = (1 + Math.sqrt(5)) / 2;
  37770. // 12 vertex x,y,z
  37771. var ico_vertices = [
  37772. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37773. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37774. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37775. ];
  37776. // index of 3 vertex makes a face of icopshere
  37777. var ico_indices = [
  37778. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37779. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37780. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37781. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37782. ];
  37783. // vertex for uv have aliased position, not for UV
  37784. var vertices_unalias_id = [
  37785. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37786. // vertex alias
  37787. 0,
  37788. 2,
  37789. 3,
  37790. 3,
  37791. 3,
  37792. 4,
  37793. 7,
  37794. 8,
  37795. 9,
  37796. 9,
  37797. 10,
  37798. 11 // 23: B + 12
  37799. ];
  37800. // uv as integer step (not pixels !)
  37801. var ico_vertexuv = [
  37802. 5, 1, 3, 1, 6, 4, 0, 0,
  37803. 5, 3, 4, 2, 2, 2, 4, 0,
  37804. 2, 0, 1, 1, 6, 0, 6, 2,
  37805. // vertex alias (for same vertex on different faces)
  37806. 0, 4,
  37807. 3, 3,
  37808. 4, 4,
  37809. 3, 1,
  37810. 4, 2,
  37811. 4, 4,
  37812. 0, 2,
  37813. 1, 1,
  37814. 2, 2,
  37815. 3, 3,
  37816. 1, 3,
  37817. 2, 4 // 23: B + 12
  37818. ];
  37819. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37820. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37821. // First island of uv mapping
  37822. // v = 4h 3+ 2
  37823. // v = 3h 9+ 4
  37824. // v = 2h 9+ 5 B
  37825. // v = 1h 9 1 0
  37826. // v = 0h 3 8 7 A
  37827. // u = 0 1 2 3 4 5 6 *a
  37828. // Second island of uv mapping
  37829. // v = 4h 0+ B+ 4+
  37830. // v = 3h A+ 2+
  37831. // v = 2h 7+ 6 3+
  37832. // v = 1h 8+ 3+
  37833. // v = 0h
  37834. // u = 0 1 2 3 4 5 6 *a
  37835. // Face layout on texture UV mapping
  37836. // ============
  37837. // \ 4 /\ 16 / ======
  37838. // \ / \ / /\ 11 /
  37839. // \/ 7 \/ / \ /
  37840. // ======= / 10 \/
  37841. // /\ 17 /\ =======
  37842. // / \ / \ \ 15 /\
  37843. // / 8 \/ 12 \ \ / \
  37844. // ============ \/ 6 \
  37845. // \ 18 /\ ============
  37846. // \ / \ \ 5 /\ 0 /
  37847. // \/ 13 \ \ / \ /
  37848. // ======= \/ 1 \/
  37849. // =============
  37850. // /\ 19 /\ 2 /\
  37851. // / \ / \ / \
  37852. // / 14 \/ 9 \/ 3 \
  37853. // ===================
  37854. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37855. var ustep = 138 / 1024;
  37856. var vstep = 239 / 1024;
  37857. var uoffset = 60 / 1024;
  37858. var voffset = 26 / 1024;
  37859. // Second island should have margin, not to touch the first island
  37860. // avoid any borderline artefact in pixel rounding
  37861. var island_u_offset = -40 / 1024;
  37862. var island_v_offset = +20 / 1024;
  37863. // face is either island 0 or 1 :
  37864. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37865. var island = [
  37866. 0, 0, 0, 0, 1,
  37867. 0, 0, 1, 1, 0,
  37868. 0, 0, 1, 1, 0,
  37869. 0, 1, 1, 1, 0 // 15 - 19
  37870. ];
  37871. var indices = new Array();
  37872. var positions = new Array();
  37873. var normals = new Array();
  37874. var uvs = new Array();
  37875. var current_indice = 0;
  37876. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37877. var face_vertex_pos = new Array(3);
  37878. var face_vertex_uv = new Array(3);
  37879. var v012;
  37880. for (v012 = 0; v012 < 3; v012++) {
  37881. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37882. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37883. }
  37884. // create all with normals
  37885. for (var face = 0; face < 20; face++) {
  37886. // 3 vertex per face
  37887. for (v012 = 0; v012 < 3; v012++) {
  37888. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37889. var v_id = ico_indices[3 * face + v012];
  37890. // vertex have 3D position (x,y,z)
  37891. 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]);
  37892. // Normalize to get normal, then scale to radius
  37893. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37894. // uv Coordinates from vertex ID
  37895. 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);
  37896. }
  37897. // Subdivide the face (interpolate pos, norm, uv)
  37898. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37899. // - norm is linear interpolation of vertex corner normal
  37900. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37901. // - uv is linear interpolation
  37902. //
  37903. // Topology is as below for sub-divide by 2
  37904. // vertex shown as v0,v1,v2
  37905. // interp index is i1 to progress in range [v0,v1[
  37906. // interp index is i2 to progress in range [v0,v2[
  37907. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37908. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37909. //
  37910. //
  37911. // i2 v2
  37912. // ^ ^
  37913. // / / \
  37914. // / / \
  37915. // / / \
  37916. // / / (0,1) \
  37917. // / #---------\
  37918. // / / \ (0,0)'/ \
  37919. // / / \ / \
  37920. // / / \ / \
  37921. // / / (0,0) \ / (1,0) \
  37922. // / #---------#---------\
  37923. // v0 v1
  37924. //
  37925. // --------------------> i1
  37926. //
  37927. // interp of (i1,i2):
  37928. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37929. // along i1 : lerp(x0,x1, i1/(S-i2))
  37930. //
  37931. // centroid of triangle is needed to get help normal computation
  37932. // (c1,c2) are used for centroid location
  37933. var interp_vertex = function (i1, i2, c1, c2) {
  37934. // vertex is interpolated from
  37935. // - face_vertex_pos[0..2]
  37936. // - face_vertex_uv[0..2]
  37937. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37938. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37939. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37940. pos_interp.normalize();
  37941. var vertex_normal;
  37942. if (flat) {
  37943. // in flat mode, recalculate normal as face centroid normal
  37944. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37945. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37946. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37947. }
  37948. else {
  37949. // in smooth mode, recalculate normal from each single vertex position
  37950. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37951. }
  37952. // Vertex normal need correction due to X,Y,Z radius scaling
  37953. vertex_normal.x /= radiusX;
  37954. vertex_normal.y /= radiusY;
  37955. vertex_normal.z /= radiusZ;
  37956. vertex_normal.normalize();
  37957. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37958. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37959. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37960. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37961. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37962. uvs.push(uv_interp.x, uv_interp.y);
  37963. // push each vertex has member of a face
  37964. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37965. indices.push(current_indice);
  37966. current_indice++;
  37967. };
  37968. for (var i2 = 0; i2 < subdivisions; i2++) {
  37969. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37970. // face : (i1,i2) for /\ :
  37971. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37972. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37973. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37974. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37975. if (i1 + i2 + 1 < subdivisions) {
  37976. // face : (i1,i2)' for \/ :
  37977. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37978. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37979. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37980. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37981. }
  37982. }
  37983. }
  37984. }
  37985. // Sides
  37986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37987. // Result
  37988. var vertexData = new VertexData();
  37989. vertexData.indices = indices;
  37990. vertexData.positions = positions;
  37991. vertexData.normals = normals;
  37992. vertexData.uvs = uvs;
  37993. return vertexData;
  37994. };
  37995. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37996. /**
  37997. * Creates the VertexData for a Polyhedron
  37998. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37999. * * type provided types are:
  38000. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38001. * * 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)
  38002. * * size the size of the IcoSphere, optional default 1
  38003. * * sizeX allows stretching in the x direction, optional, default size
  38004. * * sizeY allows stretching in the y direction, optional, default size
  38005. * * sizeZ allows stretching in the z direction, optional, default size
  38006. * * 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
  38007. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38008. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38009. * * flat when true creates a flat shaded mesh, optional, default true
  38010. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38011. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38012. * * 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)
  38013. * * 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)
  38014. * @returns the VertexData of the Polyhedron
  38015. */
  38016. VertexData.CreatePolyhedron = function (options) {
  38017. // provided polyhedron types :
  38018. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38019. // 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)
  38020. var polyhedra = [];
  38021. 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]] };
  38022. 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]] };
  38023. polyhedra[2] = {
  38024. 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]],
  38025. 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]]
  38026. };
  38027. polyhedra[3] = {
  38028. 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]],
  38029. 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]]
  38030. };
  38031. polyhedra[4] = {
  38032. 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]],
  38033. 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]]
  38034. };
  38035. 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]] };
  38036. 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]] };
  38037. 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]] };
  38038. 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]] };
  38039. 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]] };
  38040. 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]] };
  38041. 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]] };
  38042. 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]] };
  38043. 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]] };
  38044. polyhedra[14] = {
  38045. 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]],
  38046. 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]]
  38047. };
  38048. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38049. var size = options.size;
  38050. var sizeX = options.sizeX || size || 1;
  38051. var sizeY = options.sizeY || size || 1;
  38052. var sizeZ = options.sizeZ || size || 1;
  38053. var data = options.custom || polyhedra[type];
  38054. var nbfaces = data.face.length;
  38055. var faceUV = options.faceUV || new Array(nbfaces);
  38056. var faceColors = options.faceColors;
  38057. var flat = (options.flat === undefined) ? true : options.flat;
  38058. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38059. var positions = new Array();
  38060. var indices = new Array();
  38061. var normals = new Array();
  38062. var uvs = new Array();
  38063. var colors = new Array();
  38064. var index = 0;
  38065. var faceIdx = 0; // face cursor in the array "indexes"
  38066. var indexes = new Array();
  38067. var i = 0;
  38068. var f = 0;
  38069. var u, v, ang, x, y, tmp;
  38070. // default face colors and UV if undefined
  38071. if (flat) {
  38072. for (f = 0; f < nbfaces; f++) {
  38073. if (faceColors && faceColors[f] === undefined) {
  38074. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38075. }
  38076. if (faceUV && faceUV[f] === undefined) {
  38077. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38078. }
  38079. }
  38080. }
  38081. if (!flat) {
  38082. for (i = 0; i < data.vertex.length; i++) {
  38083. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38084. uvs.push(0, 0);
  38085. }
  38086. for (f = 0; f < nbfaces; f++) {
  38087. for (i = 0; i < data.face[f].length - 2; i++) {
  38088. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38089. }
  38090. }
  38091. }
  38092. else {
  38093. for (f = 0; f < nbfaces; f++) {
  38094. var fl = data.face[f].length; // number of vertices of the current face
  38095. ang = 2 * Math.PI / fl;
  38096. x = 0.5 * Math.tan(ang / 2);
  38097. y = 0.5;
  38098. // positions, uvs, colors
  38099. for (i = 0; i < fl; i++) {
  38100. // positions
  38101. 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);
  38102. indexes.push(index);
  38103. index++;
  38104. // uvs
  38105. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38106. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38107. uvs.push(u, v);
  38108. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38109. y = x * Math.sin(ang) + y * Math.cos(ang);
  38110. x = tmp;
  38111. // colors
  38112. if (faceColors) {
  38113. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38114. }
  38115. }
  38116. // indices from indexes
  38117. for (i = 0; i < fl - 2; i++) {
  38118. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38119. }
  38120. faceIdx += fl;
  38121. }
  38122. }
  38123. VertexData.ComputeNormals(positions, indices, normals);
  38124. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38125. var vertexData = new VertexData();
  38126. vertexData.positions = positions;
  38127. vertexData.indices = indices;
  38128. vertexData.normals = normals;
  38129. vertexData.uvs = uvs;
  38130. if (faceColors && flat) {
  38131. vertexData.colors = colors;
  38132. }
  38133. return vertexData;
  38134. };
  38135. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38136. /**
  38137. * Creates the VertexData for a TorusKnot
  38138. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38139. * * radius the radius of the torus knot, optional, default 2
  38140. * * tube the thickness of the tube, optional, default 0.5
  38141. * * radialSegments the number of sides on each tube segments, optional, default 32
  38142. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38143. * * p the number of windings around the z axis, optional, default 2
  38144. * * q the number of windings around the x axis, optional, default 3
  38145. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38146. * * 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)
  38147. * * 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)
  38148. * @returns the VertexData of the Torus Knot
  38149. */
  38150. VertexData.CreateTorusKnot = function (options) {
  38151. var indices = new Array();
  38152. var positions = new Array();
  38153. var normals = new Array();
  38154. var uvs = new Array();
  38155. var radius = options.radius || 2;
  38156. var tube = options.tube || 0.5;
  38157. var radialSegments = options.radialSegments || 32;
  38158. var tubularSegments = options.tubularSegments || 32;
  38159. var p = options.p || 2;
  38160. var q = options.q || 3;
  38161. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38162. // Helper
  38163. var getPos = function (angle) {
  38164. var cu = Math.cos(angle);
  38165. var su = Math.sin(angle);
  38166. var quOverP = q / p * angle;
  38167. var cs = Math.cos(quOverP);
  38168. var tx = radius * (2 + cs) * 0.5 * cu;
  38169. var ty = radius * (2 + cs) * su * 0.5;
  38170. var tz = radius * Math.sin(quOverP) * 0.5;
  38171. return new BABYLON.Vector3(tx, ty, tz);
  38172. };
  38173. // Vertices
  38174. var i;
  38175. var j;
  38176. for (i = 0; i <= radialSegments; i++) {
  38177. var modI = i % radialSegments;
  38178. var u = modI / radialSegments * 2 * p * Math.PI;
  38179. var p1 = getPos(u);
  38180. var p2 = getPos(u + 0.01);
  38181. var tang = p2.subtract(p1);
  38182. var n = p2.add(p1);
  38183. var bitan = BABYLON.Vector3.Cross(tang, n);
  38184. n = BABYLON.Vector3.Cross(bitan, tang);
  38185. bitan.normalize();
  38186. n.normalize();
  38187. for (j = 0; j < tubularSegments; j++) {
  38188. var modJ = j % tubularSegments;
  38189. var v = modJ / tubularSegments * 2 * Math.PI;
  38190. var cx = -tube * Math.cos(v);
  38191. var cy = tube * Math.sin(v);
  38192. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38193. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38194. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38195. uvs.push(i / radialSegments);
  38196. uvs.push(j / tubularSegments);
  38197. }
  38198. }
  38199. for (i = 0; i < radialSegments; i++) {
  38200. for (j = 0; j < tubularSegments; j++) {
  38201. var jNext = (j + 1) % tubularSegments;
  38202. var a = i * tubularSegments + j;
  38203. var b = (i + 1) * tubularSegments + j;
  38204. var c = (i + 1) * tubularSegments + jNext;
  38205. var d = i * tubularSegments + jNext;
  38206. indices.push(d);
  38207. indices.push(b);
  38208. indices.push(a);
  38209. indices.push(d);
  38210. indices.push(c);
  38211. indices.push(b);
  38212. }
  38213. }
  38214. // Normals
  38215. VertexData.ComputeNormals(positions, indices, normals);
  38216. // Sides
  38217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38218. // Result
  38219. var vertexData = new VertexData();
  38220. vertexData.indices = indices;
  38221. vertexData.positions = positions;
  38222. vertexData.normals = normals;
  38223. vertexData.uvs = uvs;
  38224. return vertexData;
  38225. };
  38226. // Tools
  38227. /**
  38228. * Compute normals for given positions and indices
  38229. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38230. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38231. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38232. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38233. * * facetNormals : optional array of facet normals (vector3)
  38234. * * facetPositions : optional array of facet positions (vector3)
  38235. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38236. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38237. * * bInfo : optional bounding info, required for facetPartitioning computation
  38238. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38239. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38240. * * useRightHandedSystem: optional boolean to for right handed system computation
  38241. * * depthSort : optional boolean to enable the facet depth sort computation
  38242. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38243. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38244. */
  38245. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38246. // temporary scalar variables
  38247. var index = 0; // facet index
  38248. var p1p2x = 0.0; // p1p2 vector x coordinate
  38249. var p1p2y = 0.0; // p1p2 vector y coordinate
  38250. var p1p2z = 0.0; // p1p2 vector z coordinate
  38251. var p3p2x = 0.0; // p3p2 vector x coordinate
  38252. var p3p2y = 0.0; // p3p2 vector y coordinate
  38253. var p3p2z = 0.0; // p3p2 vector z coordinate
  38254. var faceNormalx = 0.0; // facet normal x coordinate
  38255. var faceNormaly = 0.0; // facet normal y coordinate
  38256. var faceNormalz = 0.0; // facet normal z coordinate
  38257. var length = 0.0; // facet normal length before normalization
  38258. var v1x = 0; // vector1 x index in the positions array
  38259. var v1y = 0; // vector1 y index in the positions array
  38260. var v1z = 0; // vector1 z index in the positions array
  38261. var v2x = 0; // vector2 x index in the positions array
  38262. var v2y = 0; // vector2 y index in the positions array
  38263. var v2z = 0; // vector2 z index in the positions array
  38264. var v3x = 0; // vector3 x index in the positions array
  38265. var v3y = 0; // vector3 y index in the positions array
  38266. var v3z = 0; // vector3 z index in the positions array
  38267. var computeFacetNormals = false;
  38268. var computeFacetPositions = false;
  38269. var computeFacetPartitioning = false;
  38270. var computeDepthSort = false;
  38271. var faceNormalSign = 1;
  38272. var ratio = 0;
  38273. var distanceTo = null;
  38274. if (options) {
  38275. computeFacetNormals = (options.facetNormals) ? true : false;
  38276. computeFacetPositions = (options.facetPositions) ? true : false;
  38277. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38278. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38279. ratio = options.ratio || 0;
  38280. computeDepthSort = (options.depthSort) ? true : false;
  38281. distanceTo = (options.distanceTo);
  38282. if (computeDepthSort) {
  38283. if (distanceTo === undefined) {
  38284. distanceTo = BABYLON.Vector3.Zero();
  38285. }
  38286. var depthSortedFacets = options.depthSortedFacets;
  38287. }
  38288. }
  38289. // facetPartitioning reinit if needed
  38290. var xSubRatio = 0;
  38291. var ySubRatio = 0;
  38292. var zSubRatio = 0;
  38293. var subSq = 0;
  38294. if (computeFacetPartitioning && options && options.bbSize) {
  38295. var ox = 0; // X partitioning index for facet position
  38296. var oy = 0; // Y partinioning index for facet position
  38297. var oz = 0; // Z partinioning index for facet position
  38298. var b1x = 0; // X partitioning index for facet v1 vertex
  38299. var b1y = 0; // Y partitioning index for facet v1 vertex
  38300. var b1z = 0; // z partitioning index for facet v1 vertex
  38301. var b2x = 0; // X partitioning index for facet v2 vertex
  38302. var b2y = 0; // Y partitioning index for facet v2 vertex
  38303. var b2z = 0; // Z partitioning index for facet v2 vertex
  38304. var b3x = 0; // X partitioning index for facet v3 vertex
  38305. var b3y = 0; // Y partitioning index for facet v3 vertex
  38306. var b3z = 0; // Z partitioning index for facet v3 vertex
  38307. var block_idx_o = 0; // facet barycenter block index
  38308. var block_idx_v1 = 0; // v1 vertex block index
  38309. var block_idx_v2 = 0; // v2 vertex block index
  38310. var block_idx_v3 = 0; // v3 vertex block index
  38311. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38312. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38313. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38314. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38315. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38316. subSq = options.subDiv.max * options.subDiv.max;
  38317. options.facetPartitioning.length = 0;
  38318. }
  38319. // reset the normals
  38320. for (index = 0; index < positions.length; index++) {
  38321. normals[index] = 0.0;
  38322. }
  38323. // Loop : 1 indice triplet = 1 facet
  38324. var nbFaces = (indices.length / 3) | 0;
  38325. for (index = 0; index < nbFaces; index++) {
  38326. // get the indexes of the coordinates of each vertex of the facet
  38327. v1x = indices[index * 3] * 3;
  38328. v1y = v1x + 1;
  38329. v1z = v1x + 2;
  38330. v2x = indices[index * 3 + 1] * 3;
  38331. v2y = v2x + 1;
  38332. v2z = v2x + 2;
  38333. v3x = indices[index * 3 + 2] * 3;
  38334. v3y = v3x + 1;
  38335. v3z = v3x + 2;
  38336. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38337. p1p2y = positions[v1y] - positions[v2y];
  38338. p1p2z = positions[v1z] - positions[v2z];
  38339. p3p2x = positions[v3x] - positions[v2x];
  38340. p3p2y = positions[v3y] - positions[v2y];
  38341. p3p2z = positions[v3z] - positions[v2z];
  38342. // compute the face normal with the cross product
  38343. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38344. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38345. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38346. // normalize this normal and store it in the array facetData
  38347. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38348. length = (length === 0) ? 1.0 : length;
  38349. faceNormalx /= length;
  38350. faceNormaly /= length;
  38351. faceNormalz /= length;
  38352. if (computeFacetNormals && options) {
  38353. options.facetNormals[index].x = faceNormalx;
  38354. options.facetNormals[index].y = faceNormaly;
  38355. options.facetNormals[index].z = faceNormalz;
  38356. }
  38357. if (computeFacetPositions && options) {
  38358. // compute and the facet barycenter coordinates in the array facetPositions
  38359. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38360. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38361. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38362. }
  38363. if (computeFacetPartitioning && options) {
  38364. // store the facet indexes in arrays in the main facetPartitioning array :
  38365. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38366. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38367. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38368. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38369. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38370. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38371. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38372. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38373. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38374. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38375. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38376. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38377. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38378. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38379. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38380. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38381. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38382. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38383. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38384. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38385. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38386. // push each facet index in each block containing the vertex
  38387. options.facetPartitioning[block_idx_v1].push(index);
  38388. if (block_idx_v2 != block_idx_v1) {
  38389. options.facetPartitioning[block_idx_v2].push(index);
  38390. }
  38391. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38392. options.facetPartitioning[block_idx_v3].push(index);
  38393. }
  38394. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38395. options.facetPartitioning[block_idx_o].push(index);
  38396. }
  38397. }
  38398. if (computeDepthSort && options && options.facetPositions) {
  38399. var dsf = depthSortedFacets[index];
  38400. dsf.ind = index * 3;
  38401. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38402. }
  38403. // compute the normals anyway
  38404. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38405. normals[v1y] += faceNormaly;
  38406. normals[v1z] += faceNormalz;
  38407. normals[v2x] += faceNormalx;
  38408. normals[v2y] += faceNormaly;
  38409. normals[v2z] += faceNormalz;
  38410. normals[v3x] += faceNormalx;
  38411. normals[v3y] += faceNormaly;
  38412. normals[v3z] += faceNormalz;
  38413. }
  38414. // last normalization of each normal
  38415. for (index = 0; index < normals.length / 3; index++) {
  38416. faceNormalx = normals[index * 3];
  38417. faceNormaly = normals[index * 3 + 1];
  38418. faceNormalz = normals[index * 3 + 2];
  38419. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38420. length = (length === 0) ? 1.0 : length;
  38421. faceNormalx /= length;
  38422. faceNormaly /= length;
  38423. faceNormalz /= length;
  38424. normals[index * 3] = faceNormalx;
  38425. normals[index * 3 + 1] = faceNormaly;
  38426. normals[index * 3 + 2] = faceNormalz;
  38427. }
  38428. };
  38429. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38430. var li = indices.length;
  38431. var ln = normals.length;
  38432. var i;
  38433. var n;
  38434. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38435. switch (sideOrientation) {
  38436. case BABYLON.Mesh.FRONTSIDE:
  38437. // nothing changed
  38438. break;
  38439. case BABYLON.Mesh.BACKSIDE:
  38440. var tmp;
  38441. // indices
  38442. for (i = 0; i < li; i += 3) {
  38443. tmp = indices[i];
  38444. indices[i] = indices[i + 2];
  38445. indices[i + 2] = tmp;
  38446. }
  38447. // normals
  38448. for (n = 0; n < ln; n++) {
  38449. normals[n] = -normals[n];
  38450. }
  38451. break;
  38452. case BABYLON.Mesh.DOUBLESIDE:
  38453. // positions
  38454. var lp = positions.length;
  38455. var l = lp / 3;
  38456. for (var p = 0; p < lp; p++) {
  38457. positions[lp + p] = positions[p];
  38458. }
  38459. // indices
  38460. for (i = 0; i < li; i += 3) {
  38461. indices[i + li] = indices[i + 2] + l;
  38462. indices[i + 1 + li] = indices[i + 1] + l;
  38463. indices[i + 2 + li] = indices[i] + l;
  38464. }
  38465. // normals
  38466. for (n = 0; n < ln; n++) {
  38467. normals[ln + n] = -normals[n];
  38468. }
  38469. // uvs
  38470. var lu = uvs.length;
  38471. var u = 0;
  38472. for (u = 0; u < lu; u++) {
  38473. uvs[u + lu] = uvs[u];
  38474. }
  38475. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38476. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38477. u = 0;
  38478. for (i = 0; i < lu / 2; i++) {
  38479. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38480. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38481. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38482. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38483. u += 2;
  38484. }
  38485. break;
  38486. }
  38487. };
  38488. /**
  38489. * Applies VertexData created from the imported parameters to the geometry
  38490. * @param parsedVertexData the parsed data from an imported file
  38491. * @param geometry the geometry to apply the VertexData to
  38492. */
  38493. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38494. var vertexData = new VertexData();
  38495. // positions
  38496. var positions = parsedVertexData.positions;
  38497. if (positions) {
  38498. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38499. }
  38500. // normals
  38501. var normals = parsedVertexData.normals;
  38502. if (normals) {
  38503. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38504. }
  38505. // tangents
  38506. var tangents = parsedVertexData.tangents;
  38507. if (tangents) {
  38508. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38509. }
  38510. // uvs
  38511. var uvs = parsedVertexData.uvs;
  38512. if (uvs) {
  38513. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38514. }
  38515. // uv2s
  38516. var uv2s = parsedVertexData.uv2s;
  38517. if (uv2s) {
  38518. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38519. }
  38520. // uv3s
  38521. var uv3s = parsedVertexData.uv3s;
  38522. if (uv3s) {
  38523. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38524. }
  38525. // uv4s
  38526. var uv4s = parsedVertexData.uv4s;
  38527. if (uv4s) {
  38528. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38529. }
  38530. // uv5s
  38531. var uv5s = parsedVertexData.uv5s;
  38532. if (uv5s) {
  38533. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38534. }
  38535. // uv6s
  38536. var uv6s = parsedVertexData.uv6s;
  38537. if (uv6s) {
  38538. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38539. }
  38540. // colors
  38541. var colors = parsedVertexData.colors;
  38542. if (colors) {
  38543. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38544. }
  38545. // matricesIndices
  38546. var matricesIndices = parsedVertexData.matricesIndices;
  38547. if (matricesIndices) {
  38548. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38549. }
  38550. // matricesWeights
  38551. var matricesWeights = parsedVertexData.matricesWeights;
  38552. if (matricesWeights) {
  38553. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38554. }
  38555. // indices
  38556. var indices = parsedVertexData.indices;
  38557. if (indices) {
  38558. vertexData.indices = indices;
  38559. }
  38560. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38561. };
  38562. return VertexData;
  38563. }());
  38564. BABYLON.VertexData = VertexData;
  38565. })(BABYLON || (BABYLON = {}));
  38566. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38567. var BABYLON;
  38568. (function (BABYLON) {
  38569. /**
  38570. * Class used to store geometry data (vertex buffers + index buffer)
  38571. */
  38572. var Geometry = /** @class */ (function () {
  38573. /**
  38574. * Creates a new geometry
  38575. * @param id defines the unique ID
  38576. * @param scene defines the hosting scene
  38577. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38578. * @param updatable defines if geometry must be updatable (false by default)
  38579. * @param mesh defines the mesh that will be associated with the geometry
  38580. */
  38581. function Geometry(id, scene, vertexData, updatable, mesh) {
  38582. if (updatable === void 0) { updatable = false; }
  38583. if (mesh === void 0) { mesh = null; }
  38584. /**
  38585. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38586. */
  38587. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38588. this._totalVertices = 0;
  38589. this._isDisposed = false;
  38590. this._indexBufferIsUpdatable = false;
  38591. this.id = id;
  38592. this._engine = scene.getEngine();
  38593. this._meshes = [];
  38594. this._scene = scene;
  38595. //Init vertex buffer cache
  38596. this._vertexBuffers = {};
  38597. this._indices = [];
  38598. this._updatable = updatable;
  38599. // vertexData
  38600. if (vertexData) {
  38601. this.setAllVerticesData(vertexData, updatable);
  38602. }
  38603. else {
  38604. this._totalVertices = 0;
  38605. this._indices = [];
  38606. }
  38607. if (this._engine.getCaps().vertexArrayObject) {
  38608. this._vertexArrayObjects = {};
  38609. }
  38610. // applyToMesh
  38611. if (mesh) {
  38612. if (mesh.getClassName() === "LinesMesh") {
  38613. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38614. this._updateExtend();
  38615. }
  38616. this.applyToMesh(mesh);
  38617. mesh.computeWorldMatrix(true);
  38618. }
  38619. }
  38620. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38621. /**
  38622. * 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
  38623. */
  38624. get: function () {
  38625. return this._boundingBias;
  38626. },
  38627. /**
  38628. * 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
  38629. */
  38630. set: function (value) {
  38631. if (this._boundingBias && this._boundingBias.equals(value)) {
  38632. return;
  38633. }
  38634. this._boundingBias = value.clone();
  38635. this._updateBoundingInfo(true, null);
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. /**
  38641. * Static function used to attach a new empty geometry to a mesh
  38642. * @param mesh defines the mesh to attach the geometry to
  38643. * @returns the new {BABYLON.Geometry}
  38644. */
  38645. Geometry.CreateGeometryForMesh = function (mesh) {
  38646. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38647. geometry.applyToMesh(mesh);
  38648. return geometry;
  38649. };
  38650. Object.defineProperty(Geometry.prototype, "extend", {
  38651. /**
  38652. * Gets the current extend of the geometry
  38653. */
  38654. get: function () {
  38655. return this._extend;
  38656. },
  38657. enumerable: true,
  38658. configurable: true
  38659. });
  38660. /**
  38661. * Gets the hosting scene
  38662. * @returns the hosting {BABYLON.Scene}
  38663. */
  38664. Geometry.prototype.getScene = function () {
  38665. return this._scene;
  38666. };
  38667. /**
  38668. * Gets the hosting engine
  38669. * @returns the hosting {BABYLON.Engine}
  38670. */
  38671. Geometry.prototype.getEngine = function () {
  38672. return this._engine;
  38673. };
  38674. /**
  38675. * Defines if the geometry is ready to use
  38676. * @returns true if the geometry is ready to be used
  38677. */
  38678. Geometry.prototype.isReady = function () {
  38679. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38680. };
  38681. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38682. /**
  38683. * Gets a value indicating that the geometry should not be serialized
  38684. */
  38685. get: function () {
  38686. for (var index = 0; index < this._meshes.length; index++) {
  38687. if (!this._meshes[index].doNotSerialize) {
  38688. return false;
  38689. }
  38690. }
  38691. return true;
  38692. },
  38693. enumerable: true,
  38694. configurable: true
  38695. });
  38696. /** @hidden */
  38697. Geometry.prototype._rebuild = function () {
  38698. if (this._vertexArrayObjects) {
  38699. this._vertexArrayObjects = {};
  38700. }
  38701. // Index buffer
  38702. if (this._meshes.length !== 0 && this._indices) {
  38703. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38704. }
  38705. // Vertex buffers
  38706. for (var key in this._vertexBuffers) {
  38707. var vertexBuffer = this._vertexBuffers[key];
  38708. vertexBuffer._rebuild();
  38709. }
  38710. };
  38711. /**
  38712. * Affects all gemetry data in one call
  38713. * @param vertexData defines the geometry data
  38714. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38715. */
  38716. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38717. vertexData.applyToGeometry(this, updatable);
  38718. this.notifyUpdate();
  38719. };
  38720. /**
  38721. * Set specific vertex data
  38722. * @param kind defines the data kind (Position, normal, etc...)
  38723. * @param data defines the vertex data to use
  38724. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38725. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38726. */
  38727. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38728. if (updatable === void 0) { updatable = false; }
  38729. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38730. this.setVerticesBuffer(buffer);
  38731. };
  38732. /**
  38733. * Removes a specific vertex data
  38734. * @param kind defines the data kind (Position, normal, etc...)
  38735. */
  38736. Geometry.prototype.removeVerticesData = function (kind) {
  38737. if (this._vertexBuffers[kind]) {
  38738. this._vertexBuffers[kind].dispose();
  38739. delete this._vertexBuffers[kind];
  38740. }
  38741. };
  38742. /**
  38743. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38744. * @param buffer defines the vertex buffer to use
  38745. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38746. */
  38747. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38748. if (totalVertices === void 0) { totalVertices = null; }
  38749. var kind = buffer.getKind();
  38750. if (this._vertexBuffers[kind]) {
  38751. this._vertexBuffers[kind].dispose();
  38752. }
  38753. this._vertexBuffers[kind] = buffer;
  38754. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38755. var data = buffer.getData();
  38756. if (totalVertices != null) {
  38757. this._totalVertices = totalVertices;
  38758. }
  38759. else {
  38760. if (data != null) {
  38761. this._totalVertices = data.length / (buffer.byteStride / 4);
  38762. }
  38763. }
  38764. this._updateExtend(data);
  38765. this._resetPointsArrayCache();
  38766. var meshes = this._meshes;
  38767. var numOfMeshes = meshes.length;
  38768. for (var index = 0; index < numOfMeshes; index++) {
  38769. var mesh = meshes[index];
  38770. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38771. mesh._createGlobalSubMesh(false);
  38772. mesh.computeWorldMatrix(true);
  38773. }
  38774. }
  38775. this.notifyUpdate(kind);
  38776. if (this._vertexArrayObjects) {
  38777. this._disposeVertexArrayObjects();
  38778. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38779. }
  38780. };
  38781. /**
  38782. * Update a specific vertex buffer
  38783. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38784. * It will do nothing if the buffer is not updatable
  38785. * @param kind defines the data kind (Position, normal, etc...)
  38786. * @param data defines the data to use
  38787. * @param offset defines the offset in the target buffer where to store the data
  38788. * @param useBytes set to true if the offset is in bytes
  38789. */
  38790. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38791. if (useBytes === void 0) { useBytes = false; }
  38792. var vertexBuffer = this.getVertexBuffer(kind);
  38793. if (!vertexBuffer) {
  38794. return;
  38795. }
  38796. vertexBuffer.updateDirectly(data, offset, useBytes);
  38797. this.notifyUpdate(kind);
  38798. };
  38799. /**
  38800. * Update a specific vertex buffer
  38801. * This function will create a new buffer if the current one is not updatable
  38802. * @param kind defines the data kind (Position, normal, etc...)
  38803. * @param data defines the data to use
  38804. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38805. */
  38806. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38807. if (updateExtends === void 0) { updateExtends = false; }
  38808. var vertexBuffer = this.getVertexBuffer(kind);
  38809. if (!vertexBuffer) {
  38810. return;
  38811. }
  38812. vertexBuffer.update(data);
  38813. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38814. this._updateBoundingInfo(updateExtends, data);
  38815. }
  38816. this.notifyUpdate(kind);
  38817. };
  38818. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38819. if (updateExtends) {
  38820. this._updateExtend(data);
  38821. }
  38822. var meshes = this._meshes;
  38823. var numOfMeshes = meshes.length;
  38824. this._resetPointsArrayCache();
  38825. for (var index = 0; index < numOfMeshes; index++) {
  38826. var mesh = meshes[index];
  38827. if (updateExtends) {
  38828. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38829. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38830. var subMesh = mesh.subMeshes[subIndex];
  38831. subMesh.refreshBoundingInfo();
  38832. }
  38833. }
  38834. }
  38835. };
  38836. /** @hidden */
  38837. Geometry.prototype._bind = function (effect, indexToBind) {
  38838. if (!effect) {
  38839. return;
  38840. }
  38841. if (indexToBind === undefined) {
  38842. indexToBind = this._indexBuffer;
  38843. }
  38844. var vbs = this.getVertexBuffers();
  38845. if (!vbs) {
  38846. return;
  38847. }
  38848. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38849. this._engine.bindBuffers(vbs, indexToBind, effect);
  38850. return;
  38851. }
  38852. // Using VAO
  38853. if (!this._vertexArrayObjects[effect.key]) {
  38854. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38855. }
  38856. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38857. };
  38858. /**
  38859. * Gets total number of vertices
  38860. * @returns the total number of vertices
  38861. */
  38862. Geometry.prototype.getTotalVertices = function () {
  38863. if (!this.isReady()) {
  38864. return 0;
  38865. }
  38866. return this._totalVertices;
  38867. };
  38868. /**
  38869. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38870. * @param kind defines the data kind (Position, normal, etc...)
  38871. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38872. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38873. * @returns a float array containing vertex data
  38874. */
  38875. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38876. var vertexBuffer = this.getVertexBuffer(kind);
  38877. if (!vertexBuffer) {
  38878. return null;
  38879. }
  38880. var data = vertexBuffer.getData();
  38881. if (!data) {
  38882. return null;
  38883. }
  38884. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38885. var count = this._totalVertices * vertexBuffer.getSize();
  38886. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38887. var copy_1 = new Array(count);
  38888. vertexBuffer.forEach(count, function (value, index) {
  38889. copy_1[index] = value;
  38890. });
  38891. return copy_1;
  38892. }
  38893. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38894. if (data instanceof Array) {
  38895. var offset = vertexBuffer.byteOffset / 4;
  38896. return BABYLON.Tools.Slice(data, offset, offset + count);
  38897. }
  38898. else if (data instanceof ArrayBuffer) {
  38899. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38900. }
  38901. else {
  38902. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38903. }
  38904. }
  38905. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38906. return BABYLON.Tools.Slice(data);
  38907. }
  38908. return data;
  38909. };
  38910. /**
  38911. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38912. * @param kind defines the data kind (Position, normal, etc...)
  38913. * @returns true if the vertex buffer with the specified kind is updatable
  38914. */
  38915. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38916. var vb = this._vertexBuffers[kind];
  38917. if (!vb) {
  38918. return false;
  38919. }
  38920. return vb.isUpdatable();
  38921. };
  38922. /**
  38923. * Gets a specific vertex buffer
  38924. * @param kind defines the data kind (Position, normal, etc...)
  38925. * @returns a {BABYLON.VertexBuffer}
  38926. */
  38927. Geometry.prototype.getVertexBuffer = function (kind) {
  38928. if (!this.isReady()) {
  38929. return null;
  38930. }
  38931. return this._vertexBuffers[kind];
  38932. };
  38933. /**
  38934. * Returns all vertex buffers
  38935. * @return an object holding all vertex buffers indexed by kind
  38936. */
  38937. Geometry.prototype.getVertexBuffers = function () {
  38938. if (!this.isReady()) {
  38939. return null;
  38940. }
  38941. return this._vertexBuffers;
  38942. };
  38943. /**
  38944. * Gets a boolean indicating if specific vertex buffer is present
  38945. * @param kind defines the data kind (Position, normal, etc...)
  38946. * @returns true if data is present
  38947. */
  38948. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38949. if (!this._vertexBuffers) {
  38950. if (this._delayInfo) {
  38951. return this._delayInfo.indexOf(kind) !== -1;
  38952. }
  38953. return false;
  38954. }
  38955. return this._vertexBuffers[kind] !== undefined;
  38956. };
  38957. /**
  38958. * Gets a list of all attached data kinds (Position, normal, etc...)
  38959. * @returns a list of string containing all kinds
  38960. */
  38961. Geometry.prototype.getVerticesDataKinds = function () {
  38962. var result = [];
  38963. var kind;
  38964. if (!this._vertexBuffers && this._delayInfo) {
  38965. for (kind in this._delayInfo) {
  38966. result.push(kind);
  38967. }
  38968. }
  38969. else {
  38970. for (kind in this._vertexBuffers) {
  38971. result.push(kind);
  38972. }
  38973. }
  38974. return result;
  38975. };
  38976. /**
  38977. * Update index buffer
  38978. * @param indices defines the indices to store in the index buffer
  38979. * @param offset defines the offset in the target buffer where to store the data
  38980. */
  38981. Geometry.prototype.updateIndices = function (indices, offset) {
  38982. if (!this._indexBuffer) {
  38983. return;
  38984. }
  38985. if (!this._indexBufferIsUpdatable) {
  38986. this.setIndices(indices, null, true);
  38987. }
  38988. else {
  38989. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38990. }
  38991. };
  38992. /**
  38993. * Creates a new index buffer
  38994. * @param indices defines the indices to store in the index buffer
  38995. * @param totalVertices defines the total number of vertices (could be null)
  38996. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38997. */
  38998. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38999. if (totalVertices === void 0) { totalVertices = null; }
  39000. if (updatable === void 0) { updatable = false; }
  39001. if (this._indexBuffer) {
  39002. this._engine._releaseBuffer(this._indexBuffer);
  39003. }
  39004. this._disposeVertexArrayObjects();
  39005. this._indices = indices;
  39006. this._indexBufferIsUpdatable = updatable;
  39007. if (this._meshes.length !== 0 && this._indices) {
  39008. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39009. }
  39010. if (totalVertices != undefined) { // including null and undefined
  39011. this._totalVertices = totalVertices;
  39012. }
  39013. var meshes = this._meshes;
  39014. var numOfMeshes = meshes.length;
  39015. for (var index = 0; index < numOfMeshes; index++) {
  39016. meshes[index]._createGlobalSubMesh(true);
  39017. }
  39018. this.notifyUpdate();
  39019. };
  39020. /**
  39021. * Return the total number of indices
  39022. * @returns the total number of indices
  39023. */
  39024. Geometry.prototype.getTotalIndices = function () {
  39025. if (!this.isReady()) {
  39026. return 0;
  39027. }
  39028. return this._indices.length;
  39029. };
  39030. /**
  39031. * Gets the index buffer array
  39032. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39033. * @returns the index buffer array
  39034. */
  39035. Geometry.prototype.getIndices = function (copyWhenShared) {
  39036. if (!this.isReady()) {
  39037. return null;
  39038. }
  39039. var orig = this._indices;
  39040. if (!copyWhenShared || this._meshes.length === 1) {
  39041. return orig;
  39042. }
  39043. else {
  39044. var len = orig.length;
  39045. var copy = [];
  39046. for (var i = 0; i < len; i++) {
  39047. copy.push(orig[i]);
  39048. }
  39049. return copy;
  39050. }
  39051. };
  39052. /**
  39053. * Gets the index buffer
  39054. * @return the index buffer
  39055. */
  39056. Geometry.prototype.getIndexBuffer = function () {
  39057. if (!this.isReady()) {
  39058. return null;
  39059. }
  39060. return this._indexBuffer;
  39061. };
  39062. /** @hidden */
  39063. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39064. if (effect === void 0) { effect = null; }
  39065. if (!effect || !this._vertexArrayObjects) {
  39066. return;
  39067. }
  39068. if (this._vertexArrayObjects[effect.key]) {
  39069. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39070. delete this._vertexArrayObjects[effect.key];
  39071. }
  39072. };
  39073. /**
  39074. * Release the associated resources for a specific mesh
  39075. * @param mesh defines the source mesh
  39076. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39077. */
  39078. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39079. var meshes = this._meshes;
  39080. var index = meshes.indexOf(mesh);
  39081. if (index === -1) {
  39082. return;
  39083. }
  39084. meshes.splice(index, 1);
  39085. mesh._geometry = null;
  39086. if (meshes.length === 0 && shouldDispose) {
  39087. this.dispose();
  39088. }
  39089. };
  39090. /**
  39091. * Apply current geometry to a given mesh
  39092. * @param mesh defines the mesh to apply geometry to
  39093. */
  39094. Geometry.prototype.applyToMesh = function (mesh) {
  39095. if (mesh._geometry === this) {
  39096. return;
  39097. }
  39098. var previousGeometry = mesh._geometry;
  39099. if (previousGeometry) {
  39100. previousGeometry.releaseForMesh(mesh);
  39101. }
  39102. var meshes = this._meshes;
  39103. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39104. mesh._geometry = this;
  39105. this._scene.pushGeometry(this);
  39106. meshes.push(mesh);
  39107. if (this.isReady()) {
  39108. this._applyToMesh(mesh);
  39109. }
  39110. else {
  39111. mesh._boundingInfo = this._boundingInfo;
  39112. }
  39113. };
  39114. Geometry.prototype._updateExtend = function (data) {
  39115. if (data === void 0) { data = null; }
  39116. if (!data) {
  39117. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39118. }
  39119. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39120. };
  39121. Geometry.prototype._applyToMesh = function (mesh) {
  39122. var numOfMeshes = this._meshes.length;
  39123. // vertexBuffers
  39124. for (var kind in this._vertexBuffers) {
  39125. if (numOfMeshes === 1) {
  39126. this._vertexBuffers[kind].create();
  39127. }
  39128. var buffer = this._vertexBuffers[kind].getBuffer();
  39129. if (buffer)
  39130. buffer.references = numOfMeshes;
  39131. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39132. if (!this._extend) {
  39133. this._updateExtend();
  39134. }
  39135. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39136. mesh._createGlobalSubMesh(false);
  39137. //bounding info was just created again, world matrix should be applied again.
  39138. mesh._updateBoundingInfo();
  39139. }
  39140. }
  39141. // indexBuffer
  39142. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39143. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39144. }
  39145. if (this._indexBuffer) {
  39146. this._indexBuffer.references = numOfMeshes;
  39147. }
  39148. };
  39149. Geometry.prototype.notifyUpdate = function (kind) {
  39150. if (this.onGeometryUpdated) {
  39151. this.onGeometryUpdated(this, kind);
  39152. }
  39153. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39154. var mesh = _a[_i];
  39155. mesh._markSubMeshesAsAttributesDirty();
  39156. }
  39157. };
  39158. /**
  39159. * Load the geometry if it was flagged as delay loaded
  39160. * @param scene defines the hosting scene
  39161. * @param onLoaded defines a callback called when the geometry is loaded
  39162. */
  39163. Geometry.prototype.load = function (scene, onLoaded) {
  39164. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39165. return;
  39166. }
  39167. if (this.isReady()) {
  39168. if (onLoaded) {
  39169. onLoaded();
  39170. }
  39171. return;
  39172. }
  39173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39174. this._queueLoad(scene, onLoaded);
  39175. };
  39176. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39177. var _this = this;
  39178. if (!this.delayLoadingFile) {
  39179. return;
  39180. }
  39181. scene._addPendingData(this);
  39182. scene._loadFile(this.delayLoadingFile, function (data) {
  39183. if (!_this._delayLoadingFunction) {
  39184. return;
  39185. }
  39186. _this._delayLoadingFunction(JSON.parse(data), _this);
  39187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39188. _this._delayInfo = [];
  39189. scene._removePendingData(_this);
  39190. var meshes = _this._meshes;
  39191. var numOfMeshes = meshes.length;
  39192. for (var index = 0; index < numOfMeshes; index++) {
  39193. _this._applyToMesh(meshes[index]);
  39194. }
  39195. if (onLoaded) {
  39196. onLoaded();
  39197. }
  39198. }, undefined, true);
  39199. };
  39200. /**
  39201. * Invert the geometry to move from a right handed system to a left handed one.
  39202. */
  39203. Geometry.prototype.toLeftHanded = function () {
  39204. // Flip faces
  39205. var tIndices = this.getIndices(false);
  39206. if (tIndices != null && tIndices.length > 0) {
  39207. for (var i = 0; i < tIndices.length; i += 3) {
  39208. var tTemp = tIndices[i + 0];
  39209. tIndices[i + 0] = tIndices[i + 2];
  39210. tIndices[i + 2] = tTemp;
  39211. }
  39212. this.setIndices(tIndices);
  39213. }
  39214. // Negate position.z
  39215. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39216. if (tPositions != null && tPositions.length > 0) {
  39217. for (var i = 0; i < tPositions.length; i += 3) {
  39218. tPositions[i + 2] = -tPositions[i + 2];
  39219. }
  39220. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39221. }
  39222. // Negate normal.z
  39223. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39224. if (tNormals != null && tNormals.length > 0) {
  39225. for (var i = 0; i < tNormals.length; i += 3) {
  39226. tNormals[i + 2] = -tNormals[i + 2];
  39227. }
  39228. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39229. }
  39230. };
  39231. // Cache
  39232. /** @hidden */
  39233. Geometry.prototype._resetPointsArrayCache = function () {
  39234. this._positions = null;
  39235. };
  39236. /** @hidden */
  39237. Geometry.prototype._generatePointsArray = function () {
  39238. if (this._positions)
  39239. return true;
  39240. this._positions = [];
  39241. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39242. if (!data) {
  39243. return false;
  39244. }
  39245. for (var index = 0; index < data.length; index += 3) {
  39246. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39247. }
  39248. return true;
  39249. };
  39250. /**
  39251. * Gets a value indicating if the geometry is disposed
  39252. * @returns true if the geometry was disposed
  39253. */
  39254. Geometry.prototype.isDisposed = function () {
  39255. return this._isDisposed;
  39256. };
  39257. Geometry.prototype._disposeVertexArrayObjects = function () {
  39258. if (this._vertexArrayObjects) {
  39259. for (var kind in this._vertexArrayObjects) {
  39260. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39261. }
  39262. this._vertexArrayObjects = {};
  39263. }
  39264. };
  39265. /**
  39266. * Free all associated resources
  39267. */
  39268. Geometry.prototype.dispose = function () {
  39269. var meshes = this._meshes;
  39270. var numOfMeshes = meshes.length;
  39271. var index;
  39272. for (index = 0; index < numOfMeshes; index++) {
  39273. this.releaseForMesh(meshes[index]);
  39274. }
  39275. this._meshes = [];
  39276. this._disposeVertexArrayObjects();
  39277. for (var kind in this._vertexBuffers) {
  39278. this._vertexBuffers[kind].dispose();
  39279. }
  39280. this._vertexBuffers = {};
  39281. this._totalVertices = 0;
  39282. if (this._indexBuffer) {
  39283. this._engine._releaseBuffer(this._indexBuffer);
  39284. }
  39285. this._indexBuffer = null;
  39286. this._indices = [];
  39287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39288. this.delayLoadingFile = null;
  39289. this._delayLoadingFunction = null;
  39290. this._delayInfo = [];
  39291. this._boundingInfo = null;
  39292. this._scene.removeGeometry(this);
  39293. this._isDisposed = true;
  39294. };
  39295. /**
  39296. * Clone the current geometry into a new geometry
  39297. * @param id defines the unique ID of the new geometry
  39298. * @returns a new geometry object
  39299. */
  39300. Geometry.prototype.copy = function (id) {
  39301. var vertexData = new BABYLON.VertexData();
  39302. vertexData.indices = [];
  39303. var indices = this.getIndices();
  39304. if (indices) {
  39305. for (var index = 0; index < indices.length; index++) {
  39306. vertexData.indices.push(indices[index]);
  39307. }
  39308. }
  39309. var updatable = false;
  39310. var stopChecking = false;
  39311. var kind;
  39312. for (kind in this._vertexBuffers) {
  39313. // using slice() to make a copy of the array and not just reference it
  39314. var data = this.getVerticesData(kind);
  39315. if (data instanceof Float32Array) {
  39316. vertexData.set(new Float32Array(data), kind);
  39317. }
  39318. else {
  39319. vertexData.set(data.slice(0), kind);
  39320. }
  39321. if (!stopChecking) {
  39322. var vb = this.getVertexBuffer(kind);
  39323. if (vb) {
  39324. updatable = vb.isUpdatable();
  39325. stopChecking = !updatable;
  39326. }
  39327. }
  39328. }
  39329. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39330. geometry.delayLoadState = this.delayLoadState;
  39331. geometry.delayLoadingFile = this.delayLoadingFile;
  39332. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39333. for (kind in this._delayInfo) {
  39334. geometry._delayInfo = geometry._delayInfo || [];
  39335. geometry._delayInfo.push(kind);
  39336. }
  39337. // Bounding info
  39338. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39339. return geometry;
  39340. };
  39341. /**
  39342. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39343. * @return a JSON representation of the current geometry data (without the vertices data)
  39344. */
  39345. Geometry.prototype.serialize = function () {
  39346. var serializationObject = {};
  39347. serializationObject.id = this.id;
  39348. serializationObject.updatable = this._updatable;
  39349. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39350. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39351. }
  39352. return serializationObject;
  39353. };
  39354. Geometry.prototype.toNumberArray = function (origin) {
  39355. if (Array.isArray(origin)) {
  39356. return origin;
  39357. }
  39358. else {
  39359. return Array.prototype.slice.call(origin);
  39360. }
  39361. };
  39362. /**
  39363. * Serialize all vertices data into a JSON oject
  39364. * @returns a JSON representation of the current geometry data
  39365. */
  39366. Geometry.prototype.serializeVerticeData = function () {
  39367. var serializationObject = this.serialize();
  39368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39369. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39371. serializationObject.positions._updatable = true;
  39372. }
  39373. }
  39374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39375. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39376. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39377. serializationObject.normals._updatable = true;
  39378. }
  39379. }
  39380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39381. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39382. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39383. serializationObject.tangets._updatable = true;
  39384. }
  39385. }
  39386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39387. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39388. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39389. serializationObject.uvs._updatable = true;
  39390. }
  39391. }
  39392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39393. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39395. serializationObject.uv2s._updatable = true;
  39396. }
  39397. }
  39398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39399. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39401. serializationObject.uv3s._updatable = true;
  39402. }
  39403. }
  39404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39405. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39406. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39407. serializationObject.uv4s._updatable = true;
  39408. }
  39409. }
  39410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39411. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39413. serializationObject.uv5s._updatable = true;
  39414. }
  39415. }
  39416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39417. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39419. serializationObject.uv6s._updatable = true;
  39420. }
  39421. }
  39422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39423. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39424. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39425. serializationObject.colors._updatable = true;
  39426. }
  39427. }
  39428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39429. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39430. serializationObject.matricesIndices._isExpanded = true;
  39431. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39432. serializationObject.matricesIndices._updatable = true;
  39433. }
  39434. }
  39435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39436. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39437. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39438. serializationObject.matricesWeights._updatable = true;
  39439. }
  39440. }
  39441. serializationObject.indices = this.toNumberArray(this.getIndices());
  39442. return serializationObject;
  39443. };
  39444. // Statics
  39445. /**
  39446. * Extracts a clone of a mesh geometry
  39447. * @param mesh defines the source mesh
  39448. * @param id defines the unique ID of the new geometry object
  39449. * @returns the new geometry object
  39450. */
  39451. Geometry.ExtractFromMesh = function (mesh, id) {
  39452. var geometry = mesh._geometry;
  39453. if (!geometry) {
  39454. return null;
  39455. }
  39456. return geometry.copy(id);
  39457. };
  39458. /**
  39459. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39460. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39461. * Be aware Math.random() could cause collisions, but:
  39462. * "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"
  39463. * @returns a string containing a new GUID
  39464. */
  39465. Geometry.RandomId = function () {
  39466. return BABYLON.Tools.RandomId();
  39467. };
  39468. /** @hidden */
  39469. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39470. var scene = mesh.getScene();
  39471. // Geometry
  39472. var geometryId = parsedGeometry.geometryId;
  39473. if (geometryId) {
  39474. var geometry = scene.getGeometryByID(geometryId);
  39475. if (geometry) {
  39476. geometry.applyToMesh(mesh);
  39477. }
  39478. }
  39479. else if (parsedGeometry instanceof ArrayBuffer) {
  39480. var binaryInfo = mesh._binaryInfo;
  39481. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39482. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39483. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39484. }
  39485. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39486. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39487. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39488. }
  39489. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39490. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39491. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39492. }
  39493. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39494. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39496. }
  39497. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39498. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39500. }
  39501. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39502. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39504. }
  39505. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39506. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39508. }
  39509. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39510. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39512. }
  39513. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39514. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39515. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39516. }
  39517. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39518. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39520. }
  39521. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39522. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39524. }
  39525. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39526. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39528. }
  39529. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39530. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39531. mesh.setIndices(indicesData, null);
  39532. }
  39533. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39534. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39535. mesh.subMeshes = [];
  39536. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39537. var materialIndex = subMeshesData[(i * 5) + 0];
  39538. var verticesStart = subMeshesData[(i * 5) + 1];
  39539. var verticesCount = subMeshesData[(i * 5) + 2];
  39540. var indexStart = subMeshesData[(i * 5) + 3];
  39541. var indexCount = subMeshesData[(i * 5) + 4];
  39542. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39543. }
  39544. }
  39545. }
  39546. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39547. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39548. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39549. if (parsedGeometry.tangents) {
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39551. }
  39552. if (parsedGeometry.uvs) {
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39554. }
  39555. if (parsedGeometry.uvs2) {
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39557. }
  39558. if (parsedGeometry.uvs3) {
  39559. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39560. }
  39561. if (parsedGeometry.uvs4) {
  39562. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39563. }
  39564. if (parsedGeometry.uvs5) {
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39566. }
  39567. if (parsedGeometry.uvs6) {
  39568. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39569. }
  39570. if (parsedGeometry.colors) {
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39572. }
  39573. if (parsedGeometry.matricesIndices) {
  39574. if (!parsedGeometry.matricesIndices._isExpanded) {
  39575. var floatIndices = [];
  39576. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39577. var matricesIndex = parsedGeometry.matricesIndices[i];
  39578. floatIndices.push(matricesIndex & 0x000000FF);
  39579. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39580. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39581. floatIndices.push(matricesIndex >> 24);
  39582. }
  39583. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39584. }
  39585. else {
  39586. delete parsedGeometry.matricesIndices._isExpanded;
  39587. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39588. }
  39589. }
  39590. if (parsedGeometry.matricesIndicesExtra) {
  39591. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39592. var floatIndices = [];
  39593. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39594. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39595. floatIndices.push(matricesIndex & 0x000000FF);
  39596. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39597. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39598. floatIndices.push(matricesIndex >> 24);
  39599. }
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39601. }
  39602. else {
  39603. delete parsedGeometry.matricesIndices._isExpanded;
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39605. }
  39606. }
  39607. if (parsedGeometry.matricesWeights) {
  39608. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39610. }
  39611. if (parsedGeometry.matricesWeightsExtra) {
  39612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39613. }
  39614. mesh.setIndices(parsedGeometry.indices, null);
  39615. }
  39616. // SubMeshes
  39617. if (parsedGeometry.subMeshes) {
  39618. mesh.subMeshes = [];
  39619. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39620. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39621. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39622. }
  39623. }
  39624. // Flat shading
  39625. if (mesh._shouldGenerateFlatShading) {
  39626. mesh.convertToFlatShadedMesh();
  39627. delete mesh._shouldGenerateFlatShading;
  39628. }
  39629. // Update
  39630. mesh.computeWorldMatrix(true);
  39631. // Octree
  39632. var sceneOctree = scene.selectionOctree;
  39633. if (sceneOctree !== undefined && sceneOctree !== null) {
  39634. sceneOctree.addMesh(mesh);
  39635. }
  39636. };
  39637. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39638. var epsilon = 1e-3;
  39639. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39640. return;
  39641. }
  39642. var noInfluenceBoneIndex = 0.0;
  39643. if (parsedGeometry.skeletonId > -1) {
  39644. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39645. if (!skeleton) {
  39646. return;
  39647. }
  39648. noInfluenceBoneIndex = skeleton.bones.length;
  39649. }
  39650. else {
  39651. return;
  39652. }
  39653. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39654. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39655. var matricesWeights = parsedGeometry.matricesWeights;
  39656. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39657. var influencers = parsedGeometry.numBoneInfluencer;
  39658. var size = matricesWeights.length;
  39659. for (var i = 0; i < size; i += 4) {
  39660. var weight = 0.0;
  39661. var firstZeroWeight = -1;
  39662. for (var j = 0; j < 4; j++) {
  39663. var w = matricesWeights[i + j];
  39664. weight += w;
  39665. if (w < epsilon && firstZeroWeight < 0) {
  39666. firstZeroWeight = j;
  39667. }
  39668. }
  39669. if (matricesWeightsExtra) {
  39670. for (var j = 0; j < 4; j++) {
  39671. var w = matricesWeightsExtra[i + j];
  39672. weight += w;
  39673. if (w < epsilon && firstZeroWeight < 0) {
  39674. firstZeroWeight = j + 4;
  39675. }
  39676. }
  39677. }
  39678. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39679. firstZeroWeight = influencers - 1;
  39680. }
  39681. if (weight > epsilon) {
  39682. var mweight = 1.0 / weight;
  39683. for (var j = 0; j < 4; j++) {
  39684. matricesWeights[i + j] *= mweight;
  39685. }
  39686. if (matricesWeightsExtra) {
  39687. for (var j = 0; j < 4; j++) {
  39688. matricesWeightsExtra[i + j] *= mweight;
  39689. }
  39690. }
  39691. }
  39692. else {
  39693. if (firstZeroWeight >= 4) {
  39694. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39695. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39696. }
  39697. else {
  39698. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39699. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39700. }
  39701. }
  39702. }
  39703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39704. if (parsedGeometry.matricesWeightsExtra) {
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39706. }
  39707. };
  39708. /**
  39709. * Create a new geometry from persisted data (Using .babylon file format)
  39710. * @param parsedVertexData defines the persisted data
  39711. * @param scene defines the hosting scene
  39712. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39713. * @returns the new geometry object
  39714. */
  39715. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39716. if (scene.getGeometryByID(parsedVertexData.id)) {
  39717. return null; // null since geometry could be something else than a box...
  39718. }
  39719. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39720. if (BABYLON.Tags) {
  39721. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39722. }
  39723. if (parsedVertexData.delayLoadingFile) {
  39724. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39725. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39726. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39727. geometry._delayInfo = [];
  39728. if (parsedVertexData.hasUVs) {
  39729. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39730. }
  39731. if (parsedVertexData.hasUVs2) {
  39732. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39733. }
  39734. if (parsedVertexData.hasUVs3) {
  39735. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39736. }
  39737. if (parsedVertexData.hasUVs4) {
  39738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39739. }
  39740. if (parsedVertexData.hasUVs5) {
  39741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39742. }
  39743. if (parsedVertexData.hasUVs6) {
  39744. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39745. }
  39746. if (parsedVertexData.hasColors) {
  39747. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39748. }
  39749. if (parsedVertexData.hasMatricesIndices) {
  39750. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39751. }
  39752. if (parsedVertexData.hasMatricesWeights) {
  39753. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39754. }
  39755. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39756. }
  39757. else {
  39758. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39759. }
  39760. scene.pushGeometry(geometry, true);
  39761. return geometry;
  39762. };
  39763. return Geometry;
  39764. }());
  39765. BABYLON.Geometry = Geometry;
  39766. // Primitives
  39767. /// Abstract class
  39768. /**
  39769. * Abstract class used to provide common services for all typed geometries
  39770. * @hidden
  39771. */
  39772. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39773. __extends(_PrimitiveGeometry, _super);
  39774. /**
  39775. * Creates a new typed geometry
  39776. * @param id defines the unique ID of the geometry
  39777. * @param scene defines the hosting scene
  39778. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39779. * @param mesh defines the hosting mesh (can be null)
  39780. */
  39781. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39782. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39783. if (mesh === void 0) { mesh = null; }
  39784. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39785. _this._canBeRegenerated = _canBeRegenerated;
  39786. _this._beingRegenerated = true;
  39787. _this.regenerate();
  39788. _this._beingRegenerated = false;
  39789. return _this;
  39790. }
  39791. /**
  39792. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39793. * @returns true if the geometry can be regenerated
  39794. */
  39795. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39796. return this._canBeRegenerated;
  39797. };
  39798. /**
  39799. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39800. */
  39801. _PrimitiveGeometry.prototype.regenerate = function () {
  39802. if (!this._canBeRegenerated) {
  39803. return;
  39804. }
  39805. this._beingRegenerated = true;
  39806. this.setAllVerticesData(this._regenerateVertexData(), false);
  39807. this._beingRegenerated = false;
  39808. };
  39809. /**
  39810. * Clone the geometry
  39811. * @param id defines the unique ID of the new geometry
  39812. * @returns the new geometry
  39813. */
  39814. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39815. return _super.prototype.copy.call(this, id);
  39816. };
  39817. // overrides
  39818. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39819. if (!this._beingRegenerated) {
  39820. return;
  39821. }
  39822. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39823. };
  39824. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39825. if (!this._beingRegenerated) {
  39826. return;
  39827. }
  39828. _super.prototype.setVerticesData.call(this, kind, data, false);
  39829. };
  39830. // to override
  39831. /** @hidden */
  39832. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39833. throw new Error("Abstract method");
  39834. };
  39835. _PrimitiveGeometry.prototype.copy = function (id) {
  39836. throw new Error("Must be overriden in sub-classes.");
  39837. };
  39838. _PrimitiveGeometry.prototype.serialize = function () {
  39839. var serializationObject = _super.prototype.serialize.call(this);
  39840. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39841. return serializationObject;
  39842. };
  39843. return _PrimitiveGeometry;
  39844. }(Geometry));
  39845. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39846. /**
  39847. * Creates a ribbon geometry
  39848. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39849. */
  39850. var RibbonGeometry = /** @class */ (function (_super) {
  39851. __extends(RibbonGeometry, _super);
  39852. /**
  39853. * Creates a ribbon geometry
  39854. * @param id defines the unique ID of the geometry
  39855. * @param scene defines the hosting scene
  39856. * @param pathArray defines the array of paths to use
  39857. * @param closeArray defines if the last path and the first path must be joined
  39858. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39859. * @param offset defines the offset between points
  39860. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39861. * @param mesh defines the hosting mesh (can be null)
  39862. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39863. */
  39864. function RibbonGeometry(id, scene,
  39865. /**
  39866. * Defines the array of paths to use
  39867. */
  39868. pathArray,
  39869. /**
  39870. * Defines if the last and first points of each path in your pathArray must be joined
  39871. */
  39872. closeArray,
  39873. /**
  39874. * Defines if the last and first points of each path in your pathArray must be joined
  39875. */
  39876. closePath,
  39877. /**
  39878. * Defines the offset between points
  39879. */
  39880. offset, canBeRegenerated, mesh,
  39881. /**
  39882. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39883. */
  39884. side) {
  39885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39887. _this.pathArray = pathArray;
  39888. _this.closeArray = closeArray;
  39889. _this.closePath = closePath;
  39890. _this.offset = offset;
  39891. _this.side = side;
  39892. return _this;
  39893. }
  39894. /** @hidden */
  39895. RibbonGeometry.prototype._regenerateVertexData = function () {
  39896. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39897. };
  39898. RibbonGeometry.prototype.copy = function (id) {
  39899. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39900. };
  39901. return RibbonGeometry;
  39902. }(_PrimitiveGeometry));
  39903. BABYLON.RibbonGeometry = RibbonGeometry;
  39904. /**
  39905. * Creates a box geometry
  39906. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39907. */
  39908. var BoxGeometry = /** @class */ (function (_super) {
  39909. __extends(BoxGeometry, _super);
  39910. /**
  39911. * Creates a box geometry
  39912. * @param id defines the unique ID of the geometry
  39913. * @param scene defines the hosting scene
  39914. * @param size defines the zise of the box (width, height and depth are the same)
  39915. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39916. * @param mesh defines the hosting mesh (can be null)
  39917. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39918. */
  39919. function BoxGeometry(id, scene,
  39920. /**
  39921. * Defines the zise of the box (width, height and depth are the same)
  39922. */
  39923. size, canBeRegenerated, mesh,
  39924. /**
  39925. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39926. */
  39927. side) {
  39928. if (mesh === void 0) { mesh = null; }
  39929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39931. _this.size = size;
  39932. _this.side = side;
  39933. return _this;
  39934. }
  39935. BoxGeometry.prototype._regenerateVertexData = function () {
  39936. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39937. };
  39938. BoxGeometry.prototype.copy = function (id) {
  39939. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39940. };
  39941. BoxGeometry.prototype.serialize = function () {
  39942. var serializationObject = _super.prototype.serialize.call(this);
  39943. serializationObject.size = this.size;
  39944. return serializationObject;
  39945. };
  39946. BoxGeometry.Parse = function (parsedBox, scene) {
  39947. if (scene.getGeometryByID(parsedBox.id)) {
  39948. return null; // null since geometry could be something else than a box...
  39949. }
  39950. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39951. if (BABYLON.Tags) {
  39952. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39953. }
  39954. scene.pushGeometry(box, true);
  39955. return box;
  39956. };
  39957. return BoxGeometry;
  39958. }(_PrimitiveGeometry));
  39959. BABYLON.BoxGeometry = BoxGeometry;
  39960. /**
  39961. * Creates a sphere geometry
  39962. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39963. */
  39964. var SphereGeometry = /** @class */ (function (_super) {
  39965. __extends(SphereGeometry, _super);
  39966. /**
  39967. * Create a new sphere geometry
  39968. * @param id defines the unique ID of the geometry
  39969. * @param scene defines the hosting scene
  39970. * @param segments defines the number of segments to use to create the sphere
  39971. * @param diameter defines the diameter of the sphere
  39972. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39973. * @param mesh defines the hosting mesh (can be null)
  39974. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39975. */
  39976. function SphereGeometry(id, scene,
  39977. /**
  39978. * Defines the number of segments to use to create the sphere
  39979. */
  39980. segments,
  39981. /**
  39982. * Defines the diameter of the sphere
  39983. */
  39984. diameter, canBeRegenerated, mesh,
  39985. /**
  39986. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39987. */
  39988. side) {
  39989. if (mesh === void 0) { mesh = null; }
  39990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39992. _this.segments = segments;
  39993. _this.diameter = diameter;
  39994. _this.side = side;
  39995. return _this;
  39996. }
  39997. SphereGeometry.prototype._regenerateVertexData = function () {
  39998. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39999. };
  40000. SphereGeometry.prototype.copy = function (id) {
  40001. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40002. };
  40003. SphereGeometry.prototype.serialize = function () {
  40004. var serializationObject = _super.prototype.serialize.call(this);
  40005. serializationObject.segments = this.segments;
  40006. serializationObject.diameter = this.diameter;
  40007. return serializationObject;
  40008. };
  40009. SphereGeometry.Parse = function (parsedSphere, scene) {
  40010. if (scene.getGeometryByID(parsedSphere.id)) {
  40011. return null; // null since geometry could be something else than a sphere...
  40012. }
  40013. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40014. if (BABYLON.Tags) {
  40015. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40016. }
  40017. scene.pushGeometry(sphere, true);
  40018. return sphere;
  40019. };
  40020. return SphereGeometry;
  40021. }(_PrimitiveGeometry));
  40022. BABYLON.SphereGeometry = SphereGeometry;
  40023. /**
  40024. * Creates a disc geometry
  40025. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40026. */
  40027. var DiscGeometry = /** @class */ (function (_super) {
  40028. __extends(DiscGeometry, _super);
  40029. /**
  40030. * Creates a new disc geometry
  40031. * @param id defines the unique ID of the geometry
  40032. * @param scene defines the hosting scene
  40033. * @param radius defines the radius of the disc
  40034. * @param tessellation defines the tesselation factor to apply to the disc
  40035. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40036. * @param mesh defines the hosting mesh (can be null)
  40037. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40038. */
  40039. function DiscGeometry(id, scene,
  40040. /**
  40041. * Defines the radius of the disc
  40042. */
  40043. radius,
  40044. /**
  40045. * Defines the tesselation factor to apply to the disc
  40046. */
  40047. tessellation, canBeRegenerated, mesh,
  40048. /**
  40049. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40050. */
  40051. side) {
  40052. if (mesh === void 0) { mesh = null; }
  40053. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40054. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40055. _this.radius = radius;
  40056. _this.tessellation = tessellation;
  40057. _this.side = side;
  40058. return _this;
  40059. }
  40060. DiscGeometry.prototype._regenerateVertexData = function () {
  40061. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40062. };
  40063. DiscGeometry.prototype.copy = function (id) {
  40064. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40065. };
  40066. return DiscGeometry;
  40067. }(_PrimitiveGeometry));
  40068. BABYLON.DiscGeometry = DiscGeometry;
  40069. /**
  40070. * Creates a new cylinder geometry
  40071. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40072. */
  40073. var CylinderGeometry = /** @class */ (function (_super) {
  40074. __extends(CylinderGeometry, _super);
  40075. /**
  40076. * Creates a new cylinder geometry
  40077. * @param id defines the unique ID of the geometry
  40078. * @param scene defines the hosting scene
  40079. * @param height defines the height of the cylinder
  40080. * @param diameterTop defines the diameter of the cylinder's top cap
  40081. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40082. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40083. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40085. * @param mesh defines the hosting mesh (can be null)
  40086. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40087. */
  40088. function CylinderGeometry(id, scene,
  40089. /**
  40090. * Defines the height of the cylinder
  40091. */
  40092. height,
  40093. /**
  40094. * Defines the diameter of the cylinder's top cap
  40095. */
  40096. diameterTop,
  40097. /**
  40098. * Defines the diameter of the cylinder's bottom cap
  40099. */
  40100. diameterBottom,
  40101. /**
  40102. * Defines the tessellation factor to apply to the cylinder
  40103. */
  40104. tessellation,
  40105. /**
  40106. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40107. */
  40108. subdivisions, canBeRegenerated, mesh,
  40109. /**
  40110. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40111. */
  40112. side) {
  40113. if (subdivisions === void 0) { subdivisions = 1; }
  40114. if (mesh === void 0) { mesh = null; }
  40115. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40116. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40117. _this.height = height;
  40118. _this.diameterTop = diameterTop;
  40119. _this.diameterBottom = diameterBottom;
  40120. _this.tessellation = tessellation;
  40121. _this.subdivisions = subdivisions;
  40122. _this.side = side;
  40123. return _this;
  40124. }
  40125. CylinderGeometry.prototype._regenerateVertexData = function () {
  40126. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40127. };
  40128. CylinderGeometry.prototype.copy = function (id) {
  40129. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40130. };
  40131. CylinderGeometry.prototype.serialize = function () {
  40132. var serializationObject = _super.prototype.serialize.call(this);
  40133. serializationObject.height = this.height;
  40134. serializationObject.diameterTop = this.diameterTop;
  40135. serializationObject.diameterBottom = this.diameterBottom;
  40136. serializationObject.tessellation = this.tessellation;
  40137. return serializationObject;
  40138. };
  40139. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40140. if (scene.getGeometryByID(parsedCylinder.id)) {
  40141. return null; // null since geometry could be something else than a cylinder...
  40142. }
  40143. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40144. if (BABYLON.Tags) {
  40145. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40146. }
  40147. scene.pushGeometry(cylinder, true);
  40148. return cylinder;
  40149. };
  40150. return CylinderGeometry;
  40151. }(_PrimitiveGeometry));
  40152. BABYLON.CylinderGeometry = CylinderGeometry;
  40153. /**
  40154. * Creates a new torus geometry
  40155. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40156. */
  40157. var TorusGeometry = /** @class */ (function (_super) {
  40158. __extends(TorusGeometry, _super);
  40159. /**
  40160. * Creates a new torus geometry
  40161. * @param id defines the unique ID of the geometry
  40162. * @param scene defines the hosting scene
  40163. * @param diameter defines the diameter of the torus
  40164. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40165. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40166. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40167. * @param mesh defines the hosting mesh (can be null)
  40168. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40169. */
  40170. function TorusGeometry(id, scene,
  40171. /**
  40172. * Defines the diameter of the torus
  40173. */
  40174. diameter,
  40175. /**
  40176. * Defines the thickness of the torus (ie. internal diameter)
  40177. */
  40178. thickness,
  40179. /**
  40180. * Defines the tesselation factor to apply to the torus
  40181. */
  40182. tessellation, canBeRegenerated, mesh,
  40183. /**
  40184. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40185. */
  40186. side) {
  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.diameter = diameter;
  40191. _this.thickness = thickness;
  40192. _this.tessellation = tessellation;
  40193. _this.side = side;
  40194. return _this;
  40195. }
  40196. TorusGeometry.prototype._regenerateVertexData = function () {
  40197. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40198. };
  40199. TorusGeometry.prototype.copy = function (id) {
  40200. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40201. };
  40202. TorusGeometry.prototype.serialize = function () {
  40203. var serializationObject = _super.prototype.serialize.call(this);
  40204. serializationObject.diameter = this.diameter;
  40205. serializationObject.thickness = this.thickness;
  40206. serializationObject.tessellation = this.tessellation;
  40207. return serializationObject;
  40208. };
  40209. TorusGeometry.Parse = function (parsedTorus, scene) {
  40210. if (scene.getGeometryByID(parsedTorus.id)) {
  40211. return null; // null since geometry could be something else than a torus...
  40212. }
  40213. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40214. if (BABYLON.Tags) {
  40215. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40216. }
  40217. scene.pushGeometry(torus, true);
  40218. return torus;
  40219. };
  40220. return TorusGeometry;
  40221. }(_PrimitiveGeometry));
  40222. BABYLON.TorusGeometry = TorusGeometry;
  40223. /**
  40224. * Creates a new ground geometry
  40225. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40226. */
  40227. var GroundGeometry = /** @class */ (function (_super) {
  40228. __extends(GroundGeometry, _super);
  40229. /**
  40230. * Creates a new ground geometry
  40231. * @param id defines the unique ID of the geometry
  40232. * @param scene defines the hosting scene
  40233. * @param width defines the width of the ground
  40234. * @param height defines the height of the ground
  40235. * @param subdivisions defines the subdivisions to apply to the ground
  40236. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40237. * @param mesh defines the hosting mesh (can be null)
  40238. */
  40239. function GroundGeometry(id, scene,
  40240. /**
  40241. * Defines the width of the ground
  40242. */
  40243. width,
  40244. /**
  40245. * Defines the height of the ground
  40246. */
  40247. height,
  40248. /**
  40249. * Defines the subdivisions to apply to the ground
  40250. */
  40251. subdivisions, canBeRegenerated, mesh) {
  40252. if (mesh === void 0) { mesh = null; }
  40253. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40254. _this.width = width;
  40255. _this.height = height;
  40256. _this.subdivisions = subdivisions;
  40257. return _this;
  40258. }
  40259. GroundGeometry.prototype._regenerateVertexData = function () {
  40260. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40261. };
  40262. GroundGeometry.prototype.copy = function (id) {
  40263. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40264. };
  40265. GroundGeometry.prototype.serialize = function () {
  40266. var serializationObject = _super.prototype.serialize.call(this);
  40267. serializationObject.width = this.width;
  40268. serializationObject.height = this.height;
  40269. serializationObject.subdivisions = this.subdivisions;
  40270. return serializationObject;
  40271. };
  40272. GroundGeometry.Parse = function (parsedGround, scene) {
  40273. if (scene.getGeometryByID(parsedGround.id)) {
  40274. return null; // null since geometry could be something else than a ground...
  40275. }
  40276. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40277. if (BABYLON.Tags) {
  40278. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40279. }
  40280. scene.pushGeometry(ground, true);
  40281. return ground;
  40282. };
  40283. return GroundGeometry;
  40284. }(_PrimitiveGeometry));
  40285. BABYLON.GroundGeometry = GroundGeometry;
  40286. /**
  40287. * Creates a tiled ground geometry
  40288. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40289. */
  40290. var TiledGroundGeometry = /** @class */ (function (_super) {
  40291. __extends(TiledGroundGeometry, _super);
  40292. /**
  40293. * Creates a tiled ground geometry
  40294. * @param id defines the unique ID of the geometry
  40295. * @param scene defines the hosting scene
  40296. * @param xmin defines the minimum value on X axis
  40297. * @param zmin defines the minimum value on Z axis
  40298. * @param xmax defines the maximum value on X axis
  40299. * @param zmax defines the maximum value on Z axis
  40300. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40301. * @param precision defines the precision to use when computing the tiles
  40302. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40303. * @param mesh defines the hosting mesh (can be null)
  40304. */
  40305. function TiledGroundGeometry(id, scene,
  40306. /**
  40307. * Defines the minimum value on X axis
  40308. */
  40309. xmin,
  40310. /**
  40311. * Defines the minimum value on Z axis
  40312. */
  40313. zmin,
  40314. /**
  40315. * Defines the maximum value on X axis
  40316. */
  40317. xmax,
  40318. /**
  40319. * Defines the maximum value on Z axis
  40320. */
  40321. zmax,
  40322. /**
  40323. * Defines the subdivisions to apply to the ground
  40324. */
  40325. subdivisions,
  40326. /**
  40327. * Defines the precision to use when computing the tiles
  40328. */
  40329. precision, canBeRegenerated, mesh) {
  40330. if (mesh === void 0) { mesh = null; }
  40331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40332. _this.xmin = xmin;
  40333. _this.zmin = zmin;
  40334. _this.xmax = xmax;
  40335. _this.zmax = zmax;
  40336. _this.subdivisions = subdivisions;
  40337. _this.precision = precision;
  40338. return _this;
  40339. }
  40340. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40341. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40342. };
  40343. TiledGroundGeometry.prototype.copy = function (id) {
  40344. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40345. };
  40346. return TiledGroundGeometry;
  40347. }(_PrimitiveGeometry));
  40348. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40349. /**
  40350. * Creates a plane geometry
  40351. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40352. */
  40353. var PlaneGeometry = /** @class */ (function (_super) {
  40354. __extends(PlaneGeometry, _super);
  40355. /**
  40356. * Creates a plane geometry
  40357. * @param id defines the unique ID of the geometry
  40358. * @param scene defines the hosting scene
  40359. * @param size defines the size of the plane (width === height)
  40360. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40361. * @param mesh defines the hosting mesh (can be null)
  40362. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40363. */
  40364. function PlaneGeometry(id, scene,
  40365. /**
  40366. * Defines the size of the plane (width === height)
  40367. */
  40368. size, canBeRegenerated, mesh,
  40369. /**
  40370. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40371. */
  40372. side) {
  40373. if (mesh === void 0) { mesh = null; }
  40374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40375. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40376. _this.size = size;
  40377. _this.side = side;
  40378. return _this;
  40379. }
  40380. PlaneGeometry.prototype._regenerateVertexData = function () {
  40381. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40382. };
  40383. PlaneGeometry.prototype.copy = function (id) {
  40384. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40385. };
  40386. PlaneGeometry.prototype.serialize = function () {
  40387. var serializationObject = _super.prototype.serialize.call(this);
  40388. serializationObject.size = this.size;
  40389. return serializationObject;
  40390. };
  40391. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40392. if (scene.getGeometryByID(parsedPlane.id)) {
  40393. return null; // null since geometry could be something else than a ground...
  40394. }
  40395. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40396. if (BABYLON.Tags) {
  40397. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40398. }
  40399. scene.pushGeometry(plane, true);
  40400. return plane;
  40401. };
  40402. return PlaneGeometry;
  40403. }(_PrimitiveGeometry));
  40404. BABYLON.PlaneGeometry = PlaneGeometry;
  40405. /**
  40406. * Creates a torus knot geometry
  40407. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40408. */
  40409. var TorusKnotGeometry = /** @class */ (function (_super) {
  40410. __extends(TorusKnotGeometry, _super);
  40411. /**
  40412. * Creates a torus knot geometry
  40413. * @param id defines the unique ID of the geometry
  40414. * @param scene defines the hosting scene
  40415. * @param radius defines the radius of the torus knot
  40416. * @param tube defines the thickness of the torus knot tube
  40417. * @param radialSegments defines the number of radial segments
  40418. * @param tubularSegments defines the number of tubular segments
  40419. * @param p defines the first number of windings
  40420. * @param q defines the second number of windings
  40421. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40422. * @param mesh defines the hosting mesh (can be null)
  40423. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40424. */
  40425. function TorusKnotGeometry(id, scene,
  40426. /**
  40427. * Defines the radius of the torus knot
  40428. */
  40429. radius,
  40430. /**
  40431. * Defines the thickness of the torus knot tube
  40432. */
  40433. tube,
  40434. /**
  40435. * Defines the number of radial segments
  40436. */
  40437. radialSegments,
  40438. /**
  40439. * Defines the number of tubular segments
  40440. */
  40441. tubularSegments,
  40442. /**
  40443. * Defines the first number of windings
  40444. */
  40445. p,
  40446. /**
  40447. * Defines the second number of windings
  40448. */
  40449. q, canBeRegenerated, mesh,
  40450. /**
  40451. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40452. */
  40453. side) {
  40454. if (mesh === void 0) { mesh = null; }
  40455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40457. _this.radius = radius;
  40458. _this.tube = tube;
  40459. _this.radialSegments = radialSegments;
  40460. _this.tubularSegments = tubularSegments;
  40461. _this.p = p;
  40462. _this.q = q;
  40463. _this.side = side;
  40464. return _this;
  40465. }
  40466. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40467. 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 });
  40468. };
  40469. TorusKnotGeometry.prototype.copy = function (id) {
  40470. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40471. };
  40472. TorusKnotGeometry.prototype.serialize = function () {
  40473. var serializationObject = _super.prototype.serialize.call(this);
  40474. serializationObject.radius = this.radius;
  40475. serializationObject.tube = this.tube;
  40476. serializationObject.radialSegments = this.radialSegments;
  40477. serializationObject.tubularSegments = this.tubularSegments;
  40478. serializationObject.p = this.p;
  40479. serializationObject.q = this.q;
  40480. return serializationObject;
  40481. };
  40482. ;
  40483. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40484. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40485. return null; // null since geometry could be something else than a ground...
  40486. }
  40487. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40488. if (BABYLON.Tags) {
  40489. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40490. }
  40491. scene.pushGeometry(torusKnot, true);
  40492. return torusKnot;
  40493. };
  40494. return TorusKnotGeometry;
  40495. }(_PrimitiveGeometry));
  40496. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40497. //}
  40498. })(BABYLON || (BABYLON = {}));
  40499. //# sourceMappingURL=babylon.geometry.js.map
  40500. var BABYLON;
  40501. (function (BABYLON) {
  40502. /**
  40503. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40504. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40505. */
  40506. var PostProcessManager = /** @class */ (function () {
  40507. /**
  40508. * Creates a new instance PostProcess
  40509. * @param scene The scene that the post process is associated with.
  40510. */
  40511. function PostProcessManager(scene) {
  40512. this._vertexBuffers = {};
  40513. this._scene = scene;
  40514. }
  40515. PostProcessManager.prototype._prepareBuffers = function () {
  40516. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40517. return;
  40518. }
  40519. // VBO
  40520. var vertices = [];
  40521. vertices.push(1, 1);
  40522. vertices.push(-1, 1);
  40523. vertices.push(-1, -1);
  40524. vertices.push(1, -1);
  40525. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40526. this._buildIndexBuffer();
  40527. };
  40528. PostProcessManager.prototype._buildIndexBuffer = function () {
  40529. // Indices
  40530. var indices = [];
  40531. indices.push(0);
  40532. indices.push(1);
  40533. indices.push(2);
  40534. indices.push(0);
  40535. indices.push(2);
  40536. indices.push(3);
  40537. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40538. };
  40539. /**
  40540. * Rebuilds the vertex buffers of the manager.
  40541. */
  40542. PostProcessManager.prototype._rebuild = function () {
  40543. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40544. if (!vb) {
  40545. return;
  40546. }
  40547. vb._rebuild();
  40548. this._buildIndexBuffer();
  40549. };
  40550. // Methods
  40551. /**
  40552. * Prepares a frame to be run through a post process.
  40553. * @param sourceTexture The input texture to the post procesess. (default: null)
  40554. * @param postProcesses An array of post processes to be run. (default: null)
  40555. * @returns True if the post processes were able to be run.
  40556. */
  40557. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40558. if (sourceTexture === void 0) { sourceTexture = null; }
  40559. if (postProcesses === void 0) { postProcesses = null; }
  40560. var camera = this._scene.activeCamera;
  40561. if (!camera) {
  40562. return false;
  40563. }
  40564. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40565. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40566. return false;
  40567. }
  40568. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40569. return true;
  40570. };
  40571. /**
  40572. * Manually render a set of post processes to a texture.
  40573. * @param postProcesses An array of post processes to be run.
  40574. * @param targetTexture The target texture to render to.
  40575. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40576. */
  40577. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40578. if (targetTexture === void 0) { targetTexture = null; }
  40579. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40580. var engine = this._scene.getEngine();
  40581. for (var index = 0; index < postProcesses.length; index++) {
  40582. if (index < postProcesses.length - 1) {
  40583. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40584. }
  40585. else {
  40586. if (targetTexture) {
  40587. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40588. }
  40589. else {
  40590. engine.restoreDefaultFramebuffer();
  40591. }
  40592. }
  40593. var pp = postProcesses[index];
  40594. var effect = pp.apply();
  40595. if (effect) {
  40596. pp.onBeforeRenderObservable.notifyObservers(effect);
  40597. // VBOs
  40598. this._prepareBuffers();
  40599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40600. // Draw order
  40601. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40602. pp.onAfterRenderObservable.notifyObservers(effect);
  40603. }
  40604. }
  40605. // Restore depth buffer
  40606. engine.setDepthBuffer(true);
  40607. engine.setDepthWrite(true);
  40608. };
  40609. /**
  40610. * Finalize the result of the output of the postprocesses.
  40611. * @param doNotPresent If true the result will not be displayed to the screen.
  40612. * @param targetTexture The target texture to render to.
  40613. * @param faceIndex The index of the face to bind the target texture to.
  40614. * @param postProcesses The array of post processes to render.
  40615. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40616. */
  40617. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40618. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40619. var camera = this._scene.activeCamera;
  40620. if (!camera) {
  40621. return;
  40622. }
  40623. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40624. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40625. return;
  40626. }
  40627. var engine = this._scene.getEngine();
  40628. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40629. var pp = postProcesses[index];
  40630. if (index < len - 1) {
  40631. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40632. }
  40633. else {
  40634. if (targetTexture) {
  40635. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40636. pp._outputTexture = targetTexture;
  40637. }
  40638. else {
  40639. engine.restoreDefaultFramebuffer();
  40640. pp._outputTexture = null;
  40641. }
  40642. }
  40643. if (doNotPresent) {
  40644. break;
  40645. }
  40646. var effect = pp.apply();
  40647. if (effect) {
  40648. pp.onBeforeRenderObservable.notifyObservers(effect);
  40649. // VBOs
  40650. this._prepareBuffers();
  40651. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40652. // Draw order
  40653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40654. pp.onAfterRenderObservable.notifyObservers(effect);
  40655. }
  40656. }
  40657. // Restore states
  40658. engine.setDepthBuffer(true);
  40659. engine.setDepthWrite(true);
  40660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40661. };
  40662. /**
  40663. * Disposes of the post process manager.
  40664. */
  40665. PostProcessManager.prototype.dispose = function () {
  40666. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40667. if (buffer) {
  40668. buffer.dispose();
  40669. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40670. }
  40671. if (this._indexBuffer) {
  40672. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40673. this._indexBuffer = null;
  40674. }
  40675. };
  40676. return PostProcessManager;
  40677. }());
  40678. BABYLON.PostProcessManager = PostProcessManager;
  40679. })(BABYLON || (BABYLON = {}));
  40680. //# sourceMappingURL=babylon.postProcessManager.js.map
  40681. var BABYLON;
  40682. (function (BABYLON) {
  40683. /**
  40684. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40685. */
  40686. var PerformanceMonitor = /** @class */ (function () {
  40687. /**
  40688. * constructor
  40689. * @param frameSampleSize The number of samples required to saturate the sliding window
  40690. */
  40691. function PerformanceMonitor(frameSampleSize) {
  40692. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40693. this._enabled = true;
  40694. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40695. }
  40696. /**
  40697. * Samples current frame
  40698. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40699. */
  40700. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40701. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40702. if (!this._enabled)
  40703. return;
  40704. if (this._lastFrameTimeMs != null) {
  40705. var dt = timeMs - this._lastFrameTimeMs;
  40706. this._rollingFrameTime.add(dt);
  40707. }
  40708. this._lastFrameTimeMs = timeMs;
  40709. };
  40710. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40711. /**
  40712. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40713. * @return Average frame time in milliseconds
  40714. */
  40715. get: function () {
  40716. return this._rollingFrameTime.average;
  40717. },
  40718. enumerable: true,
  40719. configurable: true
  40720. });
  40721. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40722. /**
  40723. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40724. * @return Frame time variance in milliseconds squared
  40725. */
  40726. get: function () {
  40727. return this._rollingFrameTime.variance;
  40728. },
  40729. enumerable: true,
  40730. configurable: true
  40731. });
  40732. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40733. /**
  40734. * Returns the frame time of the most recent frame
  40735. * @return Frame time in milliseconds
  40736. */
  40737. get: function () {
  40738. return this._rollingFrameTime.history(0);
  40739. },
  40740. enumerable: true,
  40741. configurable: true
  40742. });
  40743. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40744. /**
  40745. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40746. * @return Framerate in frames per second
  40747. */
  40748. get: function () {
  40749. return 1000.0 / this._rollingFrameTime.average;
  40750. },
  40751. enumerable: true,
  40752. configurable: true
  40753. });
  40754. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40755. /**
  40756. * Returns the average framerate in frames per second using the most recent frame time
  40757. * @return Framerate in frames per second
  40758. */
  40759. get: function () {
  40760. var history = this._rollingFrameTime.history(0);
  40761. if (history === 0) {
  40762. return 0;
  40763. }
  40764. return 1000.0 / history;
  40765. },
  40766. enumerable: true,
  40767. configurable: true
  40768. });
  40769. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40770. /**
  40771. * Returns true if enough samples have been taken to completely fill the sliding window
  40772. * @return true if saturated
  40773. */
  40774. get: function () {
  40775. return this._rollingFrameTime.isSaturated();
  40776. },
  40777. enumerable: true,
  40778. configurable: true
  40779. });
  40780. /**
  40781. * Enables contributions to the sliding window sample set
  40782. */
  40783. PerformanceMonitor.prototype.enable = function () {
  40784. this._enabled = true;
  40785. };
  40786. /**
  40787. * Disables contributions to the sliding window sample set
  40788. * Samples will not be interpolated over the disabled period
  40789. */
  40790. PerformanceMonitor.prototype.disable = function () {
  40791. this._enabled = false;
  40792. //clear last sample to avoid interpolating over the disabled period when next enabled
  40793. this._lastFrameTimeMs = null;
  40794. };
  40795. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40796. /**
  40797. * Returns true if sampling is enabled
  40798. * @return true if enabled
  40799. */
  40800. get: function () {
  40801. return this._enabled;
  40802. },
  40803. enumerable: true,
  40804. configurable: true
  40805. });
  40806. /**
  40807. * Resets performance monitor
  40808. */
  40809. PerformanceMonitor.prototype.reset = function () {
  40810. //clear last sample to avoid interpolating over the disabled period when next enabled
  40811. this._lastFrameTimeMs = null;
  40812. //wipe record
  40813. this._rollingFrameTime.reset();
  40814. };
  40815. return PerformanceMonitor;
  40816. }());
  40817. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40818. /**
  40819. * RollingAverage
  40820. *
  40821. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40822. */
  40823. var RollingAverage = /** @class */ (function () {
  40824. /**
  40825. * constructor
  40826. * @param length The number of samples required to saturate the sliding window
  40827. */
  40828. function RollingAverage(length) {
  40829. this._samples = new Array(length);
  40830. this.reset();
  40831. }
  40832. /**
  40833. * Adds a sample to the sample set
  40834. * @param v The sample value
  40835. */
  40836. RollingAverage.prototype.add = function (v) {
  40837. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40838. var delta;
  40839. //we need to check if we've already wrapped round
  40840. if (this.isSaturated()) {
  40841. //remove bottom of stack from mean
  40842. var bottomValue = this._samples[this._pos];
  40843. delta = bottomValue - this.average;
  40844. this.average -= delta / (this._sampleCount - 1);
  40845. this._m2 -= delta * (bottomValue - this.average);
  40846. }
  40847. else {
  40848. this._sampleCount++;
  40849. }
  40850. //add new value to mean
  40851. delta = v - this.average;
  40852. this.average += delta / (this._sampleCount);
  40853. this._m2 += delta * (v - this.average);
  40854. //set the new variance
  40855. this.variance = this._m2 / (this._sampleCount - 1);
  40856. this._samples[this._pos] = v;
  40857. this._pos++;
  40858. this._pos %= this._samples.length; //positive wrap around
  40859. };
  40860. /**
  40861. * Returns previously added values or null if outside of history or outside the sliding window domain
  40862. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40863. * @return Value previously recorded with add() or null if outside of range
  40864. */
  40865. RollingAverage.prototype.history = function (i) {
  40866. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40867. return 0;
  40868. }
  40869. var i0 = this._wrapPosition(this._pos - 1.0);
  40870. return this._samples[this._wrapPosition(i0 - i)];
  40871. };
  40872. /**
  40873. * Returns true if enough samples have been taken to completely fill the sliding window
  40874. * @return true if sample-set saturated
  40875. */
  40876. RollingAverage.prototype.isSaturated = function () {
  40877. return this._sampleCount >= this._samples.length;
  40878. };
  40879. /**
  40880. * Resets the rolling average (equivalent to 0 samples taken so far)
  40881. */
  40882. RollingAverage.prototype.reset = function () {
  40883. this.average = 0;
  40884. this.variance = 0;
  40885. this._sampleCount = 0;
  40886. this._pos = 0;
  40887. this._m2 = 0;
  40888. };
  40889. /**
  40890. * Wraps a value around the sample range boundaries
  40891. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40892. * @return Wrapped position in sample range
  40893. */
  40894. RollingAverage.prototype._wrapPosition = function (i) {
  40895. var max = this._samples.length;
  40896. return ((i % max) + max) % max;
  40897. };
  40898. return RollingAverage;
  40899. }());
  40900. BABYLON.RollingAverage = RollingAverage;
  40901. })(BABYLON || (BABYLON = {}));
  40902. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40903. var BABYLON;
  40904. (function (BABYLON) {
  40905. /**
  40906. * This groups together the common properties used for image processing either in direct forward pass
  40907. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40908. * or not.
  40909. */
  40910. var ImageProcessingConfiguration = /** @class */ (function () {
  40911. function ImageProcessingConfiguration() {
  40912. /**
  40913. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40914. */
  40915. this.colorCurves = new BABYLON.ColorCurves();
  40916. this._colorCurvesEnabled = false;
  40917. this._colorGradingEnabled = false;
  40918. this._colorGradingWithGreenDepth = true;
  40919. this._colorGradingBGR = true;
  40920. this._exposure = 1.0;
  40921. this._toneMappingEnabled = false;
  40922. this._contrast = 1.0;
  40923. /**
  40924. * Vignette stretch size.
  40925. */
  40926. this.vignetteStretch = 0;
  40927. /**
  40928. * Vignette centre X Offset.
  40929. */
  40930. this.vignetteCentreX = 0;
  40931. /**
  40932. * Vignette centre Y Offset.
  40933. */
  40934. this.vignetteCentreY = 0;
  40935. /**
  40936. * Vignette weight or intensity of the vignette effect.
  40937. */
  40938. this.vignetteWeight = 1.5;
  40939. /**
  40940. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40941. * if vignetteEnabled is set to true.
  40942. */
  40943. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40944. /**
  40945. * Camera field of view used by the Vignette effect.
  40946. */
  40947. this.vignetteCameraFov = 0.5;
  40948. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40949. this._vignetteEnabled = false;
  40950. this._applyByPostProcess = false;
  40951. this._isEnabled = true;
  40952. /**
  40953. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40954. */
  40955. this.onUpdateParameters = new BABYLON.Observable();
  40956. }
  40957. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40958. /**
  40959. * Gets wether the color curves effect is enabled.
  40960. */
  40961. get: function () {
  40962. return this._colorCurvesEnabled;
  40963. },
  40964. /**
  40965. * Sets wether the color curves effect is enabled.
  40966. */
  40967. set: function (value) {
  40968. if (this._colorCurvesEnabled === value) {
  40969. return;
  40970. }
  40971. this._colorCurvesEnabled = value;
  40972. this._updateParameters();
  40973. },
  40974. enumerable: true,
  40975. configurable: true
  40976. });
  40977. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40978. /**
  40979. * Gets wether the color grading effect is enabled.
  40980. */
  40981. get: function () {
  40982. return this._colorGradingEnabled;
  40983. },
  40984. /**
  40985. * Sets wether the color grading effect is enabled.
  40986. */
  40987. set: function (value) {
  40988. if (this._colorGradingEnabled === value) {
  40989. return;
  40990. }
  40991. this._colorGradingEnabled = value;
  40992. this._updateParameters();
  40993. },
  40994. enumerable: true,
  40995. configurable: true
  40996. });
  40997. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40998. /**
  40999. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41000. */
  41001. get: function () {
  41002. return this._colorGradingWithGreenDepth;
  41003. },
  41004. /**
  41005. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41006. */
  41007. set: function (value) {
  41008. if (this._colorGradingWithGreenDepth === value) {
  41009. return;
  41010. }
  41011. this._colorGradingWithGreenDepth = value;
  41012. this._updateParameters();
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41018. /**
  41019. * Gets wether the color grading texture contains BGR values.
  41020. */
  41021. get: function () {
  41022. return this._colorGradingBGR;
  41023. },
  41024. /**
  41025. * Sets wether the color grading texture contains BGR values.
  41026. */
  41027. set: function (value) {
  41028. if (this._colorGradingBGR === value) {
  41029. return;
  41030. }
  41031. this._colorGradingBGR = value;
  41032. this._updateParameters();
  41033. },
  41034. enumerable: true,
  41035. configurable: true
  41036. });
  41037. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41038. /**
  41039. * Gets the Exposure used in the effect.
  41040. */
  41041. get: function () {
  41042. return this._exposure;
  41043. },
  41044. /**
  41045. * Sets the Exposure used in the effect.
  41046. */
  41047. set: function (value) {
  41048. if (this._exposure === value) {
  41049. return;
  41050. }
  41051. this._exposure = value;
  41052. this._updateParameters();
  41053. },
  41054. enumerable: true,
  41055. configurable: true
  41056. });
  41057. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41058. /**
  41059. * Gets wether the tone mapping effect is enabled.
  41060. */
  41061. get: function () {
  41062. return this._toneMappingEnabled;
  41063. },
  41064. /**
  41065. * Sets wether the tone mapping effect is enabled.
  41066. */
  41067. set: function (value) {
  41068. if (this._toneMappingEnabled === value) {
  41069. return;
  41070. }
  41071. this._toneMappingEnabled = value;
  41072. this._updateParameters();
  41073. },
  41074. enumerable: true,
  41075. configurable: true
  41076. });
  41077. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41078. /**
  41079. * Gets the contrast used in the effect.
  41080. */
  41081. get: function () {
  41082. return this._contrast;
  41083. },
  41084. /**
  41085. * Sets the contrast used in the effect.
  41086. */
  41087. set: function (value) {
  41088. if (this._contrast === value) {
  41089. return;
  41090. }
  41091. this._contrast = value;
  41092. this._updateParameters();
  41093. },
  41094. enumerable: true,
  41095. configurable: true
  41096. });
  41097. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41098. /**
  41099. * Gets the vignette blend mode allowing different kind of effect.
  41100. */
  41101. get: function () {
  41102. return this._vignetteBlendMode;
  41103. },
  41104. /**
  41105. * Sets the vignette blend mode allowing different kind of effect.
  41106. */
  41107. set: function (value) {
  41108. if (this._vignetteBlendMode === value) {
  41109. return;
  41110. }
  41111. this._vignetteBlendMode = value;
  41112. this._updateParameters();
  41113. },
  41114. enumerable: true,
  41115. configurable: true
  41116. });
  41117. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41118. /**
  41119. * Gets wether the vignette effect is enabled.
  41120. */
  41121. get: function () {
  41122. return this._vignetteEnabled;
  41123. },
  41124. /**
  41125. * Sets wether the vignette effect is enabled.
  41126. */
  41127. set: function (value) {
  41128. if (this._vignetteEnabled === value) {
  41129. return;
  41130. }
  41131. this._vignetteEnabled = value;
  41132. this._updateParameters();
  41133. },
  41134. enumerable: true,
  41135. configurable: true
  41136. });
  41137. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41138. /**
  41139. * Gets wether the image processing is applied through a post process or not.
  41140. */
  41141. get: function () {
  41142. return this._applyByPostProcess;
  41143. },
  41144. /**
  41145. * Sets wether the image processing is applied through a post process or not.
  41146. */
  41147. set: function (value) {
  41148. if (this._applyByPostProcess === value) {
  41149. return;
  41150. }
  41151. this._applyByPostProcess = value;
  41152. this._updateParameters();
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41158. /**
  41159. * Gets wether the image processing is enabled or not.
  41160. */
  41161. get: function () {
  41162. return this._isEnabled;
  41163. },
  41164. /**
  41165. * Sets wether the image processing is enabled or not.
  41166. */
  41167. set: function (value) {
  41168. if (this._isEnabled === value) {
  41169. return;
  41170. }
  41171. this._isEnabled = value;
  41172. this._updateParameters();
  41173. },
  41174. enumerable: true,
  41175. configurable: true
  41176. });
  41177. /**
  41178. * Method called each time the image processing information changes requires to recompile the effect.
  41179. */
  41180. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41181. this.onUpdateParameters.notifyObservers(this);
  41182. };
  41183. ImageProcessingConfiguration.prototype.getClassName = function () {
  41184. return "ImageProcessingConfiguration";
  41185. };
  41186. /**
  41187. * Prepare the list of uniforms associated with the Image Processing effects.
  41188. * @param uniformsList The list of uniforms used in the effect
  41189. * @param defines the list of defines currently in use
  41190. */
  41191. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41192. if (defines.EXPOSURE) {
  41193. uniforms.push("exposureLinear");
  41194. }
  41195. if (defines.CONTRAST) {
  41196. uniforms.push("contrast");
  41197. }
  41198. if (defines.COLORGRADING) {
  41199. uniforms.push("colorTransformSettings");
  41200. }
  41201. if (defines.VIGNETTE) {
  41202. uniforms.push("vInverseScreenSize");
  41203. uniforms.push("vignetteSettings1");
  41204. uniforms.push("vignetteSettings2");
  41205. }
  41206. if (defines.COLORCURVES) {
  41207. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41208. }
  41209. };
  41210. /**
  41211. * Prepare the list of samplers associated with the Image Processing effects.
  41212. * @param uniformsList The list of uniforms used in the effect
  41213. * @param defines the list of defines currently in use
  41214. */
  41215. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41216. if (defines.COLORGRADING) {
  41217. samplersList.push("txColorTransform");
  41218. }
  41219. };
  41220. /**
  41221. * Prepare the list of defines associated to the shader.
  41222. * @param defines the list of defines to complete
  41223. */
  41224. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41225. if (forPostProcess === void 0) { forPostProcess = false; }
  41226. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41227. defines.VIGNETTE = false;
  41228. defines.TONEMAPPING = false;
  41229. defines.CONTRAST = false;
  41230. defines.EXPOSURE = false;
  41231. defines.COLORCURVES = false;
  41232. defines.COLORGRADING = false;
  41233. defines.COLORGRADING3D = false;
  41234. defines.IMAGEPROCESSING = false;
  41235. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41236. return;
  41237. }
  41238. defines.VIGNETTE = this.vignetteEnabled;
  41239. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41240. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41241. defines.TONEMAPPING = this.toneMappingEnabled;
  41242. defines.CONTRAST = (this.contrast !== 1.0);
  41243. defines.EXPOSURE = (this.exposure !== 1.0);
  41244. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41245. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41246. if (defines.COLORGRADING) {
  41247. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41248. }
  41249. else {
  41250. defines.COLORGRADING3D = false;
  41251. }
  41252. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41253. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41254. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41255. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41256. };
  41257. /**
  41258. * Returns true if all the image processing information are ready.
  41259. */
  41260. ImageProcessingConfiguration.prototype.isReady = function () {
  41261. // Color Grading texure can not be none blocking.
  41262. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41263. };
  41264. /**
  41265. * Binds the image processing to the shader.
  41266. * @param effect The effect to bind to
  41267. */
  41268. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41269. if (aspectRatio === void 0) { aspectRatio = 1; }
  41270. // Color Curves
  41271. if (this._colorCurvesEnabled && this.colorCurves) {
  41272. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41273. }
  41274. // Vignette
  41275. if (this._vignetteEnabled) {
  41276. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41277. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41278. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41279. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41280. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41281. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41282. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41283. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41284. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41285. var vignettePower = -2.0 * this.vignetteWeight;
  41286. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41287. }
  41288. // Exposure
  41289. effect.setFloat("exposureLinear", this.exposure);
  41290. // Contrast
  41291. effect.setFloat("contrast", this.contrast);
  41292. // Color transform settings
  41293. if (this.colorGradingTexture) {
  41294. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41295. var textureSize = this.colorGradingTexture.getSize().height;
  41296. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41297. 0.5 / textureSize, // textureOffset
  41298. textureSize, // textureSize
  41299. this.colorGradingTexture.level // weight
  41300. );
  41301. }
  41302. };
  41303. /**
  41304. * Clones the current image processing instance.
  41305. * @return The cloned image processing
  41306. */
  41307. ImageProcessingConfiguration.prototype.clone = function () {
  41308. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41309. };
  41310. /**
  41311. * Serializes the current image processing instance to a json representation.
  41312. * @return a JSON representation
  41313. */
  41314. ImageProcessingConfiguration.prototype.serialize = function () {
  41315. return BABYLON.SerializationHelper.Serialize(this);
  41316. };
  41317. /**
  41318. * Parses the image processing from a json representation.
  41319. * @param source the JSON source to parse
  41320. * @return The parsed image processing
  41321. */
  41322. ImageProcessingConfiguration.Parse = function (source) {
  41323. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41324. };
  41325. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41326. /**
  41327. * Used to apply the vignette as a mix with the pixel color.
  41328. */
  41329. get: function () {
  41330. return this._VIGNETTEMODE_MULTIPLY;
  41331. },
  41332. enumerable: true,
  41333. configurable: true
  41334. });
  41335. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41336. /**
  41337. * Used to apply the vignette as a replacement of the pixel color.
  41338. */
  41339. get: function () {
  41340. return this._VIGNETTEMODE_OPAQUE;
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. // Static constants associated to the image processing.
  41346. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41347. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41348. __decorate([
  41349. BABYLON.serializeAsColorCurves()
  41350. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41351. __decorate([
  41352. BABYLON.serialize()
  41353. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41354. __decorate([
  41355. BABYLON.serializeAsTexture()
  41356. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41357. __decorate([
  41358. BABYLON.serialize()
  41359. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41360. __decorate([
  41361. BABYLON.serialize()
  41362. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41363. __decorate([
  41364. BABYLON.serialize()
  41365. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41366. __decorate([
  41367. BABYLON.serialize()
  41368. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41369. __decorate([
  41370. BABYLON.serialize()
  41371. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41372. __decorate([
  41373. BABYLON.serialize()
  41374. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41375. __decorate([
  41376. BABYLON.serialize()
  41377. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41378. __decorate([
  41379. BABYLON.serialize()
  41380. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41381. __decorate([
  41382. BABYLON.serialize()
  41383. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41384. __decorate([
  41385. BABYLON.serialize()
  41386. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41387. __decorate([
  41388. BABYLON.serializeAsColor4()
  41389. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41390. __decorate([
  41391. BABYLON.serialize()
  41392. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41393. __decorate([
  41394. BABYLON.serialize()
  41395. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41396. __decorate([
  41397. BABYLON.serialize()
  41398. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41399. __decorate([
  41400. BABYLON.serialize()
  41401. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41402. __decorate([
  41403. BABYLON.serialize()
  41404. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41405. return ImageProcessingConfiguration;
  41406. }());
  41407. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41408. })(BABYLON || (BABYLON = {}));
  41409. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41410. var BABYLON;
  41411. (function (BABYLON) {
  41412. /**
  41413. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41414. * It can help converting any input color in a desired output one. This can then be used to create effects
  41415. * from sepia, black and white to sixties or futuristic rendering...
  41416. *
  41417. * The only supported format is currently 3dl.
  41418. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41419. */
  41420. var ColorGradingTexture = /** @class */ (function (_super) {
  41421. __extends(ColorGradingTexture, _super);
  41422. /**
  41423. * Instantiates a ColorGradingTexture from the following parameters.
  41424. *
  41425. * @param url The location of the color gradind data (currently only supporting 3dl)
  41426. * @param scene The scene the texture will be used in
  41427. */
  41428. function ColorGradingTexture(url, scene) {
  41429. var _this = _super.call(this, scene) || this;
  41430. if (!url) {
  41431. return _this;
  41432. }
  41433. _this._engine = scene.getEngine();
  41434. _this._textureMatrix = BABYLON.Matrix.Identity();
  41435. _this.name = url;
  41436. _this.url = url;
  41437. _this.hasAlpha = false;
  41438. _this.isCube = false;
  41439. _this.is3D = _this._engine.webGLVersion > 1;
  41440. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41441. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41442. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41443. _this.anisotropicFilteringLevel = 1;
  41444. _this._texture = _this._getFromCache(url, true);
  41445. if (!_this._texture) {
  41446. if (!scene.useDelayedTextureLoading) {
  41447. _this.loadTexture();
  41448. }
  41449. else {
  41450. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41451. }
  41452. }
  41453. return _this;
  41454. }
  41455. /**
  41456. * Returns the texture matrix used in most of the material.
  41457. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41458. */
  41459. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41460. return this._textureMatrix;
  41461. };
  41462. /**
  41463. * Occurs when the file being loaded is a .3dl LUT file.
  41464. */
  41465. ColorGradingTexture.prototype.load3dlTexture = function () {
  41466. var engine = this._engine;
  41467. var texture;
  41468. if (engine.webGLVersion === 1) {
  41469. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41470. }
  41471. else {
  41472. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41473. }
  41474. this._texture = texture;
  41475. var callback = function (text) {
  41476. if (typeof text !== "string") {
  41477. return;
  41478. }
  41479. var data = null;
  41480. var tempData = null;
  41481. var line;
  41482. var lines = text.split('\n');
  41483. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41484. var maxColor = 0;
  41485. for (var i = 0; i < lines.length; i++) {
  41486. line = lines[i];
  41487. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41488. continue;
  41489. if (line.indexOf('#') === 0)
  41490. continue;
  41491. var words = line.split(" ");
  41492. if (size === 0) {
  41493. // Number of space + one
  41494. size = words.length;
  41495. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41496. tempData = new Float32Array(size * size * size * 4);
  41497. continue;
  41498. }
  41499. if (size != 0) {
  41500. var r = Math.max(parseInt(words[0]), 0);
  41501. var g = Math.max(parseInt(words[1]), 0);
  41502. var b = Math.max(parseInt(words[2]), 0);
  41503. maxColor = Math.max(r, maxColor);
  41504. maxColor = Math.max(g, maxColor);
  41505. maxColor = Math.max(b, maxColor);
  41506. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41507. if (tempData) {
  41508. tempData[pixelStorageIndex + 0] = r;
  41509. tempData[pixelStorageIndex + 1] = g;
  41510. tempData[pixelStorageIndex + 2] = b;
  41511. }
  41512. pixelIndexSlice++;
  41513. if (pixelIndexSlice % size == 0) {
  41514. pixelIndexH++;
  41515. pixelIndexSlice = 0;
  41516. if (pixelIndexH % size == 0) {
  41517. pixelIndexW++;
  41518. pixelIndexH = 0;
  41519. }
  41520. }
  41521. }
  41522. }
  41523. if (tempData && data) {
  41524. for (var i = 0; i < tempData.length; i++) {
  41525. if (i > 0 && (i + 1) % 4 === 0) {
  41526. data[i] = 255;
  41527. }
  41528. else {
  41529. var value = tempData[i];
  41530. data[i] = (value / maxColor * 255);
  41531. }
  41532. }
  41533. }
  41534. if (texture.is3D) {
  41535. texture.updateSize(size, size, size);
  41536. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41537. }
  41538. else {
  41539. texture.updateSize(size * size, size);
  41540. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41541. }
  41542. };
  41543. var scene = this.getScene();
  41544. if (scene) {
  41545. scene._loadFile(this.url, callback);
  41546. }
  41547. else {
  41548. this._engine._loadFile(this.url, callback);
  41549. }
  41550. return this._texture;
  41551. };
  41552. /**
  41553. * Starts the loading process of the texture.
  41554. */
  41555. ColorGradingTexture.prototype.loadTexture = function () {
  41556. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41557. this.load3dlTexture();
  41558. }
  41559. };
  41560. /**
  41561. * Clones the color gradind texture.
  41562. */
  41563. ColorGradingTexture.prototype.clone = function () {
  41564. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41565. // Base texture
  41566. newTexture.level = this.level;
  41567. return newTexture;
  41568. };
  41569. /**
  41570. * Called during delayed load for textures.
  41571. */
  41572. ColorGradingTexture.prototype.delayLoad = function () {
  41573. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41574. return;
  41575. }
  41576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41577. this._texture = this._getFromCache(this.url, true);
  41578. if (!this._texture) {
  41579. this.loadTexture();
  41580. }
  41581. };
  41582. /**
  41583. * Parses a color grading texture serialized by Babylon.
  41584. * @param parsedTexture The texture information being parsedTexture
  41585. * @param scene The scene to load the texture in
  41586. * @param rootUrl The root url of the data assets to load
  41587. * @return A color gradind texture
  41588. */
  41589. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41590. var texture = null;
  41591. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41592. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41593. texture.name = parsedTexture.name;
  41594. texture.level = parsedTexture.level;
  41595. }
  41596. return texture;
  41597. };
  41598. /**
  41599. * Serializes the LUT texture to json format.
  41600. */
  41601. ColorGradingTexture.prototype.serialize = function () {
  41602. if (!this.name) {
  41603. return null;
  41604. }
  41605. var serializationObject = {};
  41606. serializationObject.name = this.name;
  41607. serializationObject.level = this.level;
  41608. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41609. return serializationObject;
  41610. };
  41611. /**
  41612. * Empty line regex stored for GC.
  41613. */
  41614. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41615. return ColorGradingTexture;
  41616. }(BABYLON.BaseTexture));
  41617. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41618. })(BABYLON || (BABYLON = {}));
  41619. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41620. var BABYLON;
  41621. (function (BABYLON) {
  41622. /**
  41623. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41624. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41625. * 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;
  41626. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41627. */
  41628. var ColorCurves = /** @class */ (function () {
  41629. function ColorCurves() {
  41630. this._dirty = true;
  41631. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41632. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41633. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41634. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41635. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41636. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41637. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41638. this._globalHue = 30;
  41639. this._globalDensity = 0;
  41640. this._globalSaturation = 0;
  41641. this._globalExposure = 0;
  41642. this._highlightsHue = 30;
  41643. this._highlightsDensity = 0;
  41644. this._highlightsSaturation = 0;
  41645. this._highlightsExposure = 0;
  41646. this._midtonesHue = 30;
  41647. this._midtonesDensity = 0;
  41648. this._midtonesSaturation = 0;
  41649. this._midtonesExposure = 0;
  41650. this._shadowsHue = 30;
  41651. this._shadowsDensity = 0;
  41652. this._shadowsSaturation = 0;
  41653. this._shadowsExposure = 0;
  41654. }
  41655. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41656. /**
  41657. * Gets the global Hue value.
  41658. * 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).
  41659. */
  41660. get: function () {
  41661. return this._globalHue;
  41662. },
  41663. /**
  41664. * Sets the global Hue value.
  41665. * 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).
  41666. */
  41667. set: function (value) {
  41668. this._globalHue = value;
  41669. this._dirty = true;
  41670. },
  41671. enumerable: true,
  41672. configurable: true
  41673. });
  41674. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41675. /**
  41676. * Gets the global Density value.
  41677. * 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.
  41678. * Values less than zero provide a filter of opposite hue.
  41679. */
  41680. get: function () {
  41681. return this._globalDensity;
  41682. },
  41683. /**
  41684. * Sets the global Density value.
  41685. * 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.
  41686. * Values less than zero provide a filter of opposite hue.
  41687. */
  41688. set: function (value) {
  41689. this._globalDensity = value;
  41690. this._dirty = true;
  41691. },
  41692. enumerable: true,
  41693. configurable: true
  41694. });
  41695. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41696. /**
  41697. * Gets the global Saturation value.
  41698. * 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.
  41699. */
  41700. get: function () {
  41701. return this._globalSaturation;
  41702. },
  41703. /**
  41704. * Sets the global Saturation value.
  41705. * 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.
  41706. */
  41707. set: function (value) {
  41708. this._globalSaturation = value;
  41709. this._dirty = true;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41715. /**
  41716. * Gets the highlights Hue value.
  41717. * 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).
  41718. */
  41719. get: function () {
  41720. return this._highlightsHue;
  41721. },
  41722. /**
  41723. * Sets the highlights Hue value.
  41724. * 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).
  41725. */
  41726. set: function (value) {
  41727. this._highlightsHue = value;
  41728. this._dirty = true;
  41729. },
  41730. enumerable: true,
  41731. configurable: true
  41732. });
  41733. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41734. /**
  41735. * Gets the highlights Density value.
  41736. * 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.
  41737. * Values less than zero provide a filter of opposite hue.
  41738. */
  41739. get: function () {
  41740. return this._highlightsDensity;
  41741. },
  41742. /**
  41743. * Sets the highlights Density value.
  41744. * 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.
  41745. * Values less than zero provide a filter of opposite hue.
  41746. */
  41747. set: function (value) {
  41748. this._highlightsDensity = value;
  41749. this._dirty = true;
  41750. },
  41751. enumerable: true,
  41752. configurable: true
  41753. });
  41754. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41755. /**
  41756. * Gets the highlights Saturation value.
  41757. * 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.
  41758. */
  41759. get: function () {
  41760. return this._highlightsSaturation;
  41761. },
  41762. /**
  41763. * Sets the highlights Saturation value.
  41764. * 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.
  41765. */
  41766. set: function (value) {
  41767. this._highlightsSaturation = value;
  41768. this._dirty = true;
  41769. },
  41770. enumerable: true,
  41771. configurable: true
  41772. });
  41773. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41774. /**
  41775. * Gets the highlights Exposure value.
  41776. * 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.
  41777. */
  41778. get: function () {
  41779. return this._highlightsExposure;
  41780. },
  41781. /**
  41782. * Sets the highlights Exposure value.
  41783. * 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.
  41784. */
  41785. set: function (value) {
  41786. this._highlightsExposure = value;
  41787. this._dirty = true;
  41788. },
  41789. enumerable: true,
  41790. configurable: true
  41791. });
  41792. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41793. /**
  41794. * Gets the midtones Hue value.
  41795. * 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).
  41796. */
  41797. get: function () {
  41798. return this._midtonesHue;
  41799. },
  41800. /**
  41801. * Sets the midtones Hue value.
  41802. * 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).
  41803. */
  41804. set: function (value) {
  41805. this._midtonesHue = value;
  41806. this._dirty = true;
  41807. },
  41808. enumerable: true,
  41809. configurable: true
  41810. });
  41811. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41812. /**
  41813. * Gets the midtones Density value.
  41814. * 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.
  41815. * Values less than zero provide a filter of opposite hue.
  41816. */
  41817. get: function () {
  41818. return this._midtonesDensity;
  41819. },
  41820. /**
  41821. * Sets the midtones Density value.
  41822. * 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.
  41823. * Values less than zero provide a filter of opposite hue.
  41824. */
  41825. set: function (value) {
  41826. this._midtonesDensity = value;
  41827. this._dirty = true;
  41828. },
  41829. enumerable: true,
  41830. configurable: true
  41831. });
  41832. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41833. /**
  41834. * Gets the midtones Saturation value.
  41835. * 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.
  41836. */
  41837. get: function () {
  41838. return this._midtonesSaturation;
  41839. },
  41840. /**
  41841. * Sets the midtones Saturation value.
  41842. * 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.
  41843. */
  41844. set: function (value) {
  41845. this._midtonesSaturation = value;
  41846. this._dirty = true;
  41847. },
  41848. enumerable: true,
  41849. configurable: true
  41850. });
  41851. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41852. /**
  41853. * Gets the midtones Exposure value.
  41854. * 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.
  41855. */
  41856. get: function () {
  41857. return this._midtonesExposure;
  41858. },
  41859. /**
  41860. * Sets the midtones Exposure value.
  41861. * 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.
  41862. */
  41863. set: function (value) {
  41864. this._midtonesExposure = value;
  41865. this._dirty = true;
  41866. },
  41867. enumerable: true,
  41868. configurable: true
  41869. });
  41870. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41871. /**
  41872. * Gets the shadows Hue value.
  41873. * 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).
  41874. */
  41875. get: function () {
  41876. return this._shadowsHue;
  41877. },
  41878. /**
  41879. * Sets the shadows Hue value.
  41880. * 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).
  41881. */
  41882. set: function (value) {
  41883. this._shadowsHue = value;
  41884. this._dirty = true;
  41885. },
  41886. enumerable: true,
  41887. configurable: true
  41888. });
  41889. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41890. /**
  41891. * Gets the shadows Density value.
  41892. * 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.
  41893. * Values less than zero provide a filter of opposite hue.
  41894. */
  41895. get: function () {
  41896. return this._shadowsDensity;
  41897. },
  41898. /**
  41899. * Sets the shadows Density value.
  41900. * 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.
  41901. * Values less than zero provide a filter of opposite hue.
  41902. */
  41903. set: function (value) {
  41904. this._shadowsDensity = value;
  41905. this._dirty = true;
  41906. },
  41907. enumerable: true,
  41908. configurable: true
  41909. });
  41910. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41911. /**
  41912. * Gets the shadows Saturation value.
  41913. * 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.
  41914. */
  41915. get: function () {
  41916. return this._shadowsSaturation;
  41917. },
  41918. /**
  41919. * Sets the shadows Saturation value.
  41920. * 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.
  41921. */
  41922. set: function (value) {
  41923. this._shadowsSaturation = value;
  41924. this._dirty = true;
  41925. },
  41926. enumerable: true,
  41927. configurable: true
  41928. });
  41929. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41930. /**
  41931. * Gets the shadows Exposure value.
  41932. * 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.
  41933. */
  41934. get: function () {
  41935. return this._shadowsExposure;
  41936. },
  41937. /**
  41938. * Sets the shadows Exposure value.
  41939. * 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.
  41940. */
  41941. set: function (value) {
  41942. this._shadowsExposure = value;
  41943. this._dirty = true;
  41944. },
  41945. enumerable: true,
  41946. configurable: true
  41947. });
  41948. ColorCurves.prototype.getClassName = function () {
  41949. return "ColorCurves";
  41950. };
  41951. /**
  41952. * Binds the color curves to the shader.
  41953. * @param colorCurves The color curve to bind
  41954. * @param effect The effect to bind to
  41955. */
  41956. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41957. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41958. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41959. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41960. if (colorCurves._dirty) {
  41961. colorCurves._dirty = false;
  41962. // Fill in global info.
  41963. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41964. // Compute highlights info.
  41965. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41966. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41967. // Compute midtones info.
  41968. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41969. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41970. // Compute shadows info.
  41971. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41972. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41973. // Compute deltas (neutral is midtones).
  41974. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41975. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41976. }
  41977. if (effect) {
  41978. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41979. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41980. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41981. }
  41982. };
  41983. /**
  41984. * Prepare the list of uniforms associated with the ColorCurves effects.
  41985. * @param uniformsList The list of uniforms used in the effect
  41986. */
  41987. ColorCurves.PrepareUniforms = function (uniformsList) {
  41988. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41989. };
  41990. /**
  41991. * Returns color grading data based on a hue, density, saturation and exposure value.
  41992. * @param filterHue The hue of the color filter.
  41993. * @param filterDensity The density of the color filter.
  41994. * @param saturation The saturation.
  41995. * @param exposure The exposure.
  41996. * @param result The result data container.
  41997. */
  41998. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41999. if (hue == null) {
  42000. return;
  42001. }
  42002. hue = ColorCurves.clamp(hue, 0, 360);
  42003. density = ColorCurves.clamp(density, -100, 100);
  42004. saturation = ColorCurves.clamp(saturation, -100, 100);
  42005. exposure = ColorCurves.clamp(exposure, -100, 100);
  42006. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42007. // so that the maximum filter density is only 50% control. This provides fine control
  42008. // for small values and reasonable range.
  42009. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42010. density *= 0.5;
  42011. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42012. if (density < 0) {
  42013. density *= -1;
  42014. hue = (hue + 180) % 360;
  42015. }
  42016. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42017. result.scaleToRef(2, result);
  42018. result.a = 1 + 0.01 * saturation;
  42019. };
  42020. /**
  42021. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42022. * @param value The input slider value in range [-100,100].
  42023. * @returns Adjusted value.
  42024. */
  42025. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42026. value /= 100;
  42027. var x = Math.abs(value);
  42028. x = Math.pow(x, 2);
  42029. if (value < 0) {
  42030. x *= -1;
  42031. }
  42032. x *= 100;
  42033. return x;
  42034. };
  42035. /**
  42036. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42037. * @param hue The hue (H) input.
  42038. * @param saturation The saturation (S) input.
  42039. * @param brightness The brightness (B) input.
  42040. * @result An RGBA color represented as Vector4.
  42041. */
  42042. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42043. var h = ColorCurves.clamp(hue, 0, 360);
  42044. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42045. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42046. if (s === 0) {
  42047. result.r = v;
  42048. result.g = v;
  42049. result.b = v;
  42050. }
  42051. else {
  42052. // sector 0 to 5
  42053. h /= 60;
  42054. var i = Math.floor(h);
  42055. // fractional part of h
  42056. var f = h - i;
  42057. var p = v * (1 - s);
  42058. var q = v * (1 - s * f);
  42059. var t = v * (1 - s * (1 - f));
  42060. switch (i) {
  42061. case 0:
  42062. result.r = v;
  42063. result.g = t;
  42064. result.b = p;
  42065. break;
  42066. case 1:
  42067. result.r = q;
  42068. result.g = v;
  42069. result.b = p;
  42070. break;
  42071. case 2:
  42072. result.r = p;
  42073. result.g = v;
  42074. result.b = t;
  42075. break;
  42076. case 3:
  42077. result.r = p;
  42078. result.g = q;
  42079. result.b = v;
  42080. break;
  42081. case 4:
  42082. result.r = t;
  42083. result.g = p;
  42084. result.b = v;
  42085. break;
  42086. default: // case 5:
  42087. result.r = v;
  42088. result.g = p;
  42089. result.b = q;
  42090. break;
  42091. }
  42092. }
  42093. result.a = 1;
  42094. };
  42095. /**
  42096. * Returns a value clamped between min and max
  42097. * @param value The value to clamp
  42098. * @param min The minimum of value
  42099. * @param max The maximum of value
  42100. * @returns The clamped value.
  42101. */
  42102. ColorCurves.clamp = function (value, min, max) {
  42103. return Math.min(Math.max(value, min), max);
  42104. };
  42105. /**
  42106. * Clones the current color curve instance.
  42107. * @return The cloned curves
  42108. */
  42109. ColorCurves.prototype.clone = function () {
  42110. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42111. };
  42112. /**
  42113. * Serializes the current color curve instance to a json representation.
  42114. * @return a JSON representation
  42115. */
  42116. ColorCurves.prototype.serialize = function () {
  42117. return BABYLON.SerializationHelper.Serialize(this);
  42118. };
  42119. /**
  42120. * Parses the color curve from a json representation.
  42121. * @param source the JSON source to parse
  42122. * @return The parsed curves
  42123. */
  42124. ColorCurves.Parse = function (source) {
  42125. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42126. };
  42127. __decorate([
  42128. BABYLON.serialize()
  42129. ], ColorCurves.prototype, "_globalHue", void 0);
  42130. __decorate([
  42131. BABYLON.serialize()
  42132. ], ColorCurves.prototype, "_globalDensity", void 0);
  42133. __decorate([
  42134. BABYLON.serialize()
  42135. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42136. __decorate([
  42137. BABYLON.serialize()
  42138. ], ColorCurves.prototype, "_globalExposure", void 0);
  42139. __decorate([
  42140. BABYLON.serialize()
  42141. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42142. __decorate([
  42143. BABYLON.serialize()
  42144. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42145. __decorate([
  42146. BABYLON.serialize()
  42147. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42148. __decorate([
  42149. BABYLON.serialize()
  42150. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42151. __decorate([
  42152. BABYLON.serialize()
  42153. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42154. __decorate([
  42155. BABYLON.serialize()
  42156. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42157. __decorate([
  42158. BABYLON.serialize()
  42159. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42160. __decorate([
  42161. BABYLON.serialize()
  42162. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42163. return ColorCurves;
  42164. }());
  42165. BABYLON.ColorCurves = ColorCurves;
  42166. })(BABYLON || (BABYLON = {}));
  42167. //# sourceMappingURL=babylon.colorCurves.js.map
  42168. //# sourceMappingURL=babylon.behavior.js.map
  42169. var BABYLON;
  42170. (function (BABYLON) {
  42171. /**
  42172. * "Static Class" containing the most commonly used helper while dealing with material for
  42173. * rendering purpose.
  42174. *
  42175. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42176. *
  42177. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42178. */
  42179. var MaterialHelper = /** @class */ (function () {
  42180. function MaterialHelper() {
  42181. }
  42182. /**
  42183. * Bind the current view position to an effect.
  42184. * @param effect The effect to be bound
  42185. * @param scene The scene the eyes position is used from
  42186. */
  42187. MaterialHelper.BindEyePosition = function (effect, scene) {
  42188. if (scene._forcedViewPosition) {
  42189. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42190. return;
  42191. }
  42192. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42193. };
  42194. /**
  42195. * Helps preparing the defines values about the UVs in used in the effect.
  42196. * UVs are shared as much as we can accross chanels in the shaders.
  42197. * @param texture The texture we are preparing the UVs for
  42198. * @param defines The defines to update
  42199. * @param key The chanel key "diffuse", "specular"... used in the shader
  42200. */
  42201. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42202. defines._needUVs = true;
  42203. defines[key] = true;
  42204. if (texture.getTextureMatrix().isIdentity(true)) {
  42205. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42206. if (texture.coordinatesIndex === 0) {
  42207. defines["MAINUV1"] = true;
  42208. }
  42209. else {
  42210. defines["MAINUV2"] = true;
  42211. }
  42212. }
  42213. else {
  42214. defines[key + "DIRECTUV"] = 0;
  42215. }
  42216. };
  42217. /**
  42218. * Binds a texture matrix value to its corrsponding uniform
  42219. * @param texture The texture to bind the matrix for
  42220. * @param uniformBuffer The uniform buffer receivin the data
  42221. * @param key The chanel key "diffuse", "specular"... used in the shader
  42222. */
  42223. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42224. var matrix = texture.getTextureMatrix();
  42225. if (!matrix.isIdentity(true)) {
  42226. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42227. }
  42228. };
  42229. /**
  42230. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42231. * @param mesh defines the current mesh
  42232. * @param scene defines the current scene
  42233. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42234. * @param pointsCloud defines if point cloud rendering has to be turned on
  42235. * @param fogEnabled defines if fog has to be turned on
  42236. * @param alphaTest defines if alpha testing has to be turned on
  42237. * @param defines defines the current list of defines
  42238. */
  42239. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42240. if (defines._areMiscDirty) {
  42241. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42242. defines["POINTSIZE"] = pointsCloud;
  42243. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42244. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42245. defines["ALPHATEST"] = alphaTest;
  42246. }
  42247. };
  42248. /**
  42249. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42250. * @param scene defines the current scene
  42251. * @param engine defines the current engine
  42252. * @param defines specifies the list of active defines
  42253. * @param useInstances defines if instances have to be turned on
  42254. * @param useClipPlane defines if clip plane have to be turned on
  42255. */
  42256. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42257. if (useClipPlane === void 0) { useClipPlane = null; }
  42258. var changed = false;
  42259. if (useClipPlane == null) {
  42260. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42261. }
  42262. if (defines["CLIPPLANE"] !== useClipPlane) {
  42263. defines["CLIPPLANE"] = useClipPlane;
  42264. changed = true;
  42265. }
  42266. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42267. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42268. changed = true;
  42269. }
  42270. if (defines["INSTANCES"] !== useInstances) {
  42271. defines["INSTANCES"] = useInstances;
  42272. changed = true;
  42273. }
  42274. if (changed) {
  42275. defines.markAsUnprocessed();
  42276. }
  42277. };
  42278. /**
  42279. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42280. * @param mesh The mesh containing the geometry data we will draw
  42281. * @param defines The defines to update
  42282. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42283. * @param useBones Precise whether bones should be used or not (override mesh info)
  42284. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42285. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42286. * @returns false if defines are considered not dirty and have not been checked
  42287. */
  42288. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42289. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42290. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42291. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42292. return false;
  42293. }
  42294. defines._normals = defines._needNormals;
  42295. defines._uvs = defines._needUVs;
  42296. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42297. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42298. defines["TANGENT"] = true;
  42299. }
  42300. if (defines._needUVs) {
  42301. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42302. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42303. }
  42304. else {
  42305. defines["UV1"] = false;
  42306. defines["UV2"] = false;
  42307. }
  42308. if (useVertexColor) {
  42309. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42310. defines["VERTEXCOLOR"] = hasVertexColors;
  42311. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42312. }
  42313. if (useBones) {
  42314. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42315. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42316. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42317. }
  42318. else {
  42319. defines["NUM_BONE_INFLUENCERS"] = 0;
  42320. defines["BonesPerMesh"] = 0;
  42321. }
  42322. }
  42323. if (useMorphTargets) {
  42324. var manager = mesh.morphTargetManager;
  42325. if (manager) {
  42326. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42327. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42328. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42329. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42330. }
  42331. else {
  42332. defines["MORPHTARGETS_TANGENT"] = false;
  42333. defines["MORPHTARGETS_NORMAL"] = false;
  42334. defines["MORPHTARGETS"] = false;
  42335. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42336. }
  42337. }
  42338. return true;
  42339. };
  42340. /**
  42341. * Prepares the defines related to the light information passed in parameter
  42342. * @param scene The scene we are intending to draw
  42343. * @param mesh The mesh the effect is compiling for
  42344. * @param defines The defines to update
  42345. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42346. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42347. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42348. * @returns true if normals will be required for the rest of the effect
  42349. */
  42350. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42351. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42352. if (disableLighting === void 0) { disableLighting = false; }
  42353. if (!defines._areLightsDirty) {
  42354. return defines._needNormals;
  42355. }
  42356. var lightIndex = 0;
  42357. var needNormals = false;
  42358. var needRebuild = false;
  42359. var lightmapMode = false;
  42360. var shadowEnabled = false;
  42361. var specularEnabled = false;
  42362. if (scene.lightsEnabled && !disableLighting) {
  42363. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42364. var light = _a[_i];
  42365. needNormals = true;
  42366. if (defines["LIGHT" + lightIndex] === undefined) {
  42367. needRebuild = true;
  42368. }
  42369. defines["LIGHT" + lightIndex] = true;
  42370. defines["SPOTLIGHT" + lightIndex] = false;
  42371. defines["HEMILIGHT" + lightIndex] = false;
  42372. defines["POINTLIGHT" + lightIndex] = false;
  42373. defines["DIRLIGHT" + lightIndex] = false;
  42374. var type;
  42375. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42376. type = "SPOTLIGHT" + lightIndex;
  42377. var spotLight = light;
  42378. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42379. }
  42380. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42381. type = "HEMILIGHT" + lightIndex;
  42382. }
  42383. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42384. type = "POINTLIGHT" + lightIndex;
  42385. }
  42386. else {
  42387. type = "DIRLIGHT" + lightIndex;
  42388. }
  42389. defines[type] = true;
  42390. // Specular
  42391. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42392. specularEnabled = true;
  42393. }
  42394. // Shadows
  42395. defines["SHADOW" + lightIndex] = false;
  42396. defines["SHADOWPCF" + lightIndex] = false;
  42397. defines["SHADOWPCSS" + lightIndex] = false;
  42398. defines["SHADOWPOISSON" + lightIndex] = false;
  42399. defines["SHADOWESM" + lightIndex] = false;
  42400. defines["SHADOWCUBE" + lightIndex] = false;
  42401. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42402. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42403. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42404. var shadowGenerator = light.getShadowGenerator();
  42405. if (shadowGenerator) {
  42406. shadowEnabled = true;
  42407. shadowGenerator.prepareDefines(defines, lightIndex);
  42408. }
  42409. }
  42410. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42411. lightmapMode = true;
  42412. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42413. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42414. }
  42415. else {
  42416. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42417. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42418. }
  42419. lightIndex++;
  42420. if (lightIndex === maxSimultaneousLights)
  42421. break;
  42422. }
  42423. }
  42424. defines["SPECULARTERM"] = specularEnabled;
  42425. defines["SHADOWS"] = shadowEnabled;
  42426. // Resetting all other lights if any
  42427. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42428. if (defines["LIGHT" + index] !== undefined) {
  42429. defines["LIGHT" + index] = false;
  42430. defines["HEMILIGHT" + lightIndex] = false;
  42431. defines["POINTLIGHT" + lightIndex] = false;
  42432. defines["DIRLIGHT" + lightIndex] = false;
  42433. defines["SPOTLIGHT" + lightIndex] = false;
  42434. defines["SHADOW" + lightIndex] = false;
  42435. }
  42436. }
  42437. var caps = scene.getEngine().getCaps();
  42438. if (defines["SHADOWFLOAT"] === undefined) {
  42439. needRebuild = true;
  42440. }
  42441. defines["SHADOWFLOAT"] = shadowEnabled &&
  42442. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42443. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42444. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42445. if (needRebuild) {
  42446. defines.rebuild();
  42447. }
  42448. return needNormals;
  42449. };
  42450. /**
  42451. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42452. * that won t be acctive due to defines being turned off.
  42453. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42454. * @param samplersList The samplers list
  42455. * @param defines The defines helping in the list generation
  42456. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42457. */
  42458. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42459. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42460. var uniformsList;
  42461. var uniformBuffersList = null;
  42462. if (uniformsListOrOptions.uniformsNames) {
  42463. var options = uniformsListOrOptions;
  42464. uniformsList = options.uniformsNames;
  42465. uniformBuffersList = options.uniformBuffersNames;
  42466. samplersList = options.samplers;
  42467. defines = options.defines;
  42468. maxSimultaneousLights = options.maxSimultaneousLights;
  42469. }
  42470. else {
  42471. uniformsList = uniformsListOrOptions;
  42472. if (!samplersList) {
  42473. samplersList = [];
  42474. }
  42475. }
  42476. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42477. if (!defines["LIGHT" + lightIndex]) {
  42478. break;
  42479. }
  42480. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42481. if (uniformBuffersList) {
  42482. uniformBuffersList.push("Light" + lightIndex);
  42483. }
  42484. samplersList.push("shadowSampler" + lightIndex);
  42485. samplersList.push("depthSampler" + lightIndex);
  42486. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42487. samplersList.push("projectionLightSampler" + lightIndex);
  42488. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42489. }
  42490. }
  42491. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42492. uniformsList.push("morphTargetInfluences");
  42493. }
  42494. };
  42495. /**
  42496. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42497. * @param defines The defines to update while falling back
  42498. * @param fallbacks The authorized effect fallbacks
  42499. * @param maxSimultaneousLights The maximum number of lights allowed
  42500. * @param rank the current rank of the Effect
  42501. * @returns The newly affected rank
  42502. */
  42503. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42504. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42505. if (rank === void 0) { rank = 0; }
  42506. var lightFallbackRank = 0;
  42507. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42508. if (!defines["LIGHT" + lightIndex]) {
  42509. break;
  42510. }
  42511. if (lightIndex > 0) {
  42512. lightFallbackRank = rank + lightIndex;
  42513. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42514. }
  42515. if (!defines["SHADOWS"]) {
  42516. if (defines["SHADOW" + lightIndex]) {
  42517. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42518. }
  42519. if (defines["SHADOWPCF" + lightIndex]) {
  42520. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42521. }
  42522. if (defines["SHADOWPCSS" + lightIndex]) {
  42523. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42524. }
  42525. if (defines["SHADOWPOISSON" + lightIndex]) {
  42526. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42527. }
  42528. if (defines["SHADOWESM" + lightIndex]) {
  42529. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42530. }
  42531. }
  42532. }
  42533. return lightFallbackRank++;
  42534. };
  42535. /**
  42536. * Prepares the list of attributes required for morph targets according to the effect defines.
  42537. * @param attribs The current list of supported attribs
  42538. * @param mesh The mesh to prepare the morph targets attributes for
  42539. * @param defines The current Defines of the effect
  42540. */
  42541. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42542. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42543. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42544. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42545. var manager = mesh.morphTargetManager;
  42546. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42547. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42548. for (var index = 0; index < influencers; index++) {
  42549. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42550. if (normal) {
  42551. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42552. }
  42553. if (tangent) {
  42554. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42555. }
  42556. if (attribs.length > maxAttributesCount) {
  42557. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42558. }
  42559. }
  42560. }
  42561. };
  42562. /**
  42563. * Prepares the list of attributes required for bones according to the effect defines.
  42564. * @param attribs The current list of supported attribs
  42565. * @param mesh The mesh to prepare the bones attributes for
  42566. * @param defines The current Defines of the effect
  42567. * @param fallbacks The current efffect fallback strategy
  42568. */
  42569. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42570. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42571. fallbacks.addCPUSkinningFallback(0, mesh);
  42572. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42573. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42574. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42577. }
  42578. }
  42579. };
  42580. /**
  42581. * Prepares the list of attributes required for instances according to the effect defines.
  42582. * @param attribs The current list of supported attribs
  42583. * @param defines The current Defines of the effect
  42584. */
  42585. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42586. if (defines["INSTANCES"]) {
  42587. attribs.push("world0");
  42588. attribs.push("world1");
  42589. attribs.push("world2");
  42590. attribs.push("world3");
  42591. }
  42592. };
  42593. /**
  42594. * Binds the light shadow information to the effect for the given mesh.
  42595. * @param light The light containing the generator
  42596. * @param scene The scene the lights belongs to
  42597. * @param mesh The mesh we are binding the information to render
  42598. * @param lightIndex The light index in the effect used to render the mesh
  42599. * @param effect The effect we are binding the data to
  42600. */
  42601. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42602. if (light.shadowEnabled && mesh.receiveShadows) {
  42603. var shadowGenerator = light.getShadowGenerator();
  42604. if (shadowGenerator) {
  42605. shadowGenerator.bindShadowLight(lightIndex, effect);
  42606. }
  42607. }
  42608. };
  42609. /**
  42610. * Binds the light information to the effect.
  42611. * @param light The light containing the generator
  42612. * @param effect The effect we are binding the data to
  42613. * @param lightIndex The light index in the effect used to render
  42614. */
  42615. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42616. light.transferToEffect(effect, lightIndex + "");
  42617. };
  42618. /**
  42619. * Binds the lights information from the scene to the effect for the given mesh.
  42620. * @param scene The scene the lights belongs to
  42621. * @param mesh The mesh we are binding the information to render
  42622. * @param effect The effect we are binding the data to
  42623. * @param defines The generated defines for the effect
  42624. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42625. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42626. */
  42627. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42628. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42629. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42630. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42631. for (var i = 0; i < len; i++) {
  42632. var light = mesh._lightSources[i];
  42633. var iAsString = i.toString();
  42634. var scaledIntensity = light.getScaledIntensity();
  42635. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42636. MaterialHelper.BindLightProperties(light, effect, i);
  42637. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42638. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42639. if (defines["SPECULARTERM"]) {
  42640. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42641. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42642. }
  42643. // Shadows
  42644. if (scene.shadowsEnabled) {
  42645. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42646. }
  42647. light._uniformBuffer.update();
  42648. }
  42649. };
  42650. /**
  42651. * Binds the fog information from the scene to the effect for the given mesh.
  42652. * @param scene The scene the lights belongs to
  42653. * @param mesh The mesh we are binding the information to render
  42654. * @param effect The effect we are binding the data to
  42655. */
  42656. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42657. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42658. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42659. effect.setColor3("vFogColor", scene.fogColor);
  42660. }
  42661. };
  42662. /**
  42663. * Binds the bones information from the mesh to the effect.
  42664. * @param mesh The mesh we are binding the information to render
  42665. * @param effect The effect we are binding the data to
  42666. */
  42667. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42668. if (!effect || !mesh) {
  42669. return;
  42670. }
  42671. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42672. mesh.computeBonesUsingShaders = false;
  42673. }
  42674. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42675. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42676. if (matrices) {
  42677. effect.setMatrices("mBones", matrices);
  42678. }
  42679. }
  42680. };
  42681. /**
  42682. * Binds the morph targets information from the mesh to the effect.
  42683. * @param abstractMesh The mesh we are binding the information to render
  42684. * @param effect The effect we are binding the data to
  42685. */
  42686. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42687. var manager = abstractMesh.morphTargetManager;
  42688. if (!abstractMesh || !manager) {
  42689. return;
  42690. }
  42691. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42692. };
  42693. /**
  42694. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42695. * @param defines The generated defines used in the effect
  42696. * @param effect The effect we are binding the data to
  42697. * @param scene The scene we are willing to render with logarithmic scale for
  42698. */
  42699. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42700. if (defines["LOGARITHMICDEPTH"]) {
  42701. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42702. }
  42703. };
  42704. /**
  42705. * Binds the clip plane information from the scene to the effect.
  42706. * @param scene The scene the clip plane information are extracted from
  42707. * @param effect The effect we are binding the data to
  42708. */
  42709. MaterialHelper.BindClipPlane = function (effect, scene) {
  42710. if (scene.clipPlane) {
  42711. var clipPlane = scene.clipPlane;
  42712. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42713. }
  42714. };
  42715. return MaterialHelper;
  42716. }());
  42717. BABYLON.MaterialHelper = MaterialHelper;
  42718. })(BABYLON || (BABYLON = {}));
  42719. //# sourceMappingURL=babylon.materialHelper.js.map
  42720. var BABYLON;
  42721. (function (BABYLON) {
  42722. var PushMaterial = /** @class */ (function (_super) {
  42723. __extends(PushMaterial, _super);
  42724. function PushMaterial(name, scene) {
  42725. var _this = _super.call(this, name, scene) || this;
  42726. _this._normalMatrix = new BABYLON.Matrix();
  42727. _this.storeEffectOnSubMeshes = true;
  42728. return _this;
  42729. }
  42730. PushMaterial.prototype.getEffect = function () {
  42731. return this._activeEffect;
  42732. };
  42733. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42734. if (!mesh) {
  42735. return false;
  42736. }
  42737. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42738. return true;
  42739. }
  42740. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42741. };
  42742. /**
  42743. * Binds the given world matrix to the active effect
  42744. *
  42745. * @param world the matrix to bind
  42746. */
  42747. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42748. this._activeEffect.setMatrix("world", world);
  42749. };
  42750. /**
  42751. * Binds the given normal matrix to the active effect
  42752. *
  42753. * @param normalMatrix the matrix to bind
  42754. */
  42755. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42756. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42757. };
  42758. PushMaterial.prototype.bind = function (world, mesh) {
  42759. if (!mesh) {
  42760. return;
  42761. }
  42762. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42763. };
  42764. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42765. if (effect === void 0) { effect = null; }
  42766. _super.prototype._afterBind.call(this, mesh);
  42767. this.getScene()._cachedEffect = effect;
  42768. };
  42769. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42770. if (visibility === void 0) { visibility = 1; }
  42771. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42772. };
  42773. return PushMaterial;
  42774. }(BABYLON.Material));
  42775. BABYLON.PushMaterial = PushMaterial;
  42776. })(BABYLON || (BABYLON = {}));
  42777. //# sourceMappingURL=babylon.pushMaterial.js.map
  42778. var BABYLON;
  42779. (function (BABYLON) {
  42780. /** @hidden */
  42781. var StandardMaterialDefines = /** @class */ (function (_super) {
  42782. __extends(StandardMaterialDefines, _super);
  42783. function StandardMaterialDefines() {
  42784. var _this = _super.call(this) || this;
  42785. _this.MAINUV1 = false;
  42786. _this.MAINUV2 = false;
  42787. _this.DIFFUSE = false;
  42788. _this.DIFFUSEDIRECTUV = 0;
  42789. _this.AMBIENT = false;
  42790. _this.AMBIENTDIRECTUV = 0;
  42791. _this.OPACITY = false;
  42792. _this.OPACITYDIRECTUV = 0;
  42793. _this.OPACITYRGB = false;
  42794. _this.REFLECTION = false;
  42795. _this.EMISSIVE = false;
  42796. _this.EMISSIVEDIRECTUV = 0;
  42797. _this.SPECULAR = false;
  42798. _this.SPECULARDIRECTUV = 0;
  42799. _this.BUMP = false;
  42800. _this.BUMPDIRECTUV = 0;
  42801. _this.PARALLAX = false;
  42802. _this.PARALLAXOCCLUSION = false;
  42803. _this.SPECULAROVERALPHA = false;
  42804. _this.CLIPPLANE = false;
  42805. _this.ALPHATEST = false;
  42806. _this.DEPTHPREPASS = false;
  42807. _this.ALPHAFROMDIFFUSE = false;
  42808. _this.POINTSIZE = false;
  42809. _this.FOG = false;
  42810. _this.SPECULARTERM = false;
  42811. _this.DIFFUSEFRESNEL = false;
  42812. _this.OPACITYFRESNEL = false;
  42813. _this.REFLECTIONFRESNEL = false;
  42814. _this.REFRACTIONFRESNEL = false;
  42815. _this.EMISSIVEFRESNEL = false;
  42816. _this.FRESNEL = false;
  42817. _this.NORMAL = false;
  42818. _this.UV1 = false;
  42819. _this.UV2 = false;
  42820. _this.VERTEXCOLOR = false;
  42821. _this.VERTEXALPHA = false;
  42822. _this.NUM_BONE_INFLUENCERS = 0;
  42823. _this.BonesPerMesh = 0;
  42824. _this.INSTANCES = false;
  42825. _this.GLOSSINESS = false;
  42826. _this.ROUGHNESS = false;
  42827. _this.EMISSIVEASILLUMINATION = false;
  42828. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42829. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42830. _this.LIGHTMAP = false;
  42831. _this.LIGHTMAPDIRECTUV = 0;
  42832. _this.OBJECTSPACE_NORMALMAP = false;
  42833. _this.USELIGHTMAPASSHADOWMAP = false;
  42834. _this.REFLECTIONMAP_3D = false;
  42835. _this.REFLECTIONMAP_SPHERICAL = false;
  42836. _this.REFLECTIONMAP_PLANAR = false;
  42837. _this.REFLECTIONMAP_CUBIC = false;
  42838. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42839. _this.REFLECTIONMAP_PROJECTION = false;
  42840. _this.REFLECTIONMAP_SKYBOX = false;
  42841. _this.REFLECTIONMAP_EXPLICIT = false;
  42842. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42843. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42844. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42845. _this.INVERTCUBICMAP = false;
  42846. _this.LOGARITHMICDEPTH = false;
  42847. _this.REFRACTION = false;
  42848. _this.REFRACTIONMAP_3D = false;
  42849. _this.REFLECTIONOVERALPHA = false;
  42850. _this.TWOSIDEDLIGHTING = false;
  42851. _this.SHADOWFLOAT = false;
  42852. _this.MORPHTARGETS = false;
  42853. _this.MORPHTARGETS_NORMAL = false;
  42854. _this.MORPHTARGETS_TANGENT = false;
  42855. _this.NUM_MORPH_INFLUENCERS = 0;
  42856. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42857. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42858. _this.IMAGEPROCESSING = false;
  42859. _this.VIGNETTE = false;
  42860. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42861. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42862. _this.TONEMAPPING = false;
  42863. _this.CONTRAST = false;
  42864. _this.COLORCURVES = false;
  42865. _this.COLORGRADING = false;
  42866. _this.COLORGRADING3D = false;
  42867. _this.SAMPLER3DGREENDEPTH = false;
  42868. _this.SAMPLER3DBGRMAP = false;
  42869. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42870. /**
  42871. * If the reflection texture on this material is in linear color space
  42872. * @hidden
  42873. */
  42874. _this.IS_REFLECTION_LINEAR = false;
  42875. /**
  42876. * If the refraction texture on this material is in linear color space
  42877. * @hidden
  42878. */
  42879. _this.IS_REFRACTION_LINEAR = false;
  42880. _this.EXPOSURE = false;
  42881. _this.rebuild();
  42882. return _this;
  42883. }
  42884. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42885. var modes = [
  42886. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42887. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42888. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42889. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42890. ];
  42891. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42892. var mode = modes_1[_i];
  42893. this[mode] = (mode === modeToEnable);
  42894. }
  42895. };
  42896. return StandardMaterialDefines;
  42897. }(BABYLON.MaterialDefines));
  42898. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42899. var StandardMaterial = /** @class */ (function (_super) {
  42900. __extends(StandardMaterial, _super);
  42901. function StandardMaterial(name, scene) {
  42902. var _this = _super.call(this, name, scene) || this;
  42903. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42904. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42905. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42906. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42907. _this.specularPower = 64;
  42908. _this._useAlphaFromDiffuseTexture = false;
  42909. _this._useEmissiveAsIllumination = false;
  42910. _this._linkEmissiveWithDiffuse = false;
  42911. _this._useSpecularOverAlpha = false;
  42912. _this._useReflectionOverAlpha = false;
  42913. _this._disableLighting = false;
  42914. _this._useObjectSpaceNormalMap = false;
  42915. _this._useParallax = false;
  42916. _this._useParallaxOcclusion = false;
  42917. _this.parallaxScaleBias = 0.05;
  42918. _this._roughness = 0;
  42919. _this.indexOfRefraction = 0.98;
  42920. _this.invertRefractionY = true;
  42921. /**
  42922. * Defines the alpha limits in alpha test mode
  42923. */
  42924. _this.alphaCutOff = 0.4;
  42925. _this._useLightmapAsShadowmap = false;
  42926. _this._useReflectionFresnelFromSpecular = false;
  42927. _this._useGlossinessFromSpecularMapAlpha = false;
  42928. _this._maxSimultaneousLights = 4;
  42929. /**
  42930. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42931. */
  42932. _this._invertNormalMapX = false;
  42933. /**
  42934. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42935. */
  42936. _this._invertNormalMapY = false;
  42937. /**
  42938. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42939. */
  42940. _this._twoSidedLighting = false;
  42941. _this._renderTargets = new BABYLON.SmartArray(16);
  42942. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42943. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42944. // Setup the default processing configuration to the scene.
  42945. _this._attachImageProcessingConfiguration(null);
  42946. _this.getRenderTargetTextures = function () {
  42947. _this._renderTargets.reset();
  42948. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42949. _this._renderTargets.push(_this._reflectionTexture);
  42950. }
  42951. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42952. _this._renderTargets.push(_this._refractionTexture);
  42953. }
  42954. return _this._renderTargets;
  42955. };
  42956. return _this;
  42957. }
  42958. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42959. /**
  42960. * Gets the image processing configuration used either in this material.
  42961. */
  42962. get: function () {
  42963. return this._imageProcessingConfiguration;
  42964. },
  42965. /**
  42966. * Sets the Default image processing configuration used either in the this material.
  42967. *
  42968. * If sets to null, the scene one is in use.
  42969. */
  42970. set: function (value) {
  42971. this._attachImageProcessingConfiguration(value);
  42972. // Ensure the effect will be rebuilt.
  42973. this._markAllSubMeshesAsTexturesDirty();
  42974. },
  42975. enumerable: true,
  42976. configurable: true
  42977. });
  42978. /**
  42979. * Attaches a new image processing configuration to the Standard Material.
  42980. * @param configuration
  42981. */
  42982. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42983. var _this = this;
  42984. if (configuration === this._imageProcessingConfiguration) {
  42985. return;
  42986. }
  42987. // Detaches observer.
  42988. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42989. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42990. }
  42991. // Pick the scene configuration if needed.
  42992. if (!configuration) {
  42993. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42994. }
  42995. else {
  42996. this._imageProcessingConfiguration = configuration;
  42997. }
  42998. // Attaches observer.
  42999. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43000. _this._markAllSubMeshesAsImageProcessingDirty();
  43001. });
  43002. };
  43003. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43004. /**
  43005. * Gets wether the color curves effect is enabled.
  43006. */
  43007. get: function () {
  43008. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43009. },
  43010. /**
  43011. * Sets wether the color curves effect is enabled.
  43012. */
  43013. set: function (value) {
  43014. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43020. /**
  43021. * Gets wether the color grading effect is enabled.
  43022. */
  43023. get: function () {
  43024. return this.imageProcessingConfiguration.colorGradingEnabled;
  43025. },
  43026. /**
  43027. * Gets wether the color grading effect is enabled.
  43028. */
  43029. set: function (value) {
  43030. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43031. },
  43032. enumerable: true,
  43033. configurable: true
  43034. });
  43035. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43036. /**
  43037. * Gets wether tonemapping is enabled or not.
  43038. */
  43039. get: function () {
  43040. return this._imageProcessingConfiguration.toneMappingEnabled;
  43041. },
  43042. /**
  43043. * Sets wether tonemapping is enabled or not
  43044. */
  43045. set: function (value) {
  43046. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43047. },
  43048. enumerable: true,
  43049. configurable: true
  43050. });
  43051. ;
  43052. ;
  43053. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43054. /**
  43055. * The camera exposure used on this material.
  43056. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43057. * This corresponds to a photographic exposure.
  43058. */
  43059. get: function () {
  43060. return this._imageProcessingConfiguration.exposure;
  43061. },
  43062. /**
  43063. * The camera exposure used on this material.
  43064. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43065. * This corresponds to a photographic exposure.
  43066. */
  43067. set: function (value) {
  43068. this._imageProcessingConfiguration.exposure = value;
  43069. },
  43070. enumerable: true,
  43071. configurable: true
  43072. });
  43073. ;
  43074. ;
  43075. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43076. /**
  43077. * Gets The camera contrast used on this material.
  43078. */
  43079. get: function () {
  43080. return this._imageProcessingConfiguration.contrast;
  43081. },
  43082. /**
  43083. * Sets The camera contrast used on this material.
  43084. */
  43085. set: function (value) {
  43086. this._imageProcessingConfiguration.contrast = value;
  43087. },
  43088. enumerable: true,
  43089. configurable: true
  43090. });
  43091. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43092. /**
  43093. * Gets the Color Grading 2D Lookup Texture.
  43094. */
  43095. get: function () {
  43096. return this._imageProcessingConfiguration.colorGradingTexture;
  43097. },
  43098. /**
  43099. * Sets the Color Grading 2D Lookup Texture.
  43100. */
  43101. set: function (value) {
  43102. this._imageProcessingConfiguration.colorGradingTexture = value;
  43103. },
  43104. enumerable: true,
  43105. configurable: true
  43106. });
  43107. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43108. /**
  43109. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43110. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43111. * 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;
  43112. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43113. */
  43114. get: function () {
  43115. return this._imageProcessingConfiguration.colorCurves;
  43116. },
  43117. /**
  43118. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43119. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43120. * 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;
  43121. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43122. */
  43123. set: function (value) {
  43124. this._imageProcessingConfiguration.colorCurves = value;
  43125. },
  43126. enumerable: true,
  43127. configurable: true
  43128. });
  43129. StandardMaterial.prototype.getClassName = function () {
  43130. return "StandardMaterial";
  43131. };
  43132. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43133. get: function () {
  43134. return this._useLogarithmicDepth;
  43135. },
  43136. set: function (value) {
  43137. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43138. this._markAllSubMeshesAsMiscDirty();
  43139. },
  43140. enumerable: true,
  43141. configurable: true
  43142. });
  43143. StandardMaterial.prototype.needAlphaBlending = function () {
  43144. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43145. };
  43146. StandardMaterial.prototype.needAlphaTesting = function () {
  43147. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43148. };
  43149. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43150. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43151. };
  43152. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43153. return this._diffuseTexture;
  43154. };
  43155. /**
  43156. * Child classes can use it to update shaders
  43157. */
  43158. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43159. if (useInstances === void 0) { useInstances = false; }
  43160. if (subMesh.effect && this.isFrozen) {
  43161. if (this._wasPreviouslyReady && subMesh.effect) {
  43162. return true;
  43163. }
  43164. }
  43165. if (!subMesh._materialDefines) {
  43166. subMesh._materialDefines = new StandardMaterialDefines();
  43167. }
  43168. var scene = this.getScene();
  43169. var defines = subMesh._materialDefines;
  43170. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43171. if (defines._renderId === scene.getRenderId()) {
  43172. return true;
  43173. }
  43174. }
  43175. var engine = scene.getEngine();
  43176. // Lights
  43177. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43178. // Textures
  43179. if (defines._areTexturesDirty) {
  43180. defines._needUVs = false;
  43181. defines.MAINUV1 = false;
  43182. defines.MAINUV2 = false;
  43183. if (scene.texturesEnabled) {
  43184. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43185. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43186. return false;
  43187. }
  43188. else {
  43189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43190. }
  43191. }
  43192. else {
  43193. defines.DIFFUSE = false;
  43194. }
  43195. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43196. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43197. return false;
  43198. }
  43199. else {
  43200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43201. }
  43202. }
  43203. else {
  43204. defines.AMBIENT = false;
  43205. }
  43206. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43207. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43208. return false;
  43209. }
  43210. else {
  43211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43212. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43213. }
  43214. }
  43215. else {
  43216. defines.OPACITY = false;
  43217. }
  43218. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43219. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43220. return false;
  43221. }
  43222. else {
  43223. defines._needNormals = true;
  43224. defines.REFLECTION = true;
  43225. defines.ROUGHNESS = (this._roughness > 0);
  43226. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43227. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43228. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43229. switch (this._reflectionTexture.coordinatesMode) {
  43230. case BABYLON.Texture.EXPLICIT_MODE:
  43231. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43232. break;
  43233. case BABYLON.Texture.PLANAR_MODE:
  43234. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43235. break;
  43236. case BABYLON.Texture.PROJECTION_MODE:
  43237. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43238. break;
  43239. case BABYLON.Texture.SKYBOX_MODE:
  43240. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43241. break;
  43242. case BABYLON.Texture.SPHERICAL_MODE:
  43243. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43244. break;
  43245. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43246. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43247. break;
  43248. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43249. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43250. break;
  43251. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43252. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43253. break;
  43254. case BABYLON.Texture.CUBIC_MODE:
  43255. case BABYLON.Texture.INVCUBIC_MODE:
  43256. default:
  43257. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43258. break;
  43259. }
  43260. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43261. }
  43262. }
  43263. else {
  43264. defines.REFLECTION = false;
  43265. }
  43266. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43267. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43268. return false;
  43269. }
  43270. else {
  43271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43272. }
  43273. }
  43274. else {
  43275. defines.EMISSIVE = false;
  43276. }
  43277. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43278. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43279. return false;
  43280. }
  43281. else {
  43282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43283. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43284. }
  43285. }
  43286. else {
  43287. defines.LIGHTMAP = false;
  43288. }
  43289. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43290. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43291. return false;
  43292. }
  43293. else {
  43294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43295. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43296. }
  43297. }
  43298. else {
  43299. defines.SPECULAR = false;
  43300. }
  43301. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43302. // Bump texure can not be not blocking.
  43303. if (!this._bumpTexture.isReady()) {
  43304. return false;
  43305. }
  43306. else {
  43307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43308. defines.PARALLAX = this._useParallax;
  43309. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43310. }
  43311. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43312. }
  43313. else {
  43314. defines.BUMP = false;
  43315. }
  43316. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43317. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43318. return false;
  43319. }
  43320. else {
  43321. defines._needUVs = true;
  43322. defines.REFRACTION = true;
  43323. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43324. }
  43325. }
  43326. else {
  43327. defines.REFRACTION = false;
  43328. }
  43329. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43330. }
  43331. else {
  43332. defines.DIFFUSE = false;
  43333. defines.AMBIENT = false;
  43334. defines.OPACITY = false;
  43335. defines.REFLECTION = false;
  43336. defines.EMISSIVE = false;
  43337. defines.LIGHTMAP = false;
  43338. defines.BUMP = false;
  43339. defines.REFRACTION = false;
  43340. }
  43341. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43342. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43343. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43344. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43345. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43346. }
  43347. if (defines._areImageProcessingDirty) {
  43348. if (!this._imageProcessingConfiguration.isReady()) {
  43349. return false;
  43350. }
  43351. this._imageProcessingConfiguration.prepareDefines(defines);
  43352. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43353. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43354. }
  43355. if (defines._areFresnelDirty) {
  43356. if (StandardMaterial.FresnelEnabled) {
  43357. // Fresnel
  43358. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43359. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43360. this._reflectionFresnelParameters) {
  43361. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43362. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43363. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43364. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43365. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43366. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43367. defines._needNormals = true;
  43368. defines.FRESNEL = true;
  43369. }
  43370. }
  43371. else {
  43372. defines.FRESNEL = false;
  43373. }
  43374. }
  43375. // Misc.
  43376. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43377. // Attribs
  43378. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43379. // Values that need to be evaluated on every frame
  43380. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43381. // Get correct effect
  43382. if (defines.isDirty) {
  43383. defines.markAsProcessed();
  43384. scene.resetCachedMaterial();
  43385. // Fallbacks
  43386. var fallbacks = new BABYLON.EffectFallbacks();
  43387. if (defines.REFLECTION) {
  43388. fallbacks.addFallback(0, "REFLECTION");
  43389. }
  43390. if (defines.SPECULAR) {
  43391. fallbacks.addFallback(0, "SPECULAR");
  43392. }
  43393. if (defines.BUMP) {
  43394. fallbacks.addFallback(0, "BUMP");
  43395. }
  43396. if (defines.PARALLAX) {
  43397. fallbacks.addFallback(1, "PARALLAX");
  43398. }
  43399. if (defines.PARALLAXOCCLUSION) {
  43400. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43401. }
  43402. if (defines.SPECULAROVERALPHA) {
  43403. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43404. }
  43405. if (defines.FOG) {
  43406. fallbacks.addFallback(1, "FOG");
  43407. }
  43408. if (defines.POINTSIZE) {
  43409. fallbacks.addFallback(0, "POINTSIZE");
  43410. }
  43411. if (defines.LOGARITHMICDEPTH) {
  43412. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43413. }
  43414. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43415. if (defines.SPECULARTERM) {
  43416. fallbacks.addFallback(0, "SPECULARTERM");
  43417. }
  43418. if (defines.DIFFUSEFRESNEL) {
  43419. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43420. }
  43421. if (defines.OPACITYFRESNEL) {
  43422. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43423. }
  43424. if (defines.REFLECTIONFRESNEL) {
  43425. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43426. }
  43427. if (defines.EMISSIVEFRESNEL) {
  43428. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43429. }
  43430. if (defines.FRESNEL) {
  43431. fallbacks.addFallback(4, "FRESNEL");
  43432. }
  43433. //Attributes
  43434. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43435. if (defines.NORMAL) {
  43436. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43437. }
  43438. if (defines.UV1) {
  43439. attribs.push(BABYLON.VertexBuffer.UVKind);
  43440. }
  43441. if (defines.UV2) {
  43442. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43443. }
  43444. if (defines.VERTEXCOLOR) {
  43445. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43446. }
  43447. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43448. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43449. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43450. var shaderName = "default";
  43451. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43452. "vFogInfos", "vFogColor", "pointSize",
  43453. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43454. "mBones",
  43455. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43456. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43457. "vReflectionPosition", "vReflectionSize",
  43458. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43459. ];
  43460. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43461. var uniformBuffers = ["Material", "Scene"];
  43462. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43463. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43464. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43465. uniformsNames: uniforms,
  43466. uniformBuffersNames: uniformBuffers,
  43467. samplers: samplers,
  43468. defines: defines,
  43469. maxSimultaneousLights: this._maxSimultaneousLights
  43470. });
  43471. if (this.customShaderNameResolve) {
  43472. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43473. }
  43474. var join = defines.toString();
  43475. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43476. attributes: attribs,
  43477. uniformsNames: uniforms,
  43478. uniformBuffersNames: uniformBuffers,
  43479. samplers: samplers,
  43480. defines: join,
  43481. fallbacks: fallbacks,
  43482. onCompiled: this.onCompiled,
  43483. onError: this.onError,
  43484. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43485. }, engine), defines);
  43486. this.buildUniformLayout();
  43487. }
  43488. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43489. return false;
  43490. }
  43491. defines._renderId = scene.getRenderId();
  43492. this._wasPreviouslyReady = true;
  43493. return true;
  43494. };
  43495. StandardMaterial.prototype.buildUniformLayout = function () {
  43496. // Order is important !
  43497. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43498. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43499. this._uniformBuffer.addUniform("opacityParts", 4);
  43500. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43501. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43502. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43503. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43504. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43505. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43506. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43507. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43508. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43509. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43510. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43511. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43512. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43513. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43514. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43515. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43516. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43517. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43518. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43519. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43520. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43521. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43522. this._uniformBuffer.addUniform("specularMatrix", 16);
  43523. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43524. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43525. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43526. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43527. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43528. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43529. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43530. this._uniformBuffer.addUniform("pointSize", 1);
  43531. this._uniformBuffer.create();
  43532. };
  43533. StandardMaterial.prototype.unbind = function () {
  43534. if (this._activeEffect) {
  43535. var needFlag = false;
  43536. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43537. this._activeEffect.setTexture("reflection2DSampler", null);
  43538. needFlag = true;
  43539. }
  43540. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43541. this._activeEffect.setTexture("refraction2DSampler", null);
  43542. needFlag = true;
  43543. }
  43544. if (needFlag) {
  43545. this._markAllSubMeshesAsTexturesDirty();
  43546. }
  43547. }
  43548. _super.prototype.unbind.call(this);
  43549. };
  43550. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43551. var scene = this.getScene();
  43552. var defines = subMesh._materialDefines;
  43553. if (!defines) {
  43554. return;
  43555. }
  43556. var effect = subMesh.effect;
  43557. if (!effect) {
  43558. return;
  43559. }
  43560. this._activeEffect = effect;
  43561. // Matrices
  43562. this.bindOnlyWorldMatrix(world);
  43563. // Normal Matrix
  43564. if (defines.OBJECTSPACE_NORMALMAP) {
  43565. world.toNormalMatrix(this._normalMatrix);
  43566. this.bindOnlyNormalMatrix(this._normalMatrix);
  43567. }
  43568. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43569. // Bones
  43570. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43571. if (mustRebind) {
  43572. this._uniformBuffer.bindToEffect(effect, "Material");
  43573. this.bindViewProjection(effect);
  43574. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43575. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43576. // Fresnel
  43577. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43578. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43579. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43580. }
  43581. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43582. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43583. }
  43584. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43585. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43586. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43587. }
  43588. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43589. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43590. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43591. }
  43592. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43593. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43594. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43595. }
  43596. }
  43597. // Textures
  43598. if (scene.texturesEnabled) {
  43599. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43600. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43601. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43602. if (this._diffuseTexture.hasAlpha) {
  43603. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43604. }
  43605. }
  43606. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43607. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43608. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43609. }
  43610. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43611. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43612. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43613. }
  43614. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43615. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43616. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43617. if (this._reflectionTexture.boundingBoxSize) {
  43618. var cubeTexture = this._reflectionTexture;
  43619. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43620. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43621. }
  43622. }
  43623. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43624. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43625. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43626. }
  43627. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43628. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43629. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43630. }
  43631. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43632. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43633. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43634. }
  43635. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43636. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43637. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43638. if (scene._mirroredCameraPosition) {
  43639. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43640. }
  43641. else {
  43642. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43643. }
  43644. }
  43645. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43646. var depth = 1.0;
  43647. if (!this._refractionTexture.isCube) {
  43648. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43649. if (this._refractionTexture.depth) {
  43650. depth = this._refractionTexture.depth;
  43651. }
  43652. }
  43653. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43654. }
  43655. }
  43656. // Point size
  43657. if (this.pointsCloud) {
  43658. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43659. }
  43660. if (defines.SPECULARTERM) {
  43661. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43662. }
  43663. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43664. // Diffuse
  43665. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43666. }
  43667. // Textures
  43668. if (scene.texturesEnabled) {
  43669. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43670. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43671. }
  43672. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43673. effect.setTexture("ambientSampler", this._ambientTexture);
  43674. }
  43675. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43676. effect.setTexture("opacitySampler", this._opacityTexture);
  43677. }
  43678. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43679. if (this._reflectionTexture.isCube) {
  43680. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43681. }
  43682. else {
  43683. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43684. }
  43685. }
  43686. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43687. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43688. }
  43689. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43690. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43691. }
  43692. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43693. effect.setTexture("specularSampler", this._specularTexture);
  43694. }
  43695. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43696. effect.setTexture("bumpSampler", this._bumpTexture);
  43697. }
  43698. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43699. var depth = 1.0;
  43700. if (this._refractionTexture.isCube) {
  43701. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43702. }
  43703. else {
  43704. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43705. }
  43706. }
  43707. }
  43708. // Clip plane
  43709. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43710. // Colors
  43711. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43712. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43713. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43714. }
  43715. if (mustRebind || !this.isFrozen) {
  43716. // Lights
  43717. if (scene.lightsEnabled && !this._disableLighting) {
  43718. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43719. }
  43720. // View
  43721. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43722. this.bindView(effect);
  43723. }
  43724. // Fog
  43725. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43726. // Morph targets
  43727. if (defines.NUM_MORPH_INFLUENCERS) {
  43728. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43729. }
  43730. // Log. depth
  43731. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43732. // image processing
  43733. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43734. this._imageProcessingConfiguration.bind(this._activeEffect);
  43735. }
  43736. }
  43737. this._uniformBuffer.update();
  43738. this._afterBind(mesh, this._activeEffect);
  43739. };
  43740. StandardMaterial.prototype.getAnimatables = function () {
  43741. var results = [];
  43742. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43743. results.push(this._diffuseTexture);
  43744. }
  43745. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43746. results.push(this._ambientTexture);
  43747. }
  43748. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43749. results.push(this._opacityTexture);
  43750. }
  43751. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43752. results.push(this._reflectionTexture);
  43753. }
  43754. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43755. results.push(this._emissiveTexture);
  43756. }
  43757. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43758. results.push(this._specularTexture);
  43759. }
  43760. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43761. results.push(this._bumpTexture);
  43762. }
  43763. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43764. results.push(this._lightmapTexture);
  43765. }
  43766. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43767. results.push(this._refractionTexture);
  43768. }
  43769. return results;
  43770. };
  43771. StandardMaterial.prototype.getActiveTextures = function () {
  43772. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43773. if (this._diffuseTexture) {
  43774. activeTextures.push(this._diffuseTexture);
  43775. }
  43776. if (this._ambientTexture) {
  43777. activeTextures.push(this._ambientTexture);
  43778. }
  43779. if (this._opacityTexture) {
  43780. activeTextures.push(this._opacityTexture);
  43781. }
  43782. if (this._reflectionTexture) {
  43783. activeTextures.push(this._reflectionTexture);
  43784. }
  43785. if (this._emissiveTexture) {
  43786. activeTextures.push(this._emissiveTexture);
  43787. }
  43788. if (this._specularTexture) {
  43789. activeTextures.push(this._specularTexture);
  43790. }
  43791. if (this._bumpTexture) {
  43792. activeTextures.push(this._bumpTexture);
  43793. }
  43794. if (this._lightmapTexture) {
  43795. activeTextures.push(this._lightmapTexture);
  43796. }
  43797. if (this._refractionTexture) {
  43798. activeTextures.push(this._refractionTexture);
  43799. }
  43800. return activeTextures;
  43801. };
  43802. StandardMaterial.prototype.hasTexture = function (texture) {
  43803. if (_super.prototype.hasTexture.call(this, texture)) {
  43804. return true;
  43805. }
  43806. if (this._diffuseTexture === texture) {
  43807. return true;
  43808. }
  43809. if (this._ambientTexture === texture) {
  43810. return true;
  43811. }
  43812. if (this._opacityTexture === texture) {
  43813. return true;
  43814. }
  43815. if (this._reflectionTexture === texture) {
  43816. return true;
  43817. }
  43818. if (this._emissiveTexture === texture) {
  43819. return true;
  43820. }
  43821. if (this._specularTexture === texture) {
  43822. return true;
  43823. }
  43824. if (this._bumpTexture === texture) {
  43825. return true;
  43826. }
  43827. if (this._lightmapTexture === texture) {
  43828. return true;
  43829. }
  43830. if (this._refractionTexture === texture) {
  43831. return true;
  43832. }
  43833. return false;
  43834. };
  43835. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43836. if (forceDisposeTextures) {
  43837. if (this._diffuseTexture) {
  43838. this._diffuseTexture.dispose();
  43839. }
  43840. if (this._ambientTexture) {
  43841. this._ambientTexture.dispose();
  43842. }
  43843. if (this._opacityTexture) {
  43844. this._opacityTexture.dispose();
  43845. }
  43846. if (this._reflectionTexture) {
  43847. this._reflectionTexture.dispose();
  43848. }
  43849. if (this._emissiveTexture) {
  43850. this._emissiveTexture.dispose();
  43851. }
  43852. if (this._specularTexture) {
  43853. this._specularTexture.dispose();
  43854. }
  43855. if (this._bumpTexture) {
  43856. this._bumpTexture.dispose();
  43857. }
  43858. if (this._lightmapTexture) {
  43859. this._lightmapTexture.dispose();
  43860. }
  43861. if (this._refractionTexture) {
  43862. this._refractionTexture.dispose();
  43863. }
  43864. }
  43865. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43866. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43867. }
  43868. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43869. };
  43870. StandardMaterial.prototype.clone = function (name) {
  43871. var _this = this;
  43872. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43873. result.name = name;
  43874. result.id = name;
  43875. return result;
  43876. };
  43877. StandardMaterial.prototype.serialize = function () {
  43878. return BABYLON.SerializationHelper.Serialize(this);
  43879. };
  43880. // Statics
  43881. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43882. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43883. };
  43884. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43885. get: function () {
  43886. return StandardMaterial._DiffuseTextureEnabled;
  43887. },
  43888. set: function (value) {
  43889. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43890. return;
  43891. }
  43892. StandardMaterial._DiffuseTextureEnabled = value;
  43893. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43894. },
  43895. enumerable: true,
  43896. configurable: true
  43897. });
  43898. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43899. get: function () {
  43900. return StandardMaterial._AmbientTextureEnabled;
  43901. },
  43902. set: function (value) {
  43903. if (StandardMaterial._AmbientTextureEnabled === value) {
  43904. return;
  43905. }
  43906. StandardMaterial._AmbientTextureEnabled = value;
  43907. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43908. },
  43909. enumerable: true,
  43910. configurable: true
  43911. });
  43912. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43913. get: function () {
  43914. return StandardMaterial._OpacityTextureEnabled;
  43915. },
  43916. set: function (value) {
  43917. if (StandardMaterial._OpacityTextureEnabled === value) {
  43918. return;
  43919. }
  43920. StandardMaterial._OpacityTextureEnabled = value;
  43921. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43922. },
  43923. enumerable: true,
  43924. configurable: true
  43925. });
  43926. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43927. get: function () {
  43928. return StandardMaterial._ReflectionTextureEnabled;
  43929. },
  43930. set: function (value) {
  43931. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43932. return;
  43933. }
  43934. StandardMaterial._ReflectionTextureEnabled = value;
  43935. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43936. },
  43937. enumerable: true,
  43938. configurable: true
  43939. });
  43940. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43941. get: function () {
  43942. return StandardMaterial._EmissiveTextureEnabled;
  43943. },
  43944. set: function (value) {
  43945. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43946. return;
  43947. }
  43948. StandardMaterial._EmissiveTextureEnabled = value;
  43949. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43950. },
  43951. enumerable: true,
  43952. configurable: true
  43953. });
  43954. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43955. get: function () {
  43956. return StandardMaterial._SpecularTextureEnabled;
  43957. },
  43958. set: function (value) {
  43959. if (StandardMaterial._SpecularTextureEnabled === value) {
  43960. return;
  43961. }
  43962. StandardMaterial._SpecularTextureEnabled = value;
  43963. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43964. },
  43965. enumerable: true,
  43966. configurable: true
  43967. });
  43968. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43969. get: function () {
  43970. return StandardMaterial._BumpTextureEnabled;
  43971. },
  43972. set: function (value) {
  43973. if (StandardMaterial._BumpTextureEnabled === value) {
  43974. return;
  43975. }
  43976. StandardMaterial._BumpTextureEnabled = value;
  43977. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43978. },
  43979. enumerable: true,
  43980. configurable: true
  43981. });
  43982. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43983. get: function () {
  43984. return StandardMaterial._LightmapTextureEnabled;
  43985. },
  43986. set: function (value) {
  43987. if (StandardMaterial._LightmapTextureEnabled === value) {
  43988. return;
  43989. }
  43990. StandardMaterial._LightmapTextureEnabled = value;
  43991. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43997. get: function () {
  43998. return StandardMaterial._RefractionTextureEnabled;
  43999. },
  44000. set: function (value) {
  44001. if (StandardMaterial._RefractionTextureEnabled === value) {
  44002. return;
  44003. }
  44004. StandardMaterial._RefractionTextureEnabled = value;
  44005. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44011. get: function () {
  44012. return StandardMaterial._ColorGradingTextureEnabled;
  44013. },
  44014. set: function (value) {
  44015. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44016. return;
  44017. }
  44018. StandardMaterial._ColorGradingTextureEnabled = value;
  44019. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44020. },
  44021. enumerable: true,
  44022. configurable: true
  44023. });
  44024. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44025. get: function () {
  44026. return StandardMaterial._FresnelEnabled;
  44027. },
  44028. set: function (value) {
  44029. if (StandardMaterial._FresnelEnabled === value) {
  44030. return;
  44031. }
  44032. StandardMaterial._FresnelEnabled = value;
  44033. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44034. },
  44035. enumerable: true,
  44036. configurable: true
  44037. });
  44038. // Flags used to enable or disable a type of texture for all Standard Materials
  44039. StandardMaterial._DiffuseTextureEnabled = true;
  44040. StandardMaterial._AmbientTextureEnabled = true;
  44041. StandardMaterial._OpacityTextureEnabled = true;
  44042. StandardMaterial._ReflectionTextureEnabled = true;
  44043. StandardMaterial._EmissiveTextureEnabled = true;
  44044. StandardMaterial._SpecularTextureEnabled = true;
  44045. StandardMaterial._BumpTextureEnabled = true;
  44046. StandardMaterial._LightmapTextureEnabled = true;
  44047. StandardMaterial._RefractionTextureEnabled = true;
  44048. StandardMaterial._ColorGradingTextureEnabled = true;
  44049. StandardMaterial._FresnelEnabled = true;
  44050. __decorate([
  44051. BABYLON.serializeAsTexture("diffuseTexture")
  44052. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44053. __decorate([
  44054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44055. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44056. __decorate([
  44057. BABYLON.serializeAsTexture("ambientTexture")
  44058. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44059. __decorate([
  44060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44061. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44062. __decorate([
  44063. BABYLON.serializeAsTexture("opacityTexture")
  44064. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44065. __decorate([
  44066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44067. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44068. __decorate([
  44069. BABYLON.serializeAsTexture("reflectionTexture")
  44070. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44071. __decorate([
  44072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44073. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44074. __decorate([
  44075. BABYLON.serializeAsTexture("emissiveTexture")
  44076. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44077. __decorate([
  44078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44079. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44080. __decorate([
  44081. BABYLON.serializeAsTexture("specularTexture")
  44082. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44083. __decorate([
  44084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44085. ], StandardMaterial.prototype, "specularTexture", void 0);
  44086. __decorate([
  44087. BABYLON.serializeAsTexture("bumpTexture")
  44088. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44089. __decorate([
  44090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44091. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44092. __decorate([
  44093. BABYLON.serializeAsTexture("lightmapTexture")
  44094. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44095. __decorate([
  44096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44097. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44098. __decorate([
  44099. BABYLON.serializeAsTexture("refractionTexture")
  44100. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44101. __decorate([
  44102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44103. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44104. __decorate([
  44105. BABYLON.serializeAsColor3("ambient")
  44106. ], StandardMaterial.prototype, "ambientColor", void 0);
  44107. __decorate([
  44108. BABYLON.serializeAsColor3("diffuse")
  44109. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44110. __decorate([
  44111. BABYLON.serializeAsColor3("specular")
  44112. ], StandardMaterial.prototype, "specularColor", void 0);
  44113. __decorate([
  44114. BABYLON.serializeAsColor3("emissive")
  44115. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44116. __decorate([
  44117. BABYLON.serialize()
  44118. ], StandardMaterial.prototype, "specularPower", void 0);
  44119. __decorate([
  44120. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44121. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44122. __decorate([
  44123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44124. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44125. __decorate([
  44126. BABYLON.serialize("useEmissiveAsIllumination")
  44127. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44128. __decorate([
  44129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44130. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44131. __decorate([
  44132. BABYLON.serialize("linkEmissiveWithDiffuse")
  44133. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44134. __decorate([
  44135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44136. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44137. __decorate([
  44138. BABYLON.serialize("useSpecularOverAlpha")
  44139. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44140. __decorate([
  44141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44142. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44143. __decorate([
  44144. BABYLON.serialize("useReflectionOverAlpha")
  44145. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44146. __decorate([
  44147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44148. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44149. __decorate([
  44150. BABYLON.serialize("disableLighting")
  44151. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44152. __decorate([
  44153. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44154. ], StandardMaterial.prototype, "disableLighting", void 0);
  44155. __decorate([
  44156. BABYLON.serialize("useObjectSpaceNormalMap")
  44157. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44158. __decorate([
  44159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44160. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44161. __decorate([
  44162. BABYLON.serialize("useParallax")
  44163. ], StandardMaterial.prototype, "_useParallax", void 0);
  44164. __decorate([
  44165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44166. ], StandardMaterial.prototype, "useParallax", void 0);
  44167. __decorate([
  44168. BABYLON.serialize("useParallaxOcclusion")
  44169. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44170. __decorate([
  44171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44172. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44173. __decorate([
  44174. BABYLON.serialize()
  44175. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44176. __decorate([
  44177. BABYLON.serialize("roughness")
  44178. ], StandardMaterial.prototype, "_roughness", void 0);
  44179. __decorate([
  44180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44181. ], StandardMaterial.prototype, "roughness", void 0);
  44182. __decorate([
  44183. BABYLON.serialize()
  44184. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44185. __decorate([
  44186. BABYLON.serialize()
  44187. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44188. __decorate([
  44189. BABYLON.serialize()
  44190. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44191. __decorate([
  44192. BABYLON.serialize("useLightmapAsShadowmap")
  44193. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44194. __decorate([
  44195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44196. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44197. __decorate([
  44198. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44199. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44200. __decorate([
  44201. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44202. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44203. __decorate([
  44204. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44205. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44206. __decorate([
  44207. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44208. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44209. __decorate([
  44210. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44211. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44212. __decorate([
  44213. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44214. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44215. __decorate([
  44216. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44217. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44218. __decorate([
  44219. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44220. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44221. __decorate([
  44222. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44223. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44224. __decorate([
  44225. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44226. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44227. __decorate([
  44228. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44229. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44230. __decorate([
  44231. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44232. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44233. __decorate([
  44234. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44235. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44236. __decorate([
  44237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44238. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44239. __decorate([
  44240. BABYLON.serialize("maxSimultaneousLights")
  44241. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44242. __decorate([
  44243. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44244. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44245. __decorate([
  44246. BABYLON.serialize("invertNormalMapX")
  44247. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44248. __decorate([
  44249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44250. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44251. __decorate([
  44252. BABYLON.serialize("invertNormalMapY")
  44253. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44254. __decorate([
  44255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44256. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44257. __decorate([
  44258. BABYLON.serialize("twoSidedLighting")
  44259. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44260. __decorate([
  44261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44262. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44263. __decorate([
  44264. BABYLON.serialize()
  44265. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44266. return StandardMaterial;
  44267. }(BABYLON.PushMaterial));
  44268. BABYLON.StandardMaterial = StandardMaterial;
  44269. })(BABYLON || (BABYLON = {}));
  44270. //# sourceMappingURL=babylon.standardMaterial.js.map
  44271. var BABYLON;
  44272. (function (BABYLON) {
  44273. /**
  44274. * Manages the defines for the PBR Material.
  44275. * @hiddenChildren
  44276. */
  44277. var PBRMaterialDefines = /** @class */ (function (_super) {
  44278. __extends(PBRMaterialDefines, _super);
  44279. /**
  44280. * Initializes the PBR Material defines.
  44281. */
  44282. function PBRMaterialDefines() {
  44283. var _this = _super.call(this) || this;
  44284. _this.PBR = true;
  44285. _this.MAINUV1 = false;
  44286. _this.MAINUV2 = false;
  44287. _this.UV1 = false;
  44288. _this.UV2 = false;
  44289. _this.ALBEDO = false;
  44290. _this.ALBEDODIRECTUV = 0;
  44291. _this.VERTEXCOLOR = false;
  44292. _this.AMBIENT = false;
  44293. _this.AMBIENTDIRECTUV = 0;
  44294. _this.AMBIENTINGRAYSCALE = false;
  44295. _this.OPACITY = false;
  44296. _this.VERTEXALPHA = false;
  44297. _this.OPACITYDIRECTUV = 0;
  44298. _this.OPACITYRGB = false;
  44299. _this.ALPHATEST = false;
  44300. _this.DEPTHPREPASS = false;
  44301. _this.ALPHABLEND = false;
  44302. _this.ALPHAFROMALBEDO = false;
  44303. _this.ALPHATESTVALUE = "0.5";
  44304. _this.SPECULAROVERALPHA = false;
  44305. _this.RADIANCEOVERALPHA = false;
  44306. _this.ALPHAFRESNEL = false;
  44307. _this.LINEARALPHAFRESNEL = false;
  44308. _this.PREMULTIPLYALPHA = false;
  44309. _this.EMISSIVE = false;
  44310. _this.EMISSIVEDIRECTUV = 0;
  44311. _this.REFLECTIVITY = false;
  44312. _this.REFLECTIVITYDIRECTUV = 0;
  44313. _this.SPECULARTERM = false;
  44314. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44315. _this.MICROSURFACEAUTOMATIC = false;
  44316. _this.LODBASEDMICROSFURACE = false;
  44317. _this.MICROSURFACEMAP = false;
  44318. _this.MICROSURFACEMAPDIRECTUV = 0;
  44319. _this.METALLICWORKFLOW = false;
  44320. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44321. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44322. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44323. _this.AOSTOREINMETALMAPRED = false;
  44324. _this.ENVIRONMENTBRDF = false;
  44325. _this.NORMAL = false;
  44326. _this.TANGENT = false;
  44327. _this.BUMP = false;
  44328. _this.BUMPDIRECTUV = 0;
  44329. _this.OBJECTSPACE_NORMALMAP = false;
  44330. _this.PARALLAX = false;
  44331. _this.PARALLAXOCCLUSION = false;
  44332. _this.NORMALXYSCALE = true;
  44333. _this.LIGHTMAP = false;
  44334. _this.LIGHTMAPDIRECTUV = 0;
  44335. _this.USELIGHTMAPASSHADOWMAP = false;
  44336. _this.GAMMALIGHTMAP = false;
  44337. _this.REFLECTION = false;
  44338. _this.REFLECTIONMAP_3D = false;
  44339. _this.REFLECTIONMAP_SPHERICAL = false;
  44340. _this.REFLECTIONMAP_PLANAR = false;
  44341. _this.REFLECTIONMAP_CUBIC = false;
  44342. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44343. _this.REFLECTIONMAP_PROJECTION = false;
  44344. _this.REFLECTIONMAP_SKYBOX = false;
  44345. _this.REFLECTIONMAP_EXPLICIT = false;
  44346. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44347. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44348. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44349. _this.INVERTCUBICMAP = false;
  44350. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44351. _this.USESPHERICALINVERTEX = false;
  44352. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44353. _this.LODINREFLECTIONALPHA = false;
  44354. _this.GAMMAREFLECTION = false;
  44355. _this.RADIANCEOCCLUSION = false;
  44356. _this.HORIZONOCCLUSION = false;
  44357. _this.REFRACTION = false;
  44358. _this.REFRACTIONMAP_3D = false;
  44359. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44360. _this.LODINREFRACTIONALPHA = false;
  44361. _this.GAMMAREFRACTION = false;
  44362. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44363. _this.INSTANCES = false;
  44364. _this.NUM_BONE_INFLUENCERS = 0;
  44365. _this.BonesPerMesh = 0;
  44366. _this.NONUNIFORMSCALING = false;
  44367. _this.MORPHTARGETS = false;
  44368. _this.MORPHTARGETS_NORMAL = false;
  44369. _this.MORPHTARGETS_TANGENT = false;
  44370. _this.NUM_MORPH_INFLUENCERS = 0;
  44371. _this.IMAGEPROCESSING = false;
  44372. _this.VIGNETTE = false;
  44373. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44374. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44375. _this.TONEMAPPING = false;
  44376. _this.CONTRAST = false;
  44377. _this.COLORCURVES = false;
  44378. _this.COLORGRADING = false;
  44379. _this.COLORGRADING3D = false;
  44380. _this.SAMPLER3DGREENDEPTH = false;
  44381. _this.SAMPLER3DBGRMAP = false;
  44382. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44383. _this.EXPOSURE = false;
  44384. _this.USEPHYSICALLIGHTFALLOFF = false;
  44385. _this.TWOSIDEDLIGHTING = false;
  44386. _this.SHADOWFLOAT = false;
  44387. _this.CLIPPLANE = false;
  44388. _this.POINTSIZE = false;
  44389. _this.FOG = false;
  44390. _this.LOGARITHMICDEPTH = false;
  44391. _this.FORCENORMALFORWARD = false;
  44392. _this.SPECULARAA = false;
  44393. _this.UNLIT = false;
  44394. _this.rebuild();
  44395. return _this;
  44396. }
  44397. /**
  44398. * Resets the PBR Material defines.
  44399. */
  44400. PBRMaterialDefines.prototype.reset = function () {
  44401. _super.prototype.reset.call(this);
  44402. this.ALPHATESTVALUE = "0.5";
  44403. this.PBR = true;
  44404. };
  44405. return PBRMaterialDefines;
  44406. }(BABYLON.MaterialDefines));
  44407. /**
  44408. * The Physically based material base class of BJS.
  44409. *
  44410. * This offers the main features of a standard PBR material.
  44411. * For more information, please refer to the documentation :
  44412. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44413. */
  44414. var PBRBaseMaterial = /** @class */ (function (_super) {
  44415. __extends(PBRBaseMaterial, _super);
  44416. /**
  44417. * Instantiates a new PBRMaterial instance.
  44418. *
  44419. * @param name The material name
  44420. * @param scene The scene the material will be use in.
  44421. */
  44422. function PBRBaseMaterial(name, scene) {
  44423. var _this = _super.call(this, name, scene) || this;
  44424. /**
  44425. * Intensity of the direct lights e.g. the four lights available in your scene.
  44426. * This impacts both the direct diffuse and specular highlights.
  44427. */
  44428. _this._directIntensity = 1.0;
  44429. /**
  44430. * Intensity of the emissive part of the material.
  44431. * This helps controlling the emissive effect without modifying the emissive color.
  44432. */
  44433. _this._emissiveIntensity = 1.0;
  44434. /**
  44435. * Intensity of the environment e.g. how much the environment will light the object
  44436. * either through harmonics for rough material or through the refelction for shiny ones.
  44437. */
  44438. _this._environmentIntensity = 1.0;
  44439. /**
  44440. * This is a special control allowing the reduction of the specular highlights coming from the
  44441. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44442. */
  44443. _this._specularIntensity = 1.0;
  44444. /**
  44445. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44446. */
  44447. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44448. /**
  44449. * Debug Control allowing disabling the bump map on this material.
  44450. */
  44451. _this._disableBumpMap = false;
  44452. /**
  44453. * AKA Occlusion Texture Intensity in other nomenclature.
  44454. */
  44455. _this._ambientTextureStrength = 1.0;
  44456. /**
  44457. * The color of a material in ambient lighting.
  44458. */
  44459. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44460. /**
  44461. * AKA Diffuse Color in other nomenclature.
  44462. */
  44463. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44464. /**
  44465. * AKA Specular Color in other nomenclature.
  44466. */
  44467. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44468. /**
  44469. * The color applied when light is reflected from a material.
  44470. */
  44471. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44472. /**
  44473. * The color applied when light is emitted from a material.
  44474. */
  44475. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44476. /**
  44477. * AKA Glossiness in other nomenclature.
  44478. */
  44479. _this._microSurface = 0.9;
  44480. /**
  44481. * source material index of refraction (IOR)' / 'destination material IOR.
  44482. */
  44483. _this._indexOfRefraction = 0.66;
  44484. /**
  44485. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44486. */
  44487. _this._invertRefractionY = false;
  44488. /**
  44489. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44490. * Materials half opaque for instance using refraction could benefit from this control.
  44491. */
  44492. _this._linkRefractionWithTransparency = false;
  44493. /**
  44494. * Specifies that the material will use the light map as a show map.
  44495. */
  44496. _this._useLightmapAsShadowmap = false;
  44497. /**
  44498. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44499. * makes the reflect vector face the model (under horizon).
  44500. */
  44501. _this._useHorizonOcclusion = true;
  44502. /**
  44503. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44504. * too much the area relying on ambient texture to define their ambient occlusion.
  44505. */
  44506. _this._useRadianceOcclusion = true;
  44507. /**
  44508. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44509. */
  44510. _this._useAlphaFromAlbedoTexture = false;
  44511. /**
  44512. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44513. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44514. */
  44515. _this._useSpecularOverAlpha = true;
  44516. /**
  44517. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44518. */
  44519. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44520. /**
  44521. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44522. */
  44523. _this._useRoughnessFromMetallicTextureAlpha = true;
  44524. /**
  44525. * Specifies if the metallic texture contains the roughness information in its green channel.
  44526. */
  44527. _this._useRoughnessFromMetallicTextureGreen = false;
  44528. /**
  44529. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44530. */
  44531. _this._useMetallnessFromMetallicTextureBlue = false;
  44532. /**
  44533. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44534. */
  44535. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44536. /**
  44537. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44538. */
  44539. _this._useAmbientInGrayScale = false;
  44540. /**
  44541. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44542. * The material will try to infer what glossiness each pixel should be.
  44543. */
  44544. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44545. /**
  44546. * BJS is using an harcoded light falloff based on a manually sets up range.
  44547. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44548. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44549. */
  44550. _this._usePhysicalLightFalloff = true;
  44551. /**
  44552. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44553. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44554. */
  44555. _this._useRadianceOverAlpha = true;
  44556. /**
  44557. * Allows using an object space normal map (instead of tangent space).
  44558. */
  44559. _this._useObjectSpaceNormalMap = false;
  44560. /**
  44561. * Allows using the bump map in parallax mode.
  44562. */
  44563. _this._useParallax = false;
  44564. /**
  44565. * Allows using the bump map in parallax occlusion mode.
  44566. */
  44567. _this._useParallaxOcclusion = false;
  44568. /**
  44569. * Controls the scale bias of the parallax mode.
  44570. */
  44571. _this._parallaxScaleBias = 0.05;
  44572. /**
  44573. * If sets to true, disables all the lights affecting the material.
  44574. */
  44575. _this._disableLighting = false;
  44576. /**
  44577. * Number of Simultaneous lights allowed on the material.
  44578. */
  44579. _this._maxSimultaneousLights = 4;
  44580. /**
  44581. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44582. */
  44583. _this._invertNormalMapX = false;
  44584. /**
  44585. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44586. */
  44587. _this._invertNormalMapY = false;
  44588. /**
  44589. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44590. */
  44591. _this._twoSidedLighting = false;
  44592. /**
  44593. * Defines the alpha limits in alpha test mode.
  44594. */
  44595. _this._alphaCutOff = 0.4;
  44596. /**
  44597. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44598. */
  44599. _this._forceAlphaTest = false;
  44600. /**
  44601. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44602. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44603. */
  44604. _this._useAlphaFresnel = false;
  44605. /**
  44606. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44607. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44608. */
  44609. _this._useLinearAlphaFresnel = false;
  44610. /**
  44611. * The transparency mode of the material.
  44612. */
  44613. _this._transparencyMode = null;
  44614. /**
  44615. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44616. * from cos thetav and roughness:
  44617. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44618. */
  44619. _this._environmentBRDFTexture = null;
  44620. /**
  44621. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44622. */
  44623. _this._forceIrradianceInFragment = false;
  44624. /**
  44625. * Force normal to face away from face.
  44626. */
  44627. _this._forceNormalForward = false;
  44628. /**
  44629. * Enables specular anti aliasing in the PBR shader.
  44630. * It will both interacts on the Geometry for analytical and IBL lighting.
  44631. * It also prefilter the roughness map based on the bump values.
  44632. */
  44633. _this._enableSpecularAntiAliasing = false;
  44634. /**
  44635. * Stores the available render targets.
  44636. */
  44637. _this._renderTargets = new BABYLON.SmartArray(16);
  44638. /**
  44639. * Sets the global ambient color for the material used in lighting calculations.
  44640. */
  44641. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44642. /**
  44643. * If set to true, no lighting calculations will be applied.
  44644. */
  44645. _this._unlit = false;
  44646. // Setup the default processing configuration to the scene.
  44647. _this._attachImageProcessingConfiguration(null);
  44648. _this.getRenderTargetTextures = function () {
  44649. _this._renderTargets.reset();
  44650. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44651. _this._renderTargets.push(_this._reflectionTexture);
  44652. }
  44653. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44654. _this._renderTargets.push(_this._refractionTexture);
  44655. }
  44656. return _this._renderTargets;
  44657. };
  44658. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44659. return _this;
  44660. }
  44661. /**
  44662. * Attaches a new image processing configuration to the PBR Material.
  44663. * @param configuration
  44664. */
  44665. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44666. var _this = this;
  44667. if (configuration === this._imageProcessingConfiguration) {
  44668. return;
  44669. }
  44670. // Detaches observer.
  44671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44673. }
  44674. // Pick the scene configuration if needed.
  44675. if (!configuration) {
  44676. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44677. }
  44678. else {
  44679. this._imageProcessingConfiguration = configuration;
  44680. }
  44681. // Attaches observer.
  44682. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44683. _this._markAllSubMeshesAsImageProcessingDirty();
  44684. });
  44685. };
  44686. /**
  44687. * Gets the name of the material class.
  44688. */
  44689. PBRBaseMaterial.prototype.getClassName = function () {
  44690. return "PBRBaseMaterial";
  44691. };
  44692. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44693. /**
  44694. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44695. */
  44696. get: function () {
  44697. return this._useLogarithmicDepth;
  44698. },
  44699. /**
  44700. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44701. */
  44702. set: function (value) {
  44703. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44704. },
  44705. enumerable: true,
  44706. configurable: true
  44707. });
  44708. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44709. /**
  44710. * Gets the current transparency mode.
  44711. */
  44712. get: function () {
  44713. return this._transparencyMode;
  44714. },
  44715. /**
  44716. * Sets the transparency mode of the material.
  44717. */
  44718. set: function (value) {
  44719. if (this._transparencyMode === value) {
  44720. return;
  44721. }
  44722. this._transparencyMode = value;
  44723. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44724. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44725. },
  44726. enumerable: true,
  44727. configurable: true
  44728. });
  44729. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44730. /**
  44731. * Returns true if alpha blending should be disabled.
  44732. */
  44733. get: function () {
  44734. return (this._linkRefractionWithTransparency ||
  44735. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44736. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44737. },
  44738. enumerable: true,
  44739. configurable: true
  44740. });
  44741. /**
  44742. * Specifies whether or not this material should be rendered in alpha blend mode.
  44743. */
  44744. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44745. if (this._disableAlphaBlending) {
  44746. return false;
  44747. }
  44748. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44749. };
  44750. /**
  44751. * Specifies if the mesh will require alpha blending.
  44752. * @param mesh - BJS mesh.
  44753. */
  44754. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44755. if (this._disableAlphaBlending) {
  44756. return false;
  44757. }
  44758. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44759. };
  44760. /**
  44761. * Specifies whether or not this material should be rendered in alpha test mode.
  44762. */
  44763. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44764. if (this._forceAlphaTest) {
  44765. return true;
  44766. }
  44767. if (this._linkRefractionWithTransparency) {
  44768. return false;
  44769. }
  44770. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44771. };
  44772. /**
  44773. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44774. */
  44775. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44776. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44777. };
  44778. /**
  44779. * Gets the texture used for the alpha test.
  44780. */
  44781. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44782. return this._albedoTexture;
  44783. };
  44784. /**
  44785. * Specifies that the submesh is ready to be used.
  44786. * @param mesh - BJS mesh.
  44787. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44788. * @param useInstances - Specifies that instances should be used.
  44789. * @returns - boolean indicating that the submesh is ready or not.
  44790. */
  44791. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44792. if (subMesh.effect && this.isFrozen) {
  44793. if (this._wasPreviouslyReady) {
  44794. return true;
  44795. }
  44796. }
  44797. if (!subMesh._materialDefines) {
  44798. subMesh._materialDefines = new PBRMaterialDefines();
  44799. }
  44800. var defines = subMesh._materialDefines;
  44801. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44802. if (defines._renderId === this.getScene().getRenderId()) {
  44803. return true;
  44804. }
  44805. }
  44806. var scene = this.getScene();
  44807. var engine = scene.getEngine();
  44808. if (defines._areTexturesDirty) {
  44809. if (scene.texturesEnabled) {
  44810. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44811. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44812. return false;
  44813. }
  44814. }
  44815. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44816. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44817. return false;
  44818. }
  44819. }
  44820. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44821. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44822. return false;
  44823. }
  44824. }
  44825. var reflectionTexture = this._getReflectionTexture();
  44826. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44827. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44828. return false;
  44829. }
  44830. }
  44831. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44832. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44833. return false;
  44834. }
  44835. }
  44836. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44837. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44838. return false;
  44839. }
  44840. }
  44841. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44842. if (this._metallicTexture) {
  44843. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44844. return false;
  44845. }
  44846. }
  44847. else if (this._reflectivityTexture) {
  44848. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44849. return false;
  44850. }
  44851. }
  44852. if (this._microSurfaceTexture) {
  44853. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44854. return false;
  44855. }
  44856. }
  44857. }
  44858. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44859. // Bump texture cannot be not blocking.
  44860. if (!this._bumpTexture.isReady()) {
  44861. return false;
  44862. }
  44863. }
  44864. var refractionTexture = this._getRefractionTexture();
  44865. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44866. if (!refractionTexture.isReadyOrNotBlocking()) {
  44867. return false;
  44868. }
  44869. }
  44870. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44871. // This is blocking.
  44872. if (!this._environmentBRDFTexture.isReady()) {
  44873. return false;
  44874. }
  44875. }
  44876. }
  44877. }
  44878. if (defines._areImageProcessingDirty) {
  44879. if (!this._imageProcessingConfiguration.isReady()) {
  44880. return false;
  44881. }
  44882. }
  44883. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44884. mesh.createNormals(true);
  44885. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44886. }
  44887. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44888. if (effect) {
  44889. scene.resetCachedMaterial();
  44890. subMesh.setEffect(effect, defines);
  44891. this.buildUniformLayout();
  44892. }
  44893. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44894. return false;
  44895. }
  44896. defines._renderId = scene.getRenderId();
  44897. this._wasPreviouslyReady = true;
  44898. return true;
  44899. };
  44900. /**
  44901. * Specifies if the material uses metallic roughness workflow.
  44902. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44903. */
  44904. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44905. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44906. return true;
  44907. }
  44908. return false;
  44909. };
  44910. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44911. if (onCompiled === void 0) { onCompiled = null; }
  44912. if (onError === void 0) { onError = null; }
  44913. if (useInstances === void 0) { useInstances = null; }
  44914. if (useClipPlane === void 0) { useClipPlane = null; }
  44915. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44916. if (!defines.isDirty) {
  44917. return null;
  44918. }
  44919. defines.markAsProcessed();
  44920. var scene = this.getScene();
  44921. var engine = scene.getEngine();
  44922. // Fallbacks
  44923. var fallbacks = new BABYLON.EffectFallbacks();
  44924. var fallbackRank = 0;
  44925. if (defines.USESPHERICALINVERTEX) {
  44926. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44927. }
  44928. if (defines.FOG) {
  44929. fallbacks.addFallback(fallbackRank, "FOG");
  44930. }
  44931. if (defines.SPECULARAA) {
  44932. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44933. }
  44934. if (defines.POINTSIZE) {
  44935. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44936. }
  44937. if (defines.LOGARITHMICDEPTH) {
  44938. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44939. }
  44940. if (defines.PARALLAX) {
  44941. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44942. }
  44943. if (defines.PARALLAXOCCLUSION) {
  44944. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44945. }
  44946. if (defines.ENVIRONMENTBRDF) {
  44947. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44948. }
  44949. if (defines.TANGENT) {
  44950. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44951. }
  44952. if (defines.BUMP) {
  44953. fallbacks.addFallback(fallbackRank++, "BUMP");
  44954. }
  44955. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44956. if (defines.SPECULARTERM) {
  44957. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44958. }
  44959. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44960. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44961. }
  44962. if (defines.LIGHTMAP) {
  44963. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44964. }
  44965. if (defines.NORMAL) {
  44966. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44967. }
  44968. if (defines.AMBIENT) {
  44969. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44970. }
  44971. if (defines.EMISSIVE) {
  44972. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44973. }
  44974. if (defines.VERTEXCOLOR) {
  44975. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44976. }
  44977. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44978. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44979. }
  44980. if (defines.MORPHTARGETS) {
  44981. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44982. }
  44983. //Attributes
  44984. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44985. if (defines.NORMAL) {
  44986. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44987. }
  44988. if (defines.TANGENT) {
  44989. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44990. }
  44991. if (defines.UV1) {
  44992. attribs.push(BABYLON.VertexBuffer.UVKind);
  44993. }
  44994. if (defines.UV2) {
  44995. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44996. }
  44997. if (defines.VERTEXCOLOR) {
  44998. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44999. }
  45000. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45001. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45002. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45003. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45004. "vFogInfos", "vFogColor", "pointSize",
  45005. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45006. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45007. "mBones",
  45008. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45009. "vLightingIntensity",
  45010. "logarithmicDepthConstant",
  45011. "vSphericalX", "vSphericalY", "vSphericalZ",
  45012. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45013. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45014. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45015. "vTangentSpaceParams"
  45016. ];
  45017. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45018. "bumpSampler", "lightmapSampler", "opacitySampler",
  45019. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45020. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45021. "microSurfaceSampler", "environmentBrdfSampler"];
  45022. var uniformBuffers = ["Material", "Scene"];
  45023. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45024. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45025. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45026. uniformsNames: uniforms,
  45027. uniformBuffersNames: uniformBuffers,
  45028. samplers: samplers,
  45029. defines: defines,
  45030. maxSimultaneousLights: this._maxSimultaneousLights
  45031. });
  45032. var join = defines.toString();
  45033. return engine.createEffect("pbr", {
  45034. attributes: attribs,
  45035. uniformsNames: uniforms,
  45036. uniformBuffersNames: uniformBuffers,
  45037. samplers: samplers,
  45038. defines: join,
  45039. fallbacks: fallbacks,
  45040. onCompiled: onCompiled,
  45041. onError: onError,
  45042. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45043. }, engine);
  45044. };
  45045. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45046. if (useInstances === void 0) { useInstances = null; }
  45047. if (useClipPlane === void 0) { useClipPlane = null; }
  45048. var scene = this.getScene();
  45049. var engine = scene.getEngine();
  45050. // Lights
  45051. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45052. defines._needNormals = true;
  45053. // Textures
  45054. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45055. if (defines._areTexturesDirty) {
  45056. defines._needUVs = false;
  45057. if (scene.texturesEnabled) {
  45058. if (scene.getEngine().getCaps().textureLOD) {
  45059. defines.LODBASEDMICROSFURACE = true;
  45060. }
  45061. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45062. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45063. }
  45064. else {
  45065. defines.ALBEDO = false;
  45066. }
  45067. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45068. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45069. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45070. }
  45071. else {
  45072. defines.AMBIENT = false;
  45073. }
  45074. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45075. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45076. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45077. }
  45078. else {
  45079. defines.OPACITY = false;
  45080. }
  45081. var reflectionTexture = this._getReflectionTexture();
  45082. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45083. defines.REFLECTION = true;
  45084. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45085. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45086. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45087. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45088. defines.INVERTCUBICMAP = true;
  45089. }
  45090. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45091. switch (reflectionTexture.coordinatesMode) {
  45092. case BABYLON.Texture.EXPLICIT_MODE:
  45093. defines.REFLECTIONMAP_EXPLICIT = true;
  45094. break;
  45095. case BABYLON.Texture.PLANAR_MODE:
  45096. defines.REFLECTIONMAP_PLANAR = true;
  45097. break;
  45098. case BABYLON.Texture.PROJECTION_MODE:
  45099. defines.REFLECTIONMAP_PROJECTION = true;
  45100. break;
  45101. case BABYLON.Texture.SKYBOX_MODE:
  45102. defines.REFLECTIONMAP_SKYBOX = true;
  45103. break;
  45104. case BABYLON.Texture.SPHERICAL_MODE:
  45105. defines.REFLECTIONMAP_SPHERICAL = true;
  45106. break;
  45107. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45108. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45109. break;
  45110. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45111. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45112. break;
  45113. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45114. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45115. break;
  45116. case BABYLON.Texture.CUBIC_MODE:
  45117. case BABYLON.Texture.INVCUBIC_MODE:
  45118. default:
  45119. defines.REFLECTIONMAP_CUBIC = true;
  45120. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45121. break;
  45122. }
  45123. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45124. if (reflectionTexture.sphericalPolynomial) {
  45125. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45126. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45127. defines.USESPHERICALINVERTEX = false;
  45128. }
  45129. else {
  45130. defines.USESPHERICALINVERTEX = true;
  45131. }
  45132. }
  45133. }
  45134. }
  45135. else {
  45136. defines.REFLECTION = false;
  45137. defines.REFLECTIONMAP_3D = false;
  45138. defines.REFLECTIONMAP_SPHERICAL = false;
  45139. defines.REFLECTIONMAP_PLANAR = false;
  45140. defines.REFLECTIONMAP_CUBIC = false;
  45141. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45142. defines.REFLECTIONMAP_PROJECTION = false;
  45143. defines.REFLECTIONMAP_SKYBOX = false;
  45144. defines.REFLECTIONMAP_EXPLICIT = false;
  45145. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45146. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45147. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45148. defines.INVERTCUBICMAP = false;
  45149. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45150. defines.USESPHERICALINVERTEX = false;
  45151. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45152. defines.LODINREFLECTIONALPHA = false;
  45153. defines.GAMMAREFLECTION = false;
  45154. }
  45155. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45156. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45157. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45158. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45159. }
  45160. else {
  45161. defines.LIGHTMAP = false;
  45162. }
  45163. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45165. }
  45166. else {
  45167. defines.EMISSIVE = false;
  45168. }
  45169. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45170. if (this._metallicTexture) {
  45171. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45172. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45173. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45174. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45175. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45176. }
  45177. else if (this._reflectivityTexture) {
  45178. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45179. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45180. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45181. }
  45182. else {
  45183. defines.REFLECTIVITY = false;
  45184. }
  45185. if (this._microSurfaceTexture) {
  45186. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45187. }
  45188. else {
  45189. defines.MICROSURFACEMAP = false;
  45190. }
  45191. }
  45192. else {
  45193. defines.REFLECTIVITY = false;
  45194. defines.MICROSURFACEMAP = false;
  45195. }
  45196. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45197. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45198. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45199. defines.PARALLAX = true;
  45200. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45201. }
  45202. else {
  45203. defines.PARALLAX = false;
  45204. }
  45205. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45206. }
  45207. else {
  45208. defines.BUMP = false;
  45209. }
  45210. var refractionTexture = this._getRefractionTexture();
  45211. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45212. defines.REFRACTION = true;
  45213. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45214. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45215. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45216. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45217. if (this._linkRefractionWithTransparency) {
  45218. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45219. }
  45220. }
  45221. else {
  45222. defines.REFRACTION = false;
  45223. }
  45224. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45225. defines.ENVIRONMENTBRDF = true;
  45226. }
  45227. else {
  45228. defines.ENVIRONMENTBRDF = false;
  45229. }
  45230. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45231. defines.ALPHAFROMALBEDO = true;
  45232. }
  45233. else {
  45234. defines.ALPHAFROMALBEDO = false;
  45235. }
  45236. }
  45237. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45238. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45239. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45240. if (!this.backFaceCulling && this._twoSidedLighting) {
  45241. defines.TWOSIDEDLIGHTING = true;
  45242. }
  45243. else {
  45244. defines.TWOSIDEDLIGHTING = false;
  45245. }
  45246. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45247. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45248. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45249. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45250. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45251. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45252. }
  45253. if (defines._areImageProcessingDirty) {
  45254. this._imageProcessingConfiguration.prepareDefines(defines);
  45255. }
  45256. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45257. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45258. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45259. // Misc.
  45260. if (defines._areMiscDirty) {
  45261. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45262. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45263. }
  45264. // Values that need to be evaluated on every frame
  45265. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45266. // Attribs
  45267. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45268. };
  45269. /**
  45270. * Force shader compilation
  45271. */
  45272. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45273. var _this = this;
  45274. var localOptions = __assign({ clipPlane: false }, options);
  45275. var defines = new PBRMaterialDefines();
  45276. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45277. if (effect.isReady()) {
  45278. if (onCompiled) {
  45279. onCompiled(this);
  45280. }
  45281. }
  45282. else {
  45283. effect.onCompileObservable.add(function () {
  45284. if (onCompiled) {
  45285. onCompiled(_this);
  45286. }
  45287. });
  45288. }
  45289. };
  45290. /**
  45291. * Initializes the uniform buffer layout for the shader.
  45292. */
  45293. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45294. // Order is important !
  45295. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45296. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45297. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45298. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45299. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45300. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45301. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45302. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45303. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45304. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45305. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45306. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45307. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45308. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45309. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45310. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45311. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45312. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45313. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45314. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45315. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45316. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45317. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45318. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45319. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45320. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45321. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45322. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45323. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45324. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45325. this._uniformBuffer.addUniform("pointSize", 1);
  45326. this._uniformBuffer.create();
  45327. };
  45328. /**
  45329. * Unbinds the textures.
  45330. */
  45331. PBRBaseMaterial.prototype.unbind = function () {
  45332. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45333. this._uniformBuffer.setTexture("reflectionSampler", null);
  45334. }
  45335. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45336. this._uniformBuffer.setTexture("refractionSampler", null);
  45337. }
  45338. _super.prototype.unbind.call(this);
  45339. };
  45340. /**
  45341. * Binds the submesh data.
  45342. * @param world - The world matrix.
  45343. * @param mesh - The BJS mesh.
  45344. * @param subMesh - A submesh of the BJS mesh.
  45345. */
  45346. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45347. var scene = this.getScene();
  45348. var defines = subMesh._materialDefines;
  45349. if (!defines) {
  45350. return;
  45351. }
  45352. var effect = subMesh.effect;
  45353. if (!effect) {
  45354. return;
  45355. }
  45356. this._activeEffect = effect;
  45357. // Matrices
  45358. this.bindOnlyWorldMatrix(world);
  45359. // Normal Matrix
  45360. if (defines.OBJECTSPACE_NORMALMAP) {
  45361. world.toNormalMatrix(this._normalMatrix);
  45362. this.bindOnlyNormalMatrix(this._normalMatrix);
  45363. }
  45364. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45365. // Bones
  45366. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45367. var reflectionTexture = null;
  45368. if (mustRebind) {
  45369. this._uniformBuffer.bindToEffect(effect, "Material");
  45370. this.bindViewProjection(effect);
  45371. reflectionTexture = this._getReflectionTexture();
  45372. var refractionTexture = this._getRefractionTexture();
  45373. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45374. // Texture uniforms
  45375. if (scene.texturesEnabled) {
  45376. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45377. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45378. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45379. }
  45380. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45381. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45382. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45383. }
  45384. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45385. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45386. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45387. }
  45388. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45389. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45390. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45391. if (reflectionTexture.boundingBoxSize) {
  45392. var cubeTexture = reflectionTexture;
  45393. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45394. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45395. }
  45396. var polynomials = reflectionTexture.sphericalPolynomial;
  45397. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45398. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45399. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45400. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45401. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45402. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45403. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45404. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45405. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45406. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45407. }
  45408. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45409. }
  45410. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45411. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45412. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45413. }
  45414. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45415. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45416. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45417. }
  45418. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45419. if (this._metallicTexture) {
  45420. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45421. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45422. }
  45423. else if (this._reflectivityTexture) {
  45424. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45425. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45426. }
  45427. if (this._microSurfaceTexture) {
  45428. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45429. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45430. }
  45431. }
  45432. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45433. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45434. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45435. if (scene._mirroredCameraPosition) {
  45436. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45437. }
  45438. else {
  45439. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45440. }
  45441. }
  45442. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45443. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45444. var depth = 1.0;
  45445. if (!refractionTexture.isCube) {
  45446. if (refractionTexture.depth) {
  45447. depth = refractionTexture.depth;
  45448. }
  45449. }
  45450. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45451. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45452. }
  45453. }
  45454. // Point size
  45455. if (this.pointsCloud) {
  45456. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45457. }
  45458. // Colors
  45459. if (defines.METALLICWORKFLOW) {
  45460. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45461. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45462. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45463. }
  45464. else {
  45465. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45466. }
  45467. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45468. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45469. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45470. // Misc
  45471. this._lightingInfos.x = this._directIntensity;
  45472. this._lightingInfos.y = this._emissiveIntensity;
  45473. this._lightingInfos.z = this._environmentIntensity;
  45474. this._lightingInfos.w = this._specularIntensity;
  45475. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45476. }
  45477. // Textures
  45478. if (scene.texturesEnabled) {
  45479. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45480. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45481. }
  45482. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45483. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45484. }
  45485. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45486. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45487. }
  45488. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45489. if (defines.LODBASEDMICROSFURACE) {
  45490. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45491. }
  45492. else {
  45493. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45494. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45495. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45496. }
  45497. }
  45498. if (defines.ENVIRONMENTBRDF) {
  45499. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45500. }
  45501. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45502. if (defines.LODBASEDMICROSFURACE) {
  45503. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45504. }
  45505. else {
  45506. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45507. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45508. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45509. }
  45510. }
  45511. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45512. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45513. }
  45514. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45515. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45516. }
  45517. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45518. if (this._metallicTexture) {
  45519. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45520. }
  45521. else if (this._reflectivityTexture) {
  45522. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45523. }
  45524. if (this._microSurfaceTexture) {
  45525. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45526. }
  45527. }
  45528. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45529. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45530. }
  45531. }
  45532. // Clip plane
  45533. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45534. // Colors
  45535. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45536. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45537. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45538. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45539. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45540. }
  45541. if (mustRebind || !this.isFrozen) {
  45542. // Lights
  45543. if (scene.lightsEnabled && !this._disableLighting) {
  45544. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45545. }
  45546. // View
  45547. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45548. this.bindView(effect);
  45549. }
  45550. // Fog
  45551. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45552. // Morph targets
  45553. if (defines.NUM_MORPH_INFLUENCERS) {
  45554. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45555. }
  45556. // image processing
  45557. this._imageProcessingConfiguration.bind(this._activeEffect);
  45558. // Log. depth
  45559. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45560. }
  45561. this._uniformBuffer.update();
  45562. this._afterBind(mesh, this._activeEffect);
  45563. };
  45564. /**
  45565. * Returns the animatable textures.
  45566. * @returns - Array of animatable textures.
  45567. */
  45568. PBRBaseMaterial.prototype.getAnimatables = function () {
  45569. var results = [];
  45570. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45571. results.push(this._albedoTexture);
  45572. }
  45573. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45574. results.push(this._ambientTexture);
  45575. }
  45576. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45577. results.push(this._opacityTexture);
  45578. }
  45579. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45580. results.push(this._reflectionTexture);
  45581. }
  45582. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45583. results.push(this._emissiveTexture);
  45584. }
  45585. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45586. results.push(this._metallicTexture);
  45587. }
  45588. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45589. results.push(this._reflectivityTexture);
  45590. }
  45591. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45592. results.push(this._bumpTexture);
  45593. }
  45594. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45595. results.push(this._lightmapTexture);
  45596. }
  45597. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45598. results.push(this._refractionTexture);
  45599. }
  45600. return results;
  45601. };
  45602. /**
  45603. * Returns the texture used for reflections.
  45604. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45605. */
  45606. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45607. if (this._reflectionTexture) {
  45608. return this._reflectionTexture;
  45609. }
  45610. return this.getScene().environmentTexture;
  45611. };
  45612. /**
  45613. * Returns the texture used for refraction or null if none is used.
  45614. * @returns - Refection texture if present. If no refraction texture and refraction
  45615. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45616. */
  45617. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45618. if (this._refractionTexture) {
  45619. return this._refractionTexture;
  45620. }
  45621. if (this._linkRefractionWithTransparency) {
  45622. return this.getScene().environmentTexture;
  45623. }
  45624. return null;
  45625. };
  45626. /**
  45627. * Disposes the resources of the material.
  45628. * @param forceDisposeEffect - Forces the disposal of effects.
  45629. * @param forceDisposeTextures - Forces the disposal of all textures.
  45630. */
  45631. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45632. if (forceDisposeTextures) {
  45633. if (this._albedoTexture) {
  45634. this._albedoTexture.dispose();
  45635. }
  45636. if (this._ambientTexture) {
  45637. this._ambientTexture.dispose();
  45638. }
  45639. if (this._opacityTexture) {
  45640. this._opacityTexture.dispose();
  45641. }
  45642. if (this._reflectionTexture) {
  45643. this._reflectionTexture.dispose();
  45644. }
  45645. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45646. this._environmentBRDFTexture.dispose();
  45647. }
  45648. if (this._emissiveTexture) {
  45649. this._emissiveTexture.dispose();
  45650. }
  45651. if (this._metallicTexture) {
  45652. this._metallicTexture.dispose();
  45653. }
  45654. if (this._reflectivityTexture) {
  45655. this._reflectivityTexture.dispose();
  45656. }
  45657. if (this._bumpTexture) {
  45658. this._bumpTexture.dispose();
  45659. }
  45660. if (this._lightmapTexture) {
  45661. this._lightmapTexture.dispose();
  45662. }
  45663. if (this._refractionTexture) {
  45664. this._refractionTexture.dispose();
  45665. }
  45666. }
  45667. this._renderTargets.dispose();
  45668. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45669. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45670. }
  45671. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45672. };
  45673. /**
  45674. * Stores the reflectivity values based on metallic roughness workflow.
  45675. */
  45676. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45677. __decorate([
  45678. BABYLON.serializeAsImageProcessingConfiguration()
  45679. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45680. __decorate([
  45681. BABYLON.serialize()
  45682. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45683. __decorate([
  45684. BABYLON.serialize()
  45685. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45686. return PBRBaseMaterial;
  45687. }(BABYLON.PushMaterial));
  45688. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45689. })(BABYLON || (BABYLON = {}));
  45690. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45691. var BABYLON;
  45692. (function (BABYLON) {
  45693. /**
  45694. * The Physically based simple base material of BJS.
  45695. *
  45696. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45697. * It is used as the base class for both the specGloss and metalRough conventions.
  45698. */
  45699. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45700. __extends(PBRBaseSimpleMaterial, _super);
  45701. /**
  45702. * Instantiates a new PBRMaterial instance.
  45703. *
  45704. * @param name The material name
  45705. * @param scene The scene the material will be use in.
  45706. */
  45707. function PBRBaseSimpleMaterial(name, scene) {
  45708. var _this = _super.call(this, name, scene) || this;
  45709. /**
  45710. * Number of Simultaneous lights allowed on the material.
  45711. */
  45712. _this.maxSimultaneousLights = 4;
  45713. /**
  45714. * If sets to true, disables all the lights affecting the material.
  45715. */
  45716. _this.disableLighting = false;
  45717. /**
  45718. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45719. */
  45720. _this.invertNormalMapX = false;
  45721. /**
  45722. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45723. */
  45724. _this.invertNormalMapY = false;
  45725. /**
  45726. * Emissivie color used to self-illuminate the model.
  45727. */
  45728. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45729. /**
  45730. * Occlusion Channel Strenght.
  45731. */
  45732. _this.occlusionStrength = 1.0;
  45733. _this.useLightmapAsShadowmap = false;
  45734. _this._useAlphaFromAlbedoTexture = true;
  45735. _this._useAmbientInGrayScale = true;
  45736. return _this;
  45737. }
  45738. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45739. /**
  45740. * Gets the current double sided mode.
  45741. */
  45742. get: function () {
  45743. return this._twoSidedLighting;
  45744. },
  45745. /**
  45746. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45747. */
  45748. set: function (value) {
  45749. if (this._twoSidedLighting === value) {
  45750. return;
  45751. }
  45752. this._twoSidedLighting = value;
  45753. this.backFaceCulling = !value;
  45754. this._markAllSubMeshesAsTexturesDirty();
  45755. },
  45756. enumerable: true,
  45757. configurable: true
  45758. });
  45759. /**
  45760. * Return the active textures of the material.
  45761. */
  45762. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45763. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45764. if (this.environmentTexture) {
  45765. activeTextures.push(this.environmentTexture);
  45766. }
  45767. if (this.normalTexture) {
  45768. activeTextures.push(this.normalTexture);
  45769. }
  45770. if (this.emissiveTexture) {
  45771. activeTextures.push(this.emissiveTexture);
  45772. }
  45773. if (this.occlusionTexture) {
  45774. activeTextures.push(this.occlusionTexture);
  45775. }
  45776. if (this.lightmapTexture) {
  45777. activeTextures.push(this.lightmapTexture);
  45778. }
  45779. return activeTextures;
  45780. };
  45781. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45782. if (_super.prototype.hasTexture.call(this, texture)) {
  45783. return true;
  45784. }
  45785. if (this.lightmapTexture === texture) {
  45786. return true;
  45787. }
  45788. return false;
  45789. };
  45790. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45791. return "PBRBaseSimpleMaterial";
  45792. };
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45796. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45800. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45801. __decorate([
  45802. BABYLON.serializeAsTexture(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45804. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45805. __decorate([
  45806. BABYLON.serialize(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45809. __decorate([
  45810. BABYLON.serialize(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsTexture(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45816. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45817. __decorate([
  45818. BABYLON.serializeAsColor3("emissive"),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45821. __decorate([
  45822. BABYLON.serializeAsTexture(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45824. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45825. __decorate([
  45826. BABYLON.serialize(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45828. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45832. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serialize(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45836. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45837. __decorate([
  45838. BABYLON.serialize()
  45839. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45840. __decorate([
  45841. BABYLON.serializeAsTexture(),
  45842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45843. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45844. __decorate([
  45845. BABYLON.serialize(),
  45846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45847. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45848. return PBRBaseSimpleMaterial;
  45849. }(BABYLON.PBRBaseMaterial));
  45850. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45851. })(BABYLON || (BABYLON = {}));
  45852. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45853. var BABYLON;
  45854. (function (BABYLON) {
  45855. /**
  45856. * The Physically based material of BJS.
  45857. *
  45858. * This offers the main features of a standard PBR material.
  45859. * For more information, please refer to the documentation :
  45860. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45861. */
  45862. var PBRMaterial = /** @class */ (function (_super) {
  45863. __extends(PBRMaterial, _super);
  45864. /**
  45865. * Instantiates a new PBRMaterial instance.
  45866. *
  45867. * @param name The material name
  45868. * @param scene The scene the material will be use in.
  45869. */
  45870. function PBRMaterial(name, scene) {
  45871. var _this = _super.call(this, name, scene) || this;
  45872. /**
  45873. * Intensity of the direct lights e.g. the four lights available in your scene.
  45874. * This impacts both the direct diffuse and specular highlights.
  45875. */
  45876. _this.directIntensity = 1.0;
  45877. /**
  45878. * Intensity of the emissive part of the material.
  45879. * This helps controlling the emissive effect without modifying the emissive color.
  45880. */
  45881. _this.emissiveIntensity = 1.0;
  45882. /**
  45883. * Intensity of the environment e.g. how much the environment will light the object
  45884. * either through harmonics for rough material or through the refelction for shiny ones.
  45885. */
  45886. _this.environmentIntensity = 1.0;
  45887. /**
  45888. * This is a special control allowing the reduction of the specular highlights coming from the
  45889. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45890. */
  45891. _this.specularIntensity = 1.0;
  45892. /**
  45893. * Debug Control allowing disabling the bump map on this material.
  45894. */
  45895. _this.disableBumpMap = false;
  45896. /**
  45897. * AKA Occlusion Texture Intensity in other nomenclature.
  45898. */
  45899. _this.ambientTextureStrength = 1.0;
  45900. /**
  45901. * The color of a material in ambient lighting.
  45902. */
  45903. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45904. /**
  45905. * AKA Diffuse Color in other nomenclature.
  45906. */
  45907. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45908. /**
  45909. * AKA Specular Color in other nomenclature.
  45910. */
  45911. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45912. /**
  45913. * The color reflected from the material.
  45914. */
  45915. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45916. /**
  45917. * The color emitted from the material.
  45918. */
  45919. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45920. /**
  45921. * AKA Glossiness in other nomenclature.
  45922. */
  45923. _this.microSurface = 1.0;
  45924. /**
  45925. * source material index of refraction (IOR)' / 'destination material IOR.
  45926. */
  45927. _this.indexOfRefraction = 0.66;
  45928. /**
  45929. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45930. */
  45931. _this.invertRefractionY = false;
  45932. /**
  45933. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45934. * Materials half opaque for instance using refraction could benefit from this control.
  45935. */
  45936. _this.linkRefractionWithTransparency = false;
  45937. _this.useLightmapAsShadowmap = false;
  45938. /**
  45939. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45940. */
  45941. _this.useAlphaFromAlbedoTexture = false;
  45942. /**
  45943. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45944. */
  45945. _this.forceAlphaTest = false;
  45946. /**
  45947. * Defines the alpha limits in alpha test mode.
  45948. */
  45949. _this.alphaCutOff = 0.4;
  45950. /**
  45951. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45952. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45953. */
  45954. _this.useSpecularOverAlpha = true;
  45955. /**
  45956. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45957. */
  45958. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45959. /**
  45960. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45961. */
  45962. _this.useRoughnessFromMetallicTextureAlpha = true;
  45963. /**
  45964. * Specifies if the metallic texture contains the roughness information in its green channel.
  45965. */
  45966. _this.useRoughnessFromMetallicTextureGreen = false;
  45967. /**
  45968. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45969. */
  45970. _this.useMetallnessFromMetallicTextureBlue = false;
  45971. /**
  45972. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45973. */
  45974. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45975. /**
  45976. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45977. */
  45978. _this.useAmbientInGrayScale = false;
  45979. /**
  45980. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45981. * The material will try to infer what glossiness each pixel should be.
  45982. */
  45983. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45984. /**
  45985. * BJS is using an harcoded light falloff based on a manually sets up range.
  45986. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45987. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45988. */
  45989. _this.usePhysicalLightFalloff = true;
  45990. /**
  45991. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45992. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45993. */
  45994. _this.useRadianceOverAlpha = true;
  45995. /**
  45996. * Allows using an object space normal map (instead of tangent space).
  45997. */
  45998. _this.useObjectSpaceNormalMap = false;
  45999. /**
  46000. * Allows using the bump map in parallax mode.
  46001. */
  46002. _this.useParallax = false;
  46003. /**
  46004. * Allows using the bump map in parallax occlusion mode.
  46005. */
  46006. _this.useParallaxOcclusion = false;
  46007. /**
  46008. * Controls the scale bias of the parallax mode.
  46009. */
  46010. _this.parallaxScaleBias = 0.05;
  46011. /**
  46012. * If sets to true, disables all the lights affecting the material.
  46013. */
  46014. _this.disableLighting = false;
  46015. /**
  46016. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46017. */
  46018. _this.forceIrradianceInFragment = false;
  46019. /**
  46020. * Number of Simultaneous lights allowed on the material.
  46021. */
  46022. _this.maxSimultaneousLights = 4;
  46023. /**
  46024. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46025. */
  46026. _this.invertNormalMapX = false;
  46027. /**
  46028. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46029. */
  46030. _this.invertNormalMapY = false;
  46031. /**
  46032. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46033. */
  46034. _this.twoSidedLighting = false;
  46035. /**
  46036. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46037. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46038. */
  46039. _this.useAlphaFresnel = false;
  46040. /**
  46041. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46042. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46043. */
  46044. _this.useLinearAlphaFresnel = false;
  46045. /**
  46046. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46047. * And/Or occlude the blended part.
  46048. */
  46049. _this.environmentBRDFTexture = null;
  46050. /**
  46051. * Force normal to face away from face.
  46052. */
  46053. _this.forceNormalForward = false;
  46054. /**
  46055. * Enables specular anti aliasing in the PBR shader.
  46056. * It will both interacts on the Geometry for analytical and IBL lighting.
  46057. * It also prefilter the roughness map based on the bump values.
  46058. */
  46059. _this.enableSpecularAntiAliasing = false;
  46060. /**
  46061. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46062. * makes the reflect vector face the model (under horizon).
  46063. */
  46064. _this.useHorizonOcclusion = true;
  46065. /**
  46066. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46067. * too much the area relying on ambient texture to define their ambient occlusion.
  46068. */
  46069. _this.useRadianceOcclusion = true;
  46070. /**
  46071. * If set to true, no lighting calculations will be applied.
  46072. */
  46073. _this.unlit = false;
  46074. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46075. return _this;
  46076. }
  46077. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46078. /**
  46079. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46080. */
  46081. get: function () {
  46082. return this._PBRMATERIAL_OPAQUE;
  46083. },
  46084. enumerable: true,
  46085. configurable: true
  46086. });
  46087. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46088. /**
  46089. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46090. */
  46091. get: function () {
  46092. return this._PBRMATERIAL_ALPHATEST;
  46093. },
  46094. enumerable: true,
  46095. configurable: true
  46096. });
  46097. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46098. /**
  46099. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46100. */
  46101. get: function () {
  46102. return this._PBRMATERIAL_ALPHABLEND;
  46103. },
  46104. enumerable: true,
  46105. configurable: true
  46106. });
  46107. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46108. /**
  46109. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46110. * They are also discarded below the alpha cutoff threshold to improve performances.
  46111. */
  46112. get: function () {
  46113. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46114. },
  46115. enumerable: true,
  46116. configurable: true
  46117. });
  46118. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46119. /**
  46120. * Gets the image processing configuration used either in this material.
  46121. */
  46122. get: function () {
  46123. return this._imageProcessingConfiguration;
  46124. },
  46125. /**
  46126. * Sets the Default image processing configuration used either in the this material.
  46127. *
  46128. * If sets to null, the scene one is in use.
  46129. */
  46130. set: function (value) {
  46131. this._attachImageProcessingConfiguration(value);
  46132. // Ensure the effect will be rebuilt.
  46133. this._markAllSubMeshesAsTexturesDirty();
  46134. },
  46135. enumerable: true,
  46136. configurable: true
  46137. });
  46138. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46139. /**
  46140. * Gets wether the color curves effect is enabled.
  46141. */
  46142. get: function () {
  46143. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46144. },
  46145. /**
  46146. * Sets wether the color curves effect is enabled.
  46147. */
  46148. set: function (value) {
  46149. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46150. },
  46151. enumerable: true,
  46152. configurable: true
  46153. });
  46154. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46155. /**
  46156. * Gets wether the color grading effect is enabled.
  46157. */
  46158. get: function () {
  46159. return this.imageProcessingConfiguration.colorGradingEnabled;
  46160. },
  46161. /**
  46162. * Gets wether the color grading effect is enabled.
  46163. */
  46164. set: function (value) {
  46165. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46166. },
  46167. enumerable: true,
  46168. configurable: true
  46169. });
  46170. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46171. /**
  46172. * Gets wether tonemapping is enabled or not.
  46173. */
  46174. get: function () {
  46175. return this._imageProcessingConfiguration.toneMappingEnabled;
  46176. },
  46177. /**
  46178. * Sets wether tonemapping is enabled or not
  46179. */
  46180. set: function (value) {
  46181. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46182. },
  46183. enumerable: true,
  46184. configurable: true
  46185. });
  46186. ;
  46187. ;
  46188. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46189. /**
  46190. * The camera exposure used on this material.
  46191. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46192. * This corresponds to a photographic exposure.
  46193. */
  46194. get: function () {
  46195. return this._imageProcessingConfiguration.exposure;
  46196. },
  46197. /**
  46198. * The camera exposure used on this material.
  46199. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46200. * This corresponds to a photographic exposure.
  46201. */
  46202. set: function (value) {
  46203. this._imageProcessingConfiguration.exposure = value;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. ;
  46209. ;
  46210. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46211. /**
  46212. * Gets The camera contrast used on this material.
  46213. */
  46214. get: function () {
  46215. return this._imageProcessingConfiguration.contrast;
  46216. },
  46217. /**
  46218. * Sets The camera contrast used on this material.
  46219. */
  46220. set: function (value) {
  46221. this._imageProcessingConfiguration.contrast = value;
  46222. },
  46223. enumerable: true,
  46224. configurable: true
  46225. });
  46226. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46227. /**
  46228. * Gets the Color Grading 2D Lookup Texture.
  46229. */
  46230. get: function () {
  46231. return this._imageProcessingConfiguration.colorGradingTexture;
  46232. },
  46233. /**
  46234. * Sets the Color Grading 2D Lookup Texture.
  46235. */
  46236. set: function (value) {
  46237. this._imageProcessingConfiguration.colorGradingTexture = value;
  46238. },
  46239. enumerable: true,
  46240. configurable: true
  46241. });
  46242. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46243. /**
  46244. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46245. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46246. * 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;
  46247. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46248. */
  46249. get: function () {
  46250. return this._imageProcessingConfiguration.colorCurves;
  46251. },
  46252. /**
  46253. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46254. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46255. * 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;
  46256. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46257. */
  46258. set: function (value) {
  46259. this._imageProcessingConfiguration.colorCurves = value;
  46260. },
  46261. enumerable: true,
  46262. configurable: true
  46263. });
  46264. /**
  46265. * Returns the name of this material class.
  46266. */
  46267. PBRMaterial.prototype.getClassName = function () {
  46268. return "PBRMaterial";
  46269. };
  46270. /**
  46271. * Returns an array of the actively used textures.
  46272. * @returns - Array of BaseTextures
  46273. */
  46274. PBRMaterial.prototype.getActiveTextures = function () {
  46275. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46276. if (this._albedoTexture) {
  46277. activeTextures.push(this._albedoTexture);
  46278. }
  46279. if (this._ambientTexture) {
  46280. activeTextures.push(this._ambientTexture);
  46281. }
  46282. if (this._opacityTexture) {
  46283. activeTextures.push(this._opacityTexture);
  46284. }
  46285. if (this._reflectionTexture) {
  46286. activeTextures.push(this._reflectionTexture);
  46287. }
  46288. if (this._emissiveTexture) {
  46289. activeTextures.push(this._emissiveTexture);
  46290. }
  46291. if (this._reflectivityTexture) {
  46292. activeTextures.push(this._reflectivityTexture);
  46293. }
  46294. if (this._metallicTexture) {
  46295. activeTextures.push(this._metallicTexture);
  46296. }
  46297. if (this._microSurfaceTexture) {
  46298. activeTextures.push(this._microSurfaceTexture);
  46299. }
  46300. if (this._bumpTexture) {
  46301. activeTextures.push(this._bumpTexture);
  46302. }
  46303. if (this._lightmapTexture) {
  46304. activeTextures.push(this._lightmapTexture);
  46305. }
  46306. if (this._refractionTexture) {
  46307. activeTextures.push(this._refractionTexture);
  46308. }
  46309. return activeTextures;
  46310. };
  46311. /**
  46312. * Checks to see if a texture is used in the material.
  46313. * @param texture - Base texture to use.
  46314. * @returns - Boolean specifying if a texture is used in the material.
  46315. */
  46316. PBRMaterial.prototype.hasTexture = function (texture) {
  46317. if (_super.prototype.hasTexture.call(this, texture)) {
  46318. return true;
  46319. }
  46320. if (this._albedoTexture === texture) {
  46321. return true;
  46322. }
  46323. if (this._ambientTexture === texture) {
  46324. return true;
  46325. }
  46326. if (this._opacityTexture === texture) {
  46327. return true;
  46328. }
  46329. if (this._reflectionTexture === texture) {
  46330. return true;
  46331. }
  46332. if (this._reflectivityTexture === texture) {
  46333. return true;
  46334. }
  46335. if (this._metallicTexture === texture) {
  46336. return true;
  46337. }
  46338. if (this._microSurfaceTexture === texture) {
  46339. return true;
  46340. }
  46341. if (this._bumpTexture === texture) {
  46342. return true;
  46343. }
  46344. if (this._lightmapTexture === texture) {
  46345. return true;
  46346. }
  46347. if (this._refractionTexture === texture) {
  46348. return true;
  46349. }
  46350. return false;
  46351. };
  46352. /**
  46353. * Makes a duplicate of the current material.
  46354. * @param name - name to use for the new material.
  46355. */
  46356. PBRMaterial.prototype.clone = function (name) {
  46357. var _this = this;
  46358. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46359. clone.id = name;
  46360. clone.name = name;
  46361. return clone;
  46362. };
  46363. /**
  46364. * Serializes this PBR Material.
  46365. * @returns - An object with the serialized material.
  46366. */
  46367. PBRMaterial.prototype.serialize = function () {
  46368. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46369. serializationObject.customType = "BABYLON.PBRMaterial";
  46370. return serializationObject;
  46371. };
  46372. // Statics
  46373. /**
  46374. * Parses a PBR Material from a serialized object.
  46375. * @param source - Serialized object.
  46376. * @param scene - BJS scene instance.
  46377. * @param rootUrl - url for the scene object
  46378. * @returns - PBRMaterial
  46379. */
  46380. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46381. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46382. };
  46383. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46384. /**
  46385. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46386. */
  46387. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46388. /**
  46389. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46390. */
  46391. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46392. /**
  46393. * 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.
  46394. * They are also discarded below the alpha cutoff threshold to improve performances.
  46395. */
  46396. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46397. __decorate([
  46398. BABYLON.serialize(),
  46399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46400. ], PBRMaterial.prototype, "directIntensity", void 0);
  46401. __decorate([
  46402. BABYLON.serialize(),
  46403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46404. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46405. __decorate([
  46406. BABYLON.serialize(),
  46407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46408. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46409. __decorate([
  46410. BABYLON.serialize(),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46412. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46413. __decorate([
  46414. BABYLON.serialize(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46416. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46417. __decorate([
  46418. BABYLON.serializeAsTexture(),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46420. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46421. __decorate([
  46422. BABYLON.serializeAsTexture(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46424. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46425. __decorate([
  46426. BABYLON.serialize(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46428. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46429. __decorate([
  46430. BABYLON.serializeAsTexture(),
  46431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46432. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46433. __decorate([
  46434. BABYLON.serializeAsTexture(),
  46435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46436. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46437. __decorate([
  46438. BABYLON.serializeAsTexture(),
  46439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46440. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46441. __decorate([
  46442. BABYLON.serializeAsTexture(),
  46443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46444. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46445. __decorate([
  46446. BABYLON.serializeAsTexture(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46449. __decorate([
  46450. BABYLON.serialize(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46452. ], PBRMaterial.prototype, "metallic", void 0);
  46453. __decorate([
  46454. BABYLON.serialize(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "roughness", void 0);
  46457. __decorate([
  46458. BABYLON.serializeAsTexture(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46460. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46461. __decorate([
  46462. BABYLON.serializeAsTexture(),
  46463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46464. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46465. __decorate([
  46466. BABYLON.serializeAsTexture(),
  46467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46468. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46469. __decorate([
  46470. BABYLON.serializeAsTexture(),
  46471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46472. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46473. __decorate([
  46474. BABYLON.serializeAsColor3("ambient"),
  46475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46476. ], PBRMaterial.prototype, "ambientColor", void 0);
  46477. __decorate([
  46478. BABYLON.serializeAsColor3("albedo"),
  46479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46480. ], PBRMaterial.prototype, "albedoColor", void 0);
  46481. __decorate([
  46482. BABYLON.serializeAsColor3("reflectivity"),
  46483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46484. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46485. __decorate([
  46486. BABYLON.serializeAsColor3("reflection"),
  46487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46488. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46489. __decorate([
  46490. BABYLON.serializeAsColor3("emissive"),
  46491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46492. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46493. __decorate([
  46494. BABYLON.serialize(),
  46495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46496. ], PBRMaterial.prototype, "microSurface", void 0);
  46497. __decorate([
  46498. BABYLON.serialize(),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46500. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46504. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46505. __decorate([
  46506. BABYLON.serialize(),
  46507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46508. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46509. __decorate([
  46510. BABYLON.serialize(),
  46511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46512. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46513. __decorate([
  46514. BABYLON.serialize(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46516. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46517. __decorate([
  46518. BABYLON.serialize(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46520. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46521. __decorate([
  46522. BABYLON.serialize(),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46524. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46525. __decorate([
  46526. BABYLON.serialize(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46528. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46529. __decorate([
  46530. BABYLON.serialize(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46532. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46533. __decorate([
  46534. BABYLON.serialize(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46537. __decorate([
  46538. BABYLON.serialize(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46541. __decorate([
  46542. BABYLON.serialize(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46544. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46545. __decorate([
  46546. BABYLON.serialize(),
  46547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46548. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46549. __decorate([
  46550. BABYLON.serialize(),
  46551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46552. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46553. __decorate([
  46554. BABYLON.serialize(),
  46555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46556. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46557. __decorate([
  46558. BABYLON.serialize(),
  46559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46560. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46561. __decorate([
  46562. BABYLON.serialize(),
  46563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46564. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46565. __decorate([
  46566. BABYLON.serialize(),
  46567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46568. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46569. __decorate([
  46570. BABYLON.serialize(),
  46571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46572. ], PBRMaterial.prototype, "useParallax", void 0);
  46573. __decorate([
  46574. BABYLON.serialize(),
  46575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46576. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46577. __decorate([
  46578. BABYLON.serialize(),
  46579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46580. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46581. __decorate([
  46582. BABYLON.serialize(),
  46583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46584. ], PBRMaterial.prototype, "disableLighting", void 0);
  46585. __decorate([
  46586. BABYLON.serialize(),
  46587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46588. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46589. __decorate([
  46590. BABYLON.serialize(),
  46591. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46592. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46593. __decorate([
  46594. BABYLON.serialize(),
  46595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46596. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46597. __decorate([
  46598. BABYLON.serialize(),
  46599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46600. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46601. __decorate([
  46602. BABYLON.serialize(),
  46603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46604. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46605. __decorate([
  46606. BABYLON.serialize(),
  46607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46608. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46609. __decorate([
  46610. BABYLON.serialize(),
  46611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46612. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46613. __decorate([
  46614. BABYLON.serializeAsTexture(),
  46615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46616. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46617. __decorate([
  46618. BABYLON.serialize(),
  46619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46620. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46621. __decorate([
  46622. BABYLON.serialize(),
  46623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46624. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46625. __decorate([
  46626. BABYLON.serialize(),
  46627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46628. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46629. __decorate([
  46630. BABYLON.serialize(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46632. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46633. __decorate([
  46634. BABYLON.serialize(),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46636. ], PBRMaterial.prototype, "unlit", void 0);
  46637. return PBRMaterial;
  46638. }(BABYLON.PBRBaseMaterial));
  46639. BABYLON.PBRMaterial = PBRMaterial;
  46640. })(BABYLON || (BABYLON = {}));
  46641. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46642. var BABYLON;
  46643. (function (BABYLON) {
  46644. /**
  46645. * The PBR material of BJS following the metal roughness convention.
  46646. *
  46647. * This fits to the PBR convention in the GLTF definition:
  46648. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46649. */
  46650. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46651. __extends(PBRMetallicRoughnessMaterial, _super);
  46652. /**
  46653. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46654. *
  46655. * @param name The material name
  46656. * @param scene The scene the material will be use in.
  46657. */
  46658. function PBRMetallicRoughnessMaterial(name, scene) {
  46659. var _this = _super.call(this, name, scene) || this;
  46660. _this._useRoughnessFromMetallicTextureAlpha = false;
  46661. _this._useRoughnessFromMetallicTextureGreen = true;
  46662. _this._useMetallnessFromMetallicTextureBlue = true;
  46663. _this.metallic = 1.0;
  46664. _this.roughness = 1.0;
  46665. return _this;
  46666. }
  46667. /**
  46668. * Return the currrent class name of the material.
  46669. */
  46670. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46671. return "PBRMetallicRoughnessMaterial";
  46672. };
  46673. /**
  46674. * Return the active textures of the material.
  46675. */
  46676. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46677. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46678. if (this.baseTexture) {
  46679. activeTextures.push(this.baseTexture);
  46680. }
  46681. if (this.metallicRoughnessTexture) {
  46682. activeTextures.push(this.metallicRoughnessTexture);
  46683. }
  46684. return activeTextures;
  46685. };
  46686. /**
  46687. * Checks to see if a texture is used in the material.
  46688. * @param texture - Base texture to use.
  46689. * @returns - Boolean specifying if a texture is used in the material.
  46690. */
  46691. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46692. if (_super.prototype.hasTexture.call(this, texture)) {
  46693. return true;
  46694. }
  46695. if (this.baseTexture === texture) {
  46696. return true;
  46697. }
  46698. if (this.metallicRoughnessTexture === texture) {
  46699. return true;
  46700. }
  46701. return false;
  46702. };
  46703. /**
  46704. * Makes a duplicate of the current material.
  46705. * @param name - name to use for the new material.
  46706. */
  46707. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46708. var _this = this;
  46709. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46710. clone.id = name;
  46711. clone.name = name;
  46712. return clone;
  46713. };
  46714. /**
  46715. * Serialize the material to a parsable JSON object.
  46716. */
  46717. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46719. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46720. return serializationObject;
  46721. };
  46722. /**
  46723. * Parses a JSON object correponding to the serialize function.
  46724. */
  46725. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46726. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46727. };
  46728. __decorate([
  46729. BABYLON.serializeAsColor3(),
  46730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46731. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46732. __decorate([
  46733. BABYLON.serializeAsTexture(),
  46734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46735. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46736. __decorate([
  46737. BABYLON.serialize(),
  46738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46739. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46740. __decorate([
  46741. BABYLON.serialize(),
  46742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46743. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46744. __decorate([
  46745. BABYLON.serializeAsTexture(),
  46746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46747. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46748. return PBRMetallicRoughnessMaterial;
  46749. }(BABYLON.PBRBaseSimpleMaterial));
  46750. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46751. })(BABYLON || (BABYLON = {}));
  46752. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46753. var BABYLON;
  46754. (function (BABYLON) {
  46755. /**
  46756. * The PBR material of BJS following the specular glossiness convention.
  46757. *
  46758. * This fits to the PBR convention in the GLTF definition:
  46759. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46760. */
  46761. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46762. __extends(PBRSpecularGlossinessMaterial, _super);
  46763. /**
  46764. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46765. *
  46766. * @param name The material name
  46767. * @param scene The scene the material will be use in.
  46768. */
  46769. function PBRSpecularGlossinessMaterial(name, scene) {
  46770. var _this = _super.call(this, name, scene) || this;
  46771. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46772. return _this;
  46773. }
  46774. /**
  46775. * Return the currrent class name of the material.
  46776. */
  46777. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46778. return "PBRSpecularGlossinessMaterial";
  46779. };
  46780. /**
  46781. * Return the active textures of the material.
  46782. */
  46783. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46784. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46785. if (this.diffuseTexture) {
  46786. activeTextures.push(this.diffuseTexture);
  46787. }
  46788. if (this.specularGlossinessTexture) {
  46789. activeTextures.push(this.specularGlossinessTexture);
  46790. }
  46791. return activeTextures;
  46792. };
  46793. /**
  46794. * Checks to see if a texture is used in the material.
  46795. * @param texture - Base texture to use.
  46796. * @returns - Boolean specifying if a texture is used in the material.
  46797. */
  46798. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46799. if (_super.prototype.hasTexture.call(this, texture)) {
  46800. return true;
  46801. }
  46802. if (this.diffuseTexture === texture) {
  46803. return true;
  46804. }
  46805. if (this.specularGlossinessTexture === texture) {
  46806. return true;
  46807. }
  46808. return false;
  46809. };
  46810. /**
  46811. * Makes a duplicate of the current material.
  46812. * @param name - name to use for the new material.
  46813. */
  46814. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46815. var _this = this;
  46816. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46817. clone.id = name;
  46818. clone.name = name;
  46819. return clone;
  46820. };
  46821. /**
  46822. * Serialize the material to a parsable JSON object.
  46823. */
  46824. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46826. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46827. return serializationObject;
  46828. };
  46829. /**
  46830. * Parses a JSON object correponding to the serialize function.
  46831. */
  46832. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46833. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46834. };
  46835. __decorate([
  46836. BABYLON.serializeAsColor3("diffuse"),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46838. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46839. __decorate([
  46840. BABYLON.serializeAsTexture(),
  46841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46842. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46843. __decorate([
  46844. BABYLON.serializeAsColor3("specular"),
  46845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46846. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46847. __decorate([
  46848. BABYLON.serialize(),
  46849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46850. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46851. __decorate([
  46852. BABYLON.serializeAsTexture(),
  46853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46854. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46855. return PBRSpecularGlossinessMaterial;
  46856. }(BABYLON.PBRBaseSimpleMaterial));
  46857. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46858. })(BABYLON || (BABYLON = {}));
  46859. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46860. var BABYLON;
  46861. (function (BABYLON) {
  46862. BABYLON.CameraInputTypes = {};
  46863. var CameraInputsManager = /** @class */ (function () {
  46864. function CameraInputsManager(camera) {
  46865. this.attached = {};
  46866. this.camera = camera;
  46867. this.checkInputs = function () { };
  46868. }
  46869. /**
  46870. * Add an input method to a camera.
  46871. * builtin inputs example: camera.inputs.addGamepad();
  46872. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46873. * @param input camera input method
  46874. */
  46875. CameraInputsManager.prototype.add = function (input) {
  46876. var type = input.getSimpleName();
  46877. if (this.attached[type]) {
  46878. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46879. return;
  46880. }
  46881. this.attached[type] = input;
  46882. input.camera = this.camera;
  46883. //for checkInputs, we are dynamically creating a function
  46884. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46885. if (input.checkInputs) {
  46886. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46887. }
  46888. if (this.attachedElement) {
  46889. input.attachControl(this.attachedElement);
  46890. }
  46891. };
  46892. /**
  46893. * Remove a specific input method from a camera
  46894. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46895. * @param inputToRemove camera input method
  46896. */
  46897. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46898. for (var cam in this.attached) {
  46899. var input = this.attached[cam];
  46900. if (input === inputToRemove) {
  46901. input.detachControl(this.attachedElement);
  46902. input.camera = null;
  46903. delete this.attached[cam];
  46904. this.rebuildInputCheck();
  46905. }
  46906. }
  46907. };
  46908. CameraInputsManager.prototype.removeByType = function (inputType) {
  46909. for (var cam in this.attached) {
  46910. var input = this.attached[cam];
  46911. if (input.getClassName() === inputType) {
  46912. input.detachControl(this.attachedElement);
  46913. input.camera = null;
  46914. delete this.attached[cam];
  46915. this.rebuildInputCheck();
  46916. }
  46917. }
  46918. };
  46919. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46920. var current = this.checkInputs;
  46921. return function () {
  46922. current();
  46923. fn();
  46924. };
  46925. };
  46926. CameraInputsManager.prototype.attachInput = function (input) {
  46927. if (this.attachedElement) {
  46928. input.attachControl(this.attachedElement, this.noPreventDefault);
  46929. }
  46930. };
  46931. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46932. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46933. if (this.attachedElement) {
  46934. return;
  46935. }
  46936. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46937. this.attachedElement = element;
  46938. this.noPreventDefault = noPreventDefault;
  46939. for (var cam in this.attached) {
  46940. this.attached[cam].attachControl(element, noPreventDefault);
  46941. }
  46942. };
  46943. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46944. if (disconnect === void 0) { disconnect = false; }
  46945. if (this.attachedElement !== element) {
  46946. return;
  46947. }
  46948. for (var cam in this.attached) {
  46949. this.attached[cam].detachControl(element);
  46950. if (disconnect) {
  46951. this.attached[cam].camera = null;
  46952. }
  46953. }
  46954. this.attachedElement = null;
  46955. };
  46956. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46957. this.checkInputs = function () { };
  46958. for (var cam in this.attached) {
  46959. var input = this.attached[cam];
  46960. if (input.checkInputs) {
  46961. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46962. }
  46963. }
  46964. };
  46965. /**
  46966. * Remove all attached input methods from a camera
  46967. */
  46968. CameraInputsManager.prototype.clear = function () {
  46969. if (this.attachedElement) {
  46970. this.detachElement(this.attachedElement, true);
  46971. }
  46972. this.attached = {};
  46973. this.attachedElement = null;
  46974. this.checkInputs = function () { };
  46975. };
  46976. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46977. var inputs = {};
  46978. for (var cam in this.attached) {
  46979. var input = this.attached[cam];
  46980. var res = BABYLON.SerializationHelper.Serialize(input);
  46981. inputs[input.getClassName()] = res;
  46982. }
  46983. serializedCamera.inputsmgr = inputs;
  46984. };
  46985. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46986. var parsedInputs = parsedCamera.inputsmgr;
  46987. if (parsedInputs) {
  46988. this.clear();
  46989. for (var n in parsedInputs) {
  46990. var construct = BABYLON.CameraInputTypes[n];
  46991. if (construct) {
  46992. var parsedinput = parsedInputs[n];
  46993. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46994. this.add(input);
  46995. }
  46996. }
  46997. }
  46998. else {
  46999. //2016-03-08 this part is for managing backward compatibility
  47000. for (var n in this.attached) {
  47001. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47002. if (construct) {
  47003. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47004. this.remove(this.attached[n]);
  47005. this.add(input);
  47006. }
  47007. }
  47008. }
  47009. };
  47010. return CameraInputsManager;
  47011. }());
  47012. BABYLON.CameraInputsManager = CameraInputsManager;
  47013. })(BABYLON || (BABYLON = {}));
  47014. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47015. var BABYLON;
  47016. (function (BABYLON) {
  47017. var TargetCamera = /** @class */ (function (_super) {
  47018. __extends(TargetCamera, _super);
  47019. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47020. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47021. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47022. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47023. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47024. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47025. _this.speed = 2.0;
  47026. _this.noRotationConstraint = false;
  47027. _this.lockedTarget = null;
  47028. _this._currentTarget = BABYLON.Vector3.Zero();
  47029. _this._viewMatrix = BABYLON.Matrix.Zero();
  47030. _this._camMatrix = BABYLON.Matrix.Zero();
  47031. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47032. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47033. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47034. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47035. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47036. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47037. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47038. return _this;
  47039. }
  47040. TargetCamera.prototype.getFrontPosition = function (distance) {
  47041. this.getWorldMatrix();
  47042. var direction = this.getTarget().subtract(this.position);
  47043. direction.normalize();
  47044. direction.scaleInPlace(distance);
  47045. return this.globalPosition.add(direction);
  47046. };
  47047. TargetCamera.prototype._getLockedTargetPosition = function () {
  47048. if (!this.lockedTarget) {
  47049. return null;
  47050. }
  47051. if (this.lockedTarget.absolutePosition) {
  47052. this.lockedTarget.computeWorldMatrix();
  47053. }
  47054. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47055. };
  47056. TargetCamera.prototype.storeState = function () {
  47057. this._storedPosition = this.position.clone();
  47058. this._storedRotation = this.rotation.clone();
  47059. if (this.rotationQuaternion) {
  47060. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47061. }
  47062. return _super.prototype.storeState.call(this);
  47063. };
  47064. /**
  47065. * Restored camera state. You must call storeState() first
  47066. */
  47067. TargetCamera.prototype._restoreStateValues = function () {
  47068. if (!_super.prototype._restoreStateValues.call(this)) {
  47069. return false;
  47070. }
  47071. this.position = this._storedPosition.clone();
  47072. this.rotation = this._storedRotation.clone();
  47073. if (this.rotationQuaternion) {
  47074. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47075. }
  47076. this.cameraDirection.copyFromFloats(0, 0, 0);
  47077. this.cameraRotation.copyFromFloats(0, 0);
  47078. return true;
  47079. };
  47080. // Cache
  47081. TargetCamera.prototype._initCache = function () {
  47082. _super.prototype._initCache.call(this);
  47083. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47084. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47085. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47086. };
  47087. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47088. if (!ignoreParentClass) {
  47089. _super.prototype._updateCache.call(this);
  47090. }
  47091. var lockedTargetPosition = this._getLockedTargetPosition();
  47092. if (!lockedTargetPosition) {
  47093. this._cache.lockedTarget = null;
  47094. }
  47095. else {
  47096. if (!this._cache.lockedTarget) {
  47097. this._cache.lockedTarget = lockedTargetPosition.clone();
  47098. }
  47099. else {
  47100. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47101. }
  47102. }
  47103. this._cache.rotation.copyFrom(this.rotation);
  47104. if (this.rotationQuaternion)
  47105. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47106. };
  47107. // Synchronized
  47108. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47109. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47110. return false;
  47111. }
  47112. var lockedTargetPosition = this._getLockedTargetPosition();
  47113. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47114. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47115. };
  47116. // Methods
  47117. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47118. var engine = this.getEngine();
  47119. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47120. };
  47121. // Target
  47122. TargetCamera.prototype.setTarget = function (target) {
  47123. this.upVector.normalize();
  47124. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47125. this._camMatrix.invert();
  47126. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47127. var vDir = target.subtract(this.position);
  47128. if (vDir.x >= 0.0) {
  47129. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47130. }
  47131. else {
  47132. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47133. }
  47134. this.rotation.z = 0;
  47135. if (isNaN(this.rotation.x)) {
  47136. this.rotation.x = 0;
  47137. }
  47138. if (isNaN(this.rotation.y)) {
  47139. this.rotation.y = 0;
  47140. }
  47141. if (isNaN(this.rotation.z)) {
  47142. this.rotation.z = 0;
  47143. }
  47144. if (this.rotationQuaternion) {
  47145. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47146. }
  47147. };
  47148. /**
  47149. * Return the current target position of the camera. This value is expressed in local space.
  47150. */
  47151. TargetCamera.prototype.getTarget = function () {
  47152. return this._currentTarget;
  47153. };
  47154. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47155. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47156. };
  47157. TargetCamera.prototype._updatePosition = function () {
  47158. if (this.parent) {
  47159. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47160. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47161. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47162. return;
  47163. }
  47164. this.position.addInPlace(this.cameraDirection);
  47165. };
  47166. TargetCamera.prototype._checkInputs = function () {
  47167. var needToMove = this._decideIfNeedsToMove();
  47168. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47169. // Move
  47170. if (needToMove) {
  47171. this._updatePosition();
  47172. }
  47173. // Rotate
  47174. if (needToRotate) {
  47175. this.rotation.x += this.cameraRotation.x;
  47176. this.rotation.y += this.cameraRotation.y;
  47177. //rotate, if quaternion is set and rotation was used
  47178. if (this.rotationQuaternion) {
  47179. var len = this.rotation.lengthSquared();
  47180. if (len) {
  47181. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47182. }
  47183. }
  47184. if (!this.noRotationConstraint) {
  47185. var limit = (Math.PI / 2) * 0.95;
  47186. if (this.rotation.x > limit)
  47187. this.rotation.x = limit;
  47188. if (this.rotation.x < -limit)
  47189. this.rotation.x = -limit;
  47190. }
  47191. }
  47192. // Inertia
  47193. if (needToMove) {
  47194. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47195. this.cameraDirection.x = 0;
  47196. }
  47197. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47198. this.cameraDirection.y = 0;
  47199. }
  47200. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47201. this.cameraDirection.z = 0;
  47202. }
  47203. this.cameraDirection.scaleInPlace(this.inertia);
  47204. }
  47205. if (needToRotate) {
  47206. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47207. this.cameraRotation.x = 0;
  47208. }
  47209. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47210. this.cameraRotation.y = 0;
  47211. }
  47212. this.cameraRotation.scaleInPlace(this.inertia);
  47213. }
  47214. _super.prototype._checkInputs.call(this);
  47215. };
  47216. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47217. if (this.rotationQuaternion) {
  47218. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47219. }
  47220. else {
  47221. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47222. }
  47223. //update the up vector!
  47224. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47225. };
  47226. TargetCamera.prototype._getViewMatrix = function () {
  47227. if (this.lockedTarget) {
  47228. this.setTarget(this._getLockedTargetPosition());
  47229. }
  47230. // Compute
  47231. this._updateCameraRotationMatrix();
  47232. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47233. // Computing target and final matrix
  47234. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47235. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47236. return this._viewMatrix;
  47237. };
  47238. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47239. if (this.parent) {
  47240. var parentWorldMatrix = this.parent.getWorldMatrix();
  47241. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47242. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47243. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47244. this._markSyncedWithParent();
  47245. }
  47246. else {
  47247. this._globalPosition.copyFrom(this.position);
  47248. this._globalCurrentTarget.copyFrom(target);
  47249. this._globalCurrentUpVector.copyFrom(up);
  47250. }
  47251. if (this.getScene().useRightHandedSystem) {
  47252. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47253. }
  47254. else {
  47255. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47256. }
  47257. };
  47258. /**
  47259. * @override
  47260. * Override Camera.createRigCamera
  47261. */
  47262. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47263. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47264. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47265. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47266. if (!this.rotationQuaternion) {
  47267. this.rotationQuaternion = new BABYLON.Quaternion();
  47268. }
  47269. rigCamera._cameraRigParams = {};
  47270. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47271. }
  47272. return rigCamera;
  47273. }
  47274. return null;
  47275. };
  47276. /**
  47277. * @override
  47278. * Override Camera._updateRigCameras
  47279. */
  47280. TargetCamera.prototype._updateRigCameras = function () {
  47281. var camLeft = this._rigCameras[0];
  47282. var camRight = this._rigCameras[1];
  47283. switch (this.cameraRigMode) {
  47284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47288. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47289. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47290. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47291. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47292. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47293. camLeft.setTarget(this.getTarget());
  47294. camRight.setTarget(this.getTarget());
  47295. break;
  47296. case BABYLON.Camera.RIG_MODE_VR:
  47297. if (camLeft.rotationQuaternion) {
  47298. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47299. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47300. }
  47301. else {
  47302. camLeft.rotation.copyFrom(this.rotation);
  47303. camRight.rotation.copyFrom(this.rotation);
  47304. }
  47305. camLeft.position.copyFrom(this.position);
  47306. camRight.position.copyFrom(this.position);
  47307. break;
  47308. }
  47309. _super.prototype._updateRigCameras.call(this);
  47310. };
  47311. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47312. if (!this._rigCamTransformMatrix) {
  47313. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47314. }
  47315. var target = this.getTarget();
  47316. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47317. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47318. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47319. };
  47320. TargetCamera.prototype.getClassName = function () {
  47321. return "TargetCamera";
  47322. };
  47323. __decorate([
  47324. BABYLON.serializeAsVector3()
  47325. ], TargetCamera.prototype, "rotation", void 0);
  47326. __decorate([
  47327. BABYLON.serialize()
  47328. ], TargetCamera.prototype, "speed", void 0);
  47329. __decorate([
  47330. BABYLON.serializeAsMeshReference("lockedTargetId")
  47331. ], TargetCamera.prototype, "lockedTarget", void 0);
  47332. return TargetCamera;
  47333. }(BABYLON.Camera));
  47334. BABYLON.TargetCamera = TargetCamera;
  47335. })(BABYLON || (BABYLON = {}));
  47336. //# sourceMappingURL=babylon.targetCamera.js.map
  47337. var BABYLON;
  47338. (function (BABYLON) {
  47339. var FreeCameraMouseInput = /** @class */ (function () {
  47340. function FreeCameraMouseInput(touchEnabled) {
  47341. if (touchEnabled === void 0) { touchEnabled = true; }
  47342. this.touchEnabled = touchEnabled;
  47343. this.buttons = [0, 1, 2];
  47344. this.angularSensibility = 2000.0;
  47345. this.previousPosition = null;
  47346. }
  47347. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47348. var _this = this;
  47349. var engine = this.camera.getEngine();
  47350. if (!this._pointerInput) {
  47351. this._pointerInput = function (p, s) {
  47352. var evt = p.event;
  47353. if (engine.isInVRExclusivePointerMode) {
  47354. return;
  47355. }
  47356. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47357. return;
  47358. }
  47359. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47360. return;
  47361. }
  47362. var srcElement = (evt.srcElement || evt.target);
  47363. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47364. try {
  47365. srcElement.setPointerCapture(evt.pointerId);
  47366. }
  47367. catch (e) {
  47368. //Nothing to do with the error. Execution will continue.
  47369. }
  47370. _this.previousPosition = {
  47371. x: evt.clientX,
  47372. y: evt.clientY
  47373. };
  47374. if (!noPreventDefault) {
  47375. evt.preventDefault();
  47376. element.focus();
  47377. }
  47378. }
  47379. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47380. try {
  47381. srcElement.releasePointerCapture(evt.pointerId);
  47382. }
  47383. catch (e) {
  47384. //Nothing to do with the error.
  47385. }
  47386. _this.previousPosition = null;
  47387. if (!noPreventDefault) {
  47388. evt.preventDefault();
  47389. }
  47390. }
  47391. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47392. if (!_this.previousPosition || engine.isPointerLock) {
  47393. return;
  47394. }
  47395. var offsetX = evt.clientX - _this.previousPosition.x;
  47396. if (_this.camera.getScene().useRightHandedSystem)
  47397. offsetX *= -1;
  47398. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47399. offsetX *= -1;
  47400. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47401. var offsetY = evt.clientY - _this.previousPosition.y;
  47402. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47403. _this.previousPosition = {
  47404. x: evt.clientX,
  47405. y: evt.clientY
  47406. };
  47407. if (!noPreventDefault) {
  47408. evt.preventDefault();
  47409. }
  47410. }
  47411. };
  47412. }
  47413. this._onMouseMove = function (evt) {
  47414. if (!engine.isPointerLock) {
  47415. return;
  47416. }
  47417. if (engine.isInVRExclusivePointerMode) {
  47418. return;
  47419. }
  47420. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47421. if (_this.camera.getScene().useRightHandedSystem)
  47422. offsetX *= -1;
  47423. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47424. offsetX *= -1;
  47425. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47426. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47427. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47428. _this.previousPosition = null;
  47429. if (!noPreventDefault) {
  47430. evt.preventDefault();
  47431. }
  47432. };
  47433. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47434. element.addEventListener("mousemove", this._onMouseMove, false);
  47435. };
  47436. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47437. if (this._observer && element) {
  47438. this.camera.getScene().onPointerObservable.remove(this._observer);
  47439. if (this._onMouseMove) {
  47440. element.removeEventListener("mousemove", this._onMouseMove);
  47441. }
  47442. this._observer = null;
  47443. this._onMouseMove = null;
  47444. this.previousPosition = null;
  47445. }
  47446. };
  47447. FreeCameraMouseInput.prototype.getClassName = function () {
  47448. return "FreeCameraMouseInput";
  47449. };
  47450. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47451. return "mouse";
  47452. };
  47453. __decorate([
  47454. BABYLON.serialize()
  47455. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47456. __decorate([
  47457. BABYLON.serialize()
  47458. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47459. return FreeCameraMouseInput;
  47460. }());
  47461. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47462. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47463. })(BABYLON || (BABYLON = {}));
  47464. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47465. var BABYLON;
  47466. (function (BABYLON) {
  47467. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47468. function FreeCameraKeyboardMoveInput() {
  47469. this._keys = new Array();
  47470. this.keysUp = [38];
  47471. this.keysDown = [40];
  47472. this.keysLeft = [37];
  47473. this.keysRight = [39];
  47474. }
  47475. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47476. var _this = this;
  47477. if (this._onCanvasBlurObserver) {
  47478. return;
  47479. }
  47480. this._scene = this.camera.getScene();
  47481. this._engine = this._scene.getEngine();
  47482. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47483. _this._keys = [];
  47484. });
  47485. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47486. var evt = info.event;
  47487. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47491. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47492. var index = _this._keys.indexOf(evt.keyCode);
  47493. if (index === -1) {
  47494. _this._keys.push(evt.keyCode);
  47495. }
  47496. if (!noPreventDefault) {
  47497. evt.preventDefault();
  47498. }
  47499. }
  47500. }
  47501. else {
  47502. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47503. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47504. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47505. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47506. var index = _this._keys.indexOf(evt.keyCode);
  47507. if (index >= 0) {
  47508. _this._keys.splice(index, 1);
  47509. }
  47510. if (!noPreventDefault) {
  47511. evt.preventDefault();
  47512. }
  47513. }
  47514. }
  47515. });
  47516. };
  47517. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47518. if (this._scene) {
  47519. if (this._onKeyboardObserver) {
  47520. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47521. }
  47522. if (this._onCanvasBlurObserver) {
  47523. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47524. }
  47525. this._onKeyboardObserver = null;
  47526. this._onCanvasBlurObserver = null;
  47527. }
  47528. this._keys = [];
  47529. };
  47530. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47531. if (this._onKeyboardObserver) {
  47532. var camera = this.camera;
  47533. // Keyboard
  47534. for (var index = 0; index < this._keys.length; index++) {
  47535. var keyCode = this._keys[index];
  47536. var speed = camera._computeLocalCameraSpeed();
  47537. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47538. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47539. }
  47540. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47541. camera._localDirection.copyFromFloats(0, 0, speed);
  47542. }
  47543. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47544. camera._localDirection.copyFromFloats(speed, 0, 0);
  47545. }
  47546. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47547. camera._localDirection.copyFromFloats(0, 0, -speed);
  47548. }
  47549. if (camera.getScene().useRightHandedSystem) {
  47550. camera._localDirection.z *= -1;
  47551. }
  47552. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47553. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47554. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47555. }
  47556. }
  47557. };
  47558. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47559. return "FreeCameraKeyboardMoveInput";
  47560. };
  47561. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47562. this._keys = [];
  47563. };
  47564. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47565. return "keyboard";
  47566. };
  47567. __decorate([
  47568. BABYLON.serialize()
  47569. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47570. __decorate([
  47571. BABYLON.serialize()
  47572. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47573. __decorate([
  47574. BABYLON.serialize()
  47575. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47576. __decorate([
  47577. BABYLON.serialize()
  47578. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47579. return FreeCameraKeyboardMoveInput;
  47580. }());
  47581. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47582. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47583. })(BABYLON || (BABYLON = {}));
  47584. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47585. var BABYLON;
  47586. (function (BABYLON) {
  47587. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47588. __extends(FreeCameraInputsManager, _super);
  47589. function FreeCameraInputsManager(camera) {
  47590. return _super.call(this, camera) || this;
  47591. }
  47592. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47593. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47594. return this;
  47595. };
  47596. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47597. if (touchEnabled === void 0) { touchEnabled = true; }
  47598. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47599. return this;
  47600. };
  47601. FreeCameraInputsManager.prototype.addGamepad = function () {
  47602. this.add(new BABYLON.FreeCameraGamepadInput());
  47603. return this;
  47604. };
  47605. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47606. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47607. return this;
  47608. };
  47609. FreeCameraInputsManager.prototype.addTouch = function () {
  47610. this.add(new BABYLON.FreeCameraTouchInput());
  47611. return this;
  47612. };
  47613. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47614. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47615. return this;
  47616. };
  47617. return FreeCameraInputsManager;
  47618. }(BABYLON.CameraInputsManager));
  47619. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47620. })(BABYLON || (BABYLON = {}));
  47621. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47622. var BABYLON;
  47623. (function (BABYLON) {
  47624. var FreeCamera = /** @class */ (function (_super) {
  47625. __extends(FreeCamera, _super);
  47626. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47627. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47628. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47629. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47630. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47631. _this.checkCollisions = false;
  47632. _this.applyGravity = false;
  47633. _this._needMoveForGravity = false;
  47634. _this._oldPosition = BABYLON.Vector3.Zero();
  47635. _this._diffPosition = BABYLON.Vector3.Zero();
  47636. _this._newPosition = BABYLON.Vector3.Zero();
  47637. // Collisions
  47638. _this._collisionMask = -1;
  47639. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47640. if (collidedMesh === void 0) { collidedMesh = null; }
  47641. //TODO move this to the collision coordinator!
  47642. if (_this.getScene().workerCollisions)
  47643. newPosition.multiplyInPlace(_this._collider._radius);
  47644. var updatePosition = function (newPos) {
  47645. _this._newPosition.copyFrom(newPos);
  47646. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47647. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47648. _this.position.addInPlace(_this._diffPosition);
  47649. if (_this.onCollide && collidedMesh) {
  47650. _this.onCollide(collidedMesh);
  47651. }
  47652. }
  47653. };
  47654. updatePosition(newPosition);
  47655. };
  47656. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47657. _this.inputs.addKeyboard().addMouse();
  47658. return _this;
  47659. }
  47660. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47661. //-- begin properties for backward compatibility for inputs
  47662. /**
  47663. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47664. * Higher values reduce sensitivity.
  47665. */
  47666. get: function () {
  47667. var mouse = this.inputs.attached["mouse"];
  47668. if (mouse)
  47669. return mouse.angularSensibility;
  47670. return 0;
  47671. },
  47672. /**
  47673. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47674. * Higher values reduce sensitivity.
  47675. */
  47676. set: function (value) {
  47677. var mouse = this.inputs.attached["mouse"];
  47678. if (mouse)
  47679. mouse.angularSensibility = value;
  47680. },
  47681. enumerable: true,
  47682. configurable: true
  47683. });
  47684. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47685. get: function () {
  47686. var keyboard = this.inputs.attached["keyboard"];
  47687. if (keyboard)
  47688. return keyboard.keysUp;
  47689. return [];
  47690. },
  47691. set: function (value) {
  47692. var keyboard = this.inputs.attached["keyboard"];
  47693. if (keyboard)
  47694. keyboard.keysUp = value;
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47700. get: function () {
  47701. var keyboard = this.inputs.attached["keyboard"];
  47702. if (keyboard)
  47703. return keyboard.keysDown;
  47704. return [];
  47705. },
  47706. set: function (value) {
  47707. var keyboard = this.inputs.attached["keyboard"];
  47708. if (keyboard)
  47709. keyboard.keysDown = value;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47715. get: function () {
  47716. var keyboard = this.inputs.attached["keyboard"];
  47717. if (keyboard)
  47718. return keyboard.keysLeft;
  47719. return [];
  47720. },
  47721. set: function (value) {
  47722. var keyboard = this.inputs.attached["keyboard"];
  47723. if (keyboard)
  47724. keyboard.keysLeft = value;
  47725. },
  47726. enumerable: true,
  47727. configurable: true
  47728. });
  47729. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47730. get: function () {
  47731. var keyboard = this.inputs.attached["keyboard"];
  47732. if (keyboard)
  47733. return keyboard.keysRight;
  47734. return [];
  47735. },
  47736. set: function (value) {
  47737. var keyboard = this.inputs.attached["keyboard"];
  47738. if (keyboard)
  47739. keyboard.keysRight = value;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. // Controls
  47745. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47746. this.inputs.attachElement(element, noPreventDefault);
  47747. };
  47748. FreeCamera.prototype.detachControl = function (element) {
  47749. this.inputs.detachElement(element);
  47750. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47751. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47752. };
  47753. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47754. get: function () {
  47755. return this._collisionMask;
  47756. },
  47757. set: function (mask) {
  47758. this._collisionMask = !isNaN(mask) ? mask : -1;
  47759. },
  47760. enumerable: true,
  47761. configurable: true
  47762. });
  47763. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47764. var globalPosition;
  47765. if (this.parent) {
  47766. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47767. }
  47768. else {
  47769. globalPosition = this.position;
  47770. }
  47771. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47772. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47773. if (!this._collider) {
  47774. this._collider = new BABYLON.Collider();
  47775. }
  47776. this._collider._radius = this.ellipsoid;
  47777. this._collider.collisionMask = this._collisionMask;
  47778. //no need for clone, as long as gravity is not on.
  47779. var actualDisplacement = displacement;
  47780. //add gravity to the direction to prevent the dual-collision checking
  47781. if (this.applyGravity) {
  47782. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47783. actualDisplacement = displacement.add(this.getScene().gravity);
  47784. }
  47785. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47786. };
  47787. FreeCamera.prototype._checkInputs = function () {
  47788. if (!this._localDirection) {
  47789. this._localDirection = BABYLON.Vector3.Zero();
  47790. this._transformedDirection = BABYLON.Vector3.Zero();
  47791. }
  47792. this.inputs.checkInputs();
  47793. _super.prototype._checkInputs.call(this);
  47794. };
  47795. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47796. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47797. };
  47798. FreeCamera.prototype._updatePosition = function () {
  47799. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47800. this._collideWithWorld(this.cameraDirection);
  47801. }
  47802. else {
  47803. _super.prototype._updatePosition.call(this);
  47804. }
  47805. };
  47806. FreeCamera.prototype.dispose = function () {
  47807. this.inputs.clear();
  47808. _super.prototype.dispose.call(this);
  47809. };
  47810. FreeCamera.prototype.getClassName = function () {
  47811. return "FreeCamera";
  47812. };
  47813. __decorate([
  47814. BABYLON.serializeAsVector3()
  47815. ], FreeCamera.prototype, "ellipsoid", void 0);
  47816. __decorate([
  47817. BABYLON.serializeAsVector3()
  47818. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47819. __decorate([
  47820. BABYLON.serialize()
  47821. ], FreeCamera.prototype, "checkCollisions", void 0);
  47822. __decorate([
  47823. BABYLON.serialize()
  47824. ], FreeCamera.prototype, "applyGravity", void 0);
  47825. return FreeCamera;
  47826. }(BABYLON.TargetCamera));
  47827. BABYLON.FreeCamera = FreeCamera;
  47828. })(BABYLON || (BABYLON = {}));
  47829. //# sourceMappingURL=babylon.freeCamera.js.map
  47830. var BABYLON;
  47831. (function (BABYLON) {
  47832. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47833. function ArcRotateCameraKeyboardMoveInput() {
  47834. this._keys = new Array();
  47835. this.keysUp = [38];
  47836. this.keysDown = [40];
  47837. this.keysLeft = [37];
  47838. this.keysRight = [39];
  47839. this.keysReset = [220];
  47840. this.panningSensibility = 50.0;
  47841. this.zoomingSensibility = 25.0;
  47842. this.useAltToZoom = true;
  47843. }
  47844. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47845. var _this = this;
  47846. if (this._onCanvasBlurObserver) {
  47847. return;
  47848. }
  47849. this._scene = this.camera.getScene();
  47850. this._engine = this._scene.getEngine();
  47851. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47852. _this._keys = [];
  47853. });
  47854. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47855. var evt = info.event;
  47856. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47857. _this._ctrlPressed = evt.ctrlKey;
  47858. _this._altPressed = evt.altKey;
  47859. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47860. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47861. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47862. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47863. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47864. var index = _this._keys.indexOf(evt.keyCode);
  47865. if (index === -1) {
  47866. _this._keys.push(evt.keyCode);
  47867. }
  47868. if (evt.preventDefault) {
  47869. if (!noPreventDefault) {
  47870. evt.preventDefault();
  47871. }
  47872. }
  47873. }
  47874. }
  47875. else {
  47876. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47877. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47878. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47879. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47880. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47881. var index = _this._keys.indexOf(evt.keyCode);
  47882. if (index >= 0) {
  47883. _this._keys.splice(index, 1);
  47884. }
  47885. if (evt.preventDefault) {
  47886. if (!noPreventDefault) {
  47887. evt.preventDefault();
  47888. }
  47889. }
  47890. }
  47891. }
  47892. });
  47893. };
  47894. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47895. if (this._scene) {
  47896. if (this._onKeyboardObserver) {
  47897. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47898. }
  47899. if (this._onCanvasBlurObserver) {
  47900. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47901. }
  47902. this._onKeyboardObserver = null;
  47903. this._onCanvasBlurObserver = null;
  47904. }
  47905. this._keys = [];
  47906. };
  47907. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47908. if (this._onKeyboardObserver) {
  47909. var camera = this.camera;
  47910. for (var index = 0; index < this._keys.length; index++) {
  47911. var keyCode = this._keys[index];
  47912. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47913. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47914. camera.inertialPanningX -= 1 / this.panningSensibility;
  47915. }
  47916. else {
  47917. camera.inertialAlphaOffset -= 0.01;
  47918. }
  47919. }
  47920. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47921. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47922. camera.inertialPanningY += 1 / this.panningSensibility;
  47923. }
  47924. else if (this._altPressed && this.useAltToZoom) {
  47925. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47926. }
  47927. else {
  47928. camera.inertialBetaOffset -= 0.01;
  47929. }
  47930. }
  47931. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47932. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47933. camera.inertialPanningX += 1 / this.panningSensibility;
  47934. }
  47935. else {
  47936. camera.inertialAlphaOffset += 0.01;
  47937. }
  47938. }
  47939. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47940. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47941. camera.inertialPanningY -= 1 / this.panningSensibility;
  47942. }
  47943. else if (this._altPressed && this.useAltToZoom) {
  47944. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47945. }
  47946. else {
  47947. camera.inertialBetaOffset += 0.01;
  47948. }
  47949. }
  47950. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47951. camera.restoreState();
  47952. }
  47953. }
  47954. }
  47955. };
  47956. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47957. return "ArcRotateCameraKeyboardMoveInput";
  47958. };
  47959. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47960. return "keyboard";
  47961. };
  47962. __decorate([
  47963. BABYLON.serialize()
  47964. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47965. __decorate([
  47966. BABYLON.serialize()
  47967. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47968. __decorate([
  47969. BABYLON.serialize()
  47970. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47971. __decorate([
  47972. BABYLON.serialize()
  47973. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47974. __decorate([
  47975. BABYLON.serialize()
  47976. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47977. __decorate([
  47978. BABYLON.serialize()
  47979. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47980. __decorate([
  47981. BABYLON.serialize()
  47982. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47983. __decorate([
  47984. BABYLON.serialize()
  47985. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47986. return ArcRotateCameraKeyboardMoveInput;
  47987. }());
  47988. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47989. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47990. })(BABYLON || (BABYLON = {}));
  47991. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47992. var BABYLON;
  47993. (function (BABYLON) {
  47994. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47995. function ArcRotateCameraMouseWheelInput() {
  47996. this.wheelPrecision = 3.0;
  47997. /**
  47998. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47999. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48000. */
  48001. this.wheelDeltaPercentage = 0;
  48002. }
  48003. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48004. var _this = this;
  48005. this._wheel = function (p, s) {
  48006. //sanity check - this should be a PointerWheel event.
  48007. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48008. return;
  48009. var event = p.event;
  48010. var delta = 0;
  48011. if (event.wheelDelta) {
  48012. if (_this.wheelDeltaPercentage) {
  48013. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48014. if (event.wheelDelta > 0) {
  48015. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48016. }
  48017. else {
  48018. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48019. }
  48020. }
  48021. else {
  48022. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48023. }
  48024. }
  48025. else if (event.detail) {
  48026. delta = -event.detail / _this.wheelPrecision;
  48027. }
  48028. if (delta)
  48029. _this.camera.inertialRadiusOffset += delta;
  48030. if (event.preventDefault) {
  48031. if (!noPreventDefault) {
  48032. event.preventDefault();
  48033. }
  48034. }
  48035. };
  48036. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48037. };
  48038. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48039. if (this._observer && element) {
  48040. this.camera.getScene().onPointerObservable.remove(this._observer);
  48041. this._observer = null;
  48042. this._wheel = null;
  48043. }
  48044. };
  48045. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48046. return "ArcRotateCameraMouseWheelInput";
  48047. };
  48048. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48049. return "mousewheel";
  48050. };
  48051. __decorate([
  48052. BABYLON.serialize()
  48053. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48054. __decorate([
  48055. BABYLON.serialize()
  48056. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48057. return ArcRotateCameraMouseWheelInput;
  48058. }());
  48059. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48060. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48061. })(BABYLON || (BABYLON = {}));
  48062. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48063. var BABYLON;
  48064. (function (BABYLON) {
  48065. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48066. function ArcRotateCameraPointersInput() {
  48067. this.buttons = [0, 1, 2];
  48068. this.angularSensibilityX = 1000.0;
  48069. this.angularSensibilityY = 1000.0;
  48070. this.pinchPrecision = 12.0;
  48071. /**
  48072. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48073. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48074. */
  48075. this.pinchDeltaPercentage = 0;
  48076. this.panningSensibility = 1000.0;
  48077. this.multiTouchPanning = true;
  48078. this.multiTouchPanAndZoom = true;
  48079. this._isPanClick = false;
  48080. this.pinchInwards = true;
  48081. }
  48082. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48083. var _this = this;
  48084. var engine = this.camera.getEngine();
  48085. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48086. var pointA = null;
  48087. var pointB = null;
  48088. var previousPinchSquaredDistance = 0;
  48089. var initialDistance = 0;
  48090. var twoFingerActivityCount = 0;
  48091. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48092. this._pointerInput = function (p, s) {
  48093. var evt = p.event;
  48094. var isTouch = p.event.pointerType === "touch";
  48095. if (engine.isInVRExclusivePointerMode) {
  48096. return;
  48097. }
  48098. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48099. return;
  48100. }
  48101. var srcElement = (evt.srcElement || evt.target);
  48102. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48103. try {
  48104. srcElement.setPointerCapture(evt.pointerId);
  48105. }
  48106. catch (e) {
  48107. //Nothing to do with the error. Execution will continue.
  48108. }
  48109. // Manage panning with pan button click
  48110. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48111. // manage pointers
  48112. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48113. if (pointA === null) {
  48114. pointA = cacheSoloPointer;
  48115. }
  48116. else if (pointB === null) {
  48117. pointB = cacheSoloPointer;
  48118. }
  48119. if (!noPreventDefault) {
  48120. evt.preventDefault();
  48121. element.focus();
  48122. }
  48123. }
  48124. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48125. _this.camera.restoreState();
  48126. }
  48127. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48128. try {
  48129. srcElement.releasePointerCapture(evt.pointerId);
  48130. }
  48131. catch (e) {
  48132. //Nothing to do with the error.
  48133. }
  48134. cacheSoloPointer = null;
  48135. previousPinchSquaredDistance = 0;
  48136. previousMultiTouchPanPosition.isPaning = false;
  48137. previousMultiTouchPanPosition.isPinching = false;
  48138. twoFingerActivityCount = 0;
  48139. initialDistance = 0;
  48140. if (!isTouch) {
  48141. pointB = null; // Mouse and pen are mono pointer
  48142. }
  48143. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48144. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48145. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48146. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48147. if (engine._badOS) {
  48148. pointA = pointB = null;
  48149. }
  48150. else {
  48151. //only remove the impacted pointer in case of multitouch allowing on most
  48152. //platforms switching from rotate to zoom and pan seamlessly.
  48153. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48154. pointA = pointB;
  48155. pointB = null;
  48156. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48157. }
  48158. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48159. pointB = null;
  48160. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48161. }
  48162. else {
  48163. pointA = pointB = null;
  48164. }
  48165. }
  48166. if (!noPreventDefault) {
  48167. evt.preventDefault();
  48168. }
  48169. }
  48170. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48171. if (!noPreventDefault) {
  48172. evt.preventDefault();
  48173. }
  48174. // One button down
  48175. if (pointA && pointB === null && cacheSoloPointer) {
  48176. if (_this.panningSensibility !== 0 &&
  48177. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48178. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48179. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48180. }
  48181. else {
  48182. var offsetX = evt.clientX - cacheSoloPointer.x;
  48183. var offsetY = evt.clientY - cacheSoloPointer.y;
  48184. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48185. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48186. }
  48187. cacheSoloPointer.x = evt.clientX;
  48188. cacheSoloPointer.y = evt.clientY;
  48189. }
  48190. // Two buttons down: pinch/pan
  48191. else if (pointA && pointB) {
  48192. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48193. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48194. ed.x = evt.clientX;
  48195. ed.y = evt.clientY;
  48196. var direction = _this.pinchInwards ? 1 : -1;
  48197. var distX = pointA.x - pointB.x;
  48198. var distY = pointA.y - pointB.y;
  48199. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48200. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48201. if (previousPinchSquaredDistance === 0) {
  48202. initialDistance = pinchDistance;
  48203. previousPinchSquaredDistance = pinchSquaredDistance;
  48204. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48205. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48206. return;
  48207. }
  48208. if (_this.multiTouchPanAndZoom) {
  48209. if (_this.pinchDeltaPercentage) {
  48210. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48211. }
  48212. else {
  48213. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48214. (_this.pinchPrecision *
  48215. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48216. direction);
  48217. }
  48218. if (_this.panningSensibility !== 0) {
  48219. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48220. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48221. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48222. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48223. previousMultiTouchPanPosition.x = pointersCenterX;
  48224. previousMultiTouchPanPosition.y = pointersCenterY;
  48225. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48226. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48227. }
  48228. }
  48229. else {
  48230. twoFingerActivityCount++;
  48231. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48232. if (_this.pinchDeltaPercentage) {
  48233. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48234. }
  48235. else {
  48236. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48237. (_this.pinchPrecision *
  48238. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48239. direction);
  48240. }
  48241. previousMultiTouchPanPosition.isPaning = false;
  48242. previousMultiTouchPanPosition.isPinching = true;
  48243. }
  48244. else {
  48245. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48246. if (!previousMultiTouchPanPosition.isPaning) {
  48247. previousMultiTouchPanPosition.isPaning = true;
  48248. previousMultiTouchPanPosition.isPinching = false;
  48249. previousMultiTouchPanPosition.x = ed.x;
  48250. previousMultiTouchPanPosition.y = ed.y;
  48251. return;
  48252. }
  48253. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48254. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48255. }
  48256. }
  48257. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48258. previousMultiTouchPanPosition.x = ed.x;
  48259. previousMultiTouchPanPosition.y = ed.y;
  48260. }
  48261. }
  48262. previousPinchSquaredDistance = pinchSquaredDistance;
  48263. }
  48264. }
  48265. };
  48266. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48267. this._onContextMenu = function (evt) {
  48268. evt.preventDefault();
  48269. };
  48270. if (!this.camera._useCtrlForPanning) {
  48271. element.addEventListener("contextmenu", this._onContextMenu, false);
  48272. }
  48273. this._onLostFocus = function () {
  48274. //this._keys = [];
  48275. pointA = pointB = null;
  48276. previousPinchSquaredDistance = 0;
  48277. previousMultiTouchPanPosition.isPaning = false;
  48278. previousMultiTouchPanPosition.isPinching = false;
  48279. twoFingerActivityCount = 0;
  48280. cacheSoloPointer = null;
  48281. initialDistance = 0;
  48282. };
  48283. this._onMouseMove = function (evt) {
  48284. if (!engine.isPointerLock) {
  48285. return;
  48286. }
  48287. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48288. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48289. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48290. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48291. if (!noPreventDefault) {
  48292. evt.preventDefault();
  48293. }
  48294. };
  48295. this._onGestureStart = function (e) {
  48296. if (window.MSGesture === undefined) {
  48297. return;
  48298. }
  48299. if (!_this._MSGestureHandler) {
  48300. _this._MSGestureHandler = new MSGesture();
  48301. _this._MSGestureHandler.target = element;
  48302. }
  48303. _this._MSGestureHandler.addPointer(e.pointerId);
  48304. };
  48305. this._onGesture = function (e) {
  48306. _this.camera.radius *= e.scale;
  48307. if (e.preventDefault) {
  48308. if (!noPreventDefault) {
  48309. e.stopPropagation();
  48310. e.preventDefault();
  48311. }
  48312. }
  48313. };
  48314. element.addEventListener("mousemove", this._onMouseMove, false);
  48315. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48316. element.addEventListener("MSGestureChange", this._onGesture, false);
  48317. BABYLON.Tools.RegisterTopRootEvents([
  48318. { name: "blur", handler: this._onLostFocus }
  48319. ]);
  48320. };
  48321. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48322. if (this._onLostFocus) {
  48323. BABYLON.Tools.UnregisterTopRootEvents([
  48324. { name: "blur", handler: this._onLostFocus }
  48325. ]);
  48326. }
  48327. if (element && this._observer) {
  48328. this.camera.getScene().onPointerObservable.remove(this._observer);
  48329. this._observer = null;
  48330. if (this._onContextMenu) {
  48331. element.removeEventListener("contextmenu", this._onContextMenu);
  48332. }
  48333. if (this._onMouseMove) {
  48334. element.removeEventListener("mousemove", this._onMouseMove);
  48335. }
  48336. if (this._onGestureStart) {
  48337. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48338. }
  48339. if (this._onGesture) {
  48340. element.removeEventListener("MSGestureChange", this._onGesture);
  48341. }
  48342. this._isPanClick = false;
  48343. this.pinchInwards = true;
  48344. this._onMouseMove = null;
  48345. this._onGestureStart = null;
  48346. this._onGesture = null;
  48347. this._MSGestureHandler = null;
  48348. this._onLostFocus = null;
  48349. this._onContextMenu = null;
  48350. }
  48351. };
  48352. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48353. return "ArcRotateCameraPointersInput";
  48354. };
  48355. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48356. return "pointers";
  48357. };
  48358. __decorate([
  48359. BABYLON.serialize()
  48360. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48361. __decorate([
  48362. BABYLON.serialize()
  48363. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48370. __decorate([
  48371. BABYLON.serialize()
  48372. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48373. __decorate([
  48374. BABYLON.serialize()
  48375. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48376. __decorate([
  48377. BABYLON.serialize()
  48378. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48379. __decorate([
  48380. BABYLON.serialize()
  48381. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48382. return ArcRotateCameraPointersInput;
  48383. }());
  48384. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48385. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48386. })(BABYLON || (BABYLON = {}));
  48387. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48388. var BABYLON;
  48389. (function (BABYLON) {
  48390. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48391. __extends(ArcRotateCameraInputsManager, _super);
  48392. function ArcRotateCameraInputsManager(camera) {
  48393. return _super.call(this, camera) || this;
  48394. }
  48395. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48396. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48397. return this;
  48398. };
  48399. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48400. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48401. return this;
  48402. };
  48403. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48404. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48405. return this;
  48406. };
  48407. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48408. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48409. return this;
  48410. };
  48411. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48412. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48413. return this;
  48414. };
  48415. return ArcRotateCameraInputsManager;
  48416. }(BABYLON.CameraInputsManager));
  48417. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48418. })(BABYLON || (BABYLON = {}));
  48419. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48420. var BABYLON;
  48421. (function (BABYLON) {
  48422. var ArcRotateCamera = /** @class */ (function (_super) {
  48423. __extends(ArcRotateCamera, _super);
  48424. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48425. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48426. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48427. _this.inertialAlphaOffset = 0;
  48428. _this.inertialBetaOffset = 0;
  48429. _this.inertialRadiusOffset = 0;
  48430. _this.lowerAlphaLimit = null;
  48431. _this.upperAlphaLimit = null;
  48432. _this.lowerBetaLimit = 0.01;
  48433. _this.upperBetaLimit = Math.PI;
  48434. _this.lowerRadiusLimit = null;
  48435. _this.upperRadiusLimit = null;
  48436. _this.inertialPanningX = 0;
  48437. _this.inertialPanningY = 0;
  48438. _this.pinchToPanMaxDistance = 20;
  48439. _this.panningDistanceLimit = null;
  48440. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48441. _this.panningInertia = 0.9;
  48442. //-- end properties for backward compatibility for inputs
  48443. _this.zoomOnFactor = 1;
  48444. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48445. _this.allowUpsideDown = true;
  48446. _this._viewMatrix = new BABYLON.Matrix();
  48447. // Panning
  48448. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48449. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48450. _this.checkCollisions = false;
  48451. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48452. _this._previousPosition = BABYLON.Vector3.Zero();
  48453. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48454. _this._newPosition = BABYLON.Vector3.Zero();
  48455. _this._computationVector = BABYLON.Vector3.Zero();
  48456. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48457. if (collidedMesh === void 0) { collidedMesh = null; }
  48458. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48459. newPosition.multiplyInPlace(_this._collider._radius);
  48460. }
  48461. if (!collidedMesh) {
  48462. _this._previousPosition.copyFrom(_this.position);
  48463. }
  48464. else {
  48465. _this.setPosition(newPosition);
  48466. if (_this.onCollide) {
  48467. _this.onCollide(collidedMesh);
  48468. }
  48469. }
  48470. // Recompute because of constraints
  48471. var cosa = Math.cos(_this.alpha);
  48472. var sina = Math.sin(_this.alpha);
  48473. var cosb = Math.cos(_this.beta);
  48474. var sinb = Math.sin(_this.beta);
  48475. if (sinb === 0) {
  48476. sinb = 0.0001;
  48477. }
  48478. var target = _this._getTargetPosition();
  48479. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48480. target.addToRef(_this._computationVector, _this._newPosition);
  48481. _this.position.copyFrom(_this._newPosition);
  48482. var up = _this.upVector;
  48483. if (_this.allowUpsideDown && _this.beta < 0) {
  48484. up = up.clone();
  48485. up = up.negate();
  48486. }
  48487. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48488. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48489. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48490. _this._collisionTriggered = false;
  48491. };
  48492. _this._target = BABYLON.Vector3.Zero();
  48493. if (target) {
  48494. _this.setTarget(target);
  48495. }
  48496. _this.alpha = alpha;
  48497. _this.beta = beta;
  48498. _this.radius = radius;
  48499. _this.getViewMatrix();
  48500. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48501. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48502. return _this;
  48503. }
  48504. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48505. get: function () {
  48506. return this._target;
  48507. },
  48508. set: function (value) {
  48509. this.setTarget(value);
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48515. //-- begin properties for backward compatibility for inputs
  48516. get: function () {
  48517. var pointers = this.inputs.attached["pointers"];
  48518. if (pointers)
  48519. return pointers.angularSensibilityX;
  48520. return 0;
  48521. },
  48522. set: function (value) {
  48523. var pointers = this.inputs.attached["pointers"];
  48524. if (pointers) {
  48525. pointers.angularSensibilityX = value;
  48526. }
  48527. },
  48528. enumerable: true,
  48529. configurable: true
  48530. });
  48531. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48532. get: function () {
  48533. var pointers = this.inputs.attached["pointers"];
  48534. if (pointers)
  48535. return pointers.angularSensibilityY;
  48536. return 0;
  48537. },
  48538. set: function (value) {
  48539. var pointers = this.inputs.attached["pointers"];
  48540. if (pointers) {
  48541. pointers.angularSensibilityY = value;
  48542. }
  48543. },
  48544. enumerable: true,
  48545. configurable: true
  48546. });
  48547. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48548. get: function () {
  48549. var pointers = this.inputs.attached["pointers"];
  48550. if (pointers)
  48551. return pointers.pinchPrecision;
  48552. return 0;
  48553. },
  48554. set: function (value) {
  48555. var pointers = this.inputs.attached["pointers"];
  48556. if (pointers) {
  48557. pointers.pinchPrecision = value;
  48558. }
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48564. get: function () {
  48565. var pointers = this.inputs.attached["pointers"];
  48566. if (pointers)
  48567. return pointers.pinchDeltaPercentage;
  48568. return 0;
  48569. },
  48570. set: function (value) {
  48571. var pointers = this.inputs.attached["pointers"];
  48572. if (pointers) {
  48573. pointers.pinchDeltaPercentage = value;
  48574. }
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48580. get: function () {
  48581. var pointers = this.inputs.attached["pointers"];
  48582. if (pointers)
  48583. return pointers.panningSensibility;
  48584. return 0;
  48585. },
  48586. set: function (value) {
  48587. var pointers = this.inputs.attached["pointers"];
  48588. if (pointers) {
  48589. pointers.panningSensibility = value;
  48590. }
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48596. get: function () {
  48597. var keyboard = this.inputs.attached["keyboard"];
  48598. if (keyboard)
  48599. return keyboard.keysUp;
  48600. return [];
  48601. },
  48602. set: function (value) {
  48603. var keyboard = this.inputs.attached["keyboard"];
  48604. if (keyboard)
  48605. keyboard.keysUp = value;
  48606. },
  48607. enumerable: true,
  48608. configurable: true
  48609. });
  48610. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48611. get: function () {
  48612. var keyboard = this.inputs.attached["keyboard"];
  48613. if (keyboard)
  48614. return keyboard.keysDown;
  48615. return [];
  48616. },
  48617. set: function (value) {
  48618. var keyboard = this.inputs.attached["keyboard"];
  48619. if (keyboard)
  48620. keyboard.keysDown = value;
  48621. },
  48622. enumerable: true,
  48623. configurable: true
  48624. });
  48625. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48626. get: function () {
  48627. var keyboard = this.inputs.attached["keyboard"];
  48628. if (keyboard)
  48629. return keyboard.keysLeft;
  48630. return [];
  48631. },
  48632. set: function (value) {
  48633. var keyboard = this.inputs.attached["keyboard"];
  48634. if (keyboard)
  48635. keyboard.keysLeft = value;
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48641. get: function () {
  48642. var keyboard = this.inputs.attached["keyboard"];
  48643. if (keyboard)
  48644. return keyboard.keysRight;
  48645. return [];
  48646. },
  48647. set: function (value) {
  48648. var keyboard = this.inputs.attached["keyboard"];
  48649. if (keyboard)
  48650. keyboard.keysRight = value;
  48651. },
  48652. enumerable: true,
  48653. configurable: true
  48654. });
  48655. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48656. get: function () {
  48657. var mousewheel = this.inputs.attached["mousewheel"];
  48658. if (mousewheel)
  48659. return mousewheel.wheelPrecision;
  48660. return 0;
  48661. },
  48662. set: function (value) {
  48663. var mousewheel = this.inputs.attached["mousewheel"];
  48664. if (mousewheel)
  48665. mousewheel.wheelPrecision = value;
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48671. get: function () {
  48672. var mousewheel = this.inputs.attached["mousewheel"];
  48673. if (mousewheel)
  48674. return mousewheel.wheelDeltaPercentage;
  48675. return 0;
  48676. },
  48677. set: function (value) {
  48678. var mousewheel = this.inputs.attached["mousewheel"];
  48679. if (mousewheel)
  48680. mousewheel.wheelDeltaPercentage = value;
  48681. },
  48682. enumerable: true,
  48683. configurable: true
  48684. });
  48685. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48686. get: function () {
  48687. return this._bouncingBehavior;
  48688. },
  48689. enumerable: true,
  48690. configurable: true
  48691. });
  48692. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48693. get: function () {
  48694. return this._bouncingBehavior != null;
  48695. },
  48696. set: function (value) {
  48697. if (value === this.useBouncingBehavior) {
  48698. return;
  48699. }
  48700. if (value) {
  48701. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48702. this.addBehavior(this._bouncingBehavior);
  48703. }
  48704. else if (this._bouncingBehavior) {
  48705. this.removeBehavior(this._bouncingBehavior);
  48706. this._bouncingBehavior = null;
  48707. }
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48713. get: function () {
  48714. return this._framingBehavior;
  48715. },
  48716. enumerable: true,
  48717. configurable: true
  48718. });
  48719. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48720. get: function () {
  48721. return this._framingBehavior != null;
  48722. },
  48723. set: function (value) {
  48724. if (value === this.useFramingBehavior) {
  48725. return;
  48726. }
  48727. if (value) {
  48728. this._framingBehavior = new BABYLON.FramingBehavior();
  48729. this.addBehavior(this._framingBehavior);
  48730. }
  48731. else if (this._framingBehavior) {
  48732. this.removeBehavior(this._framingBehavior);
  48733. this._framingBehavior = null;
  48734. }
  48735. },
  48736. enumerable: true,
  48737. configurable: true
  48738. });
  48739. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48740. get: function () {
  48741. return this._autoRotationBehavior;
  48742. },
  48743. enumerable: true,
  48744. configurable: true
  48745. });
  48746. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48747. get: function () {
  48748. return this._autoRotationBehavior != null;
  48749. },
  48750. set: function (value) {
  48751. if (value === this.useAutoRotationBehavior) {
  48752. return;
  48753. }
  48754. if (value) {
  48755. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48756. this.addBehavior(this._autoRotationBehavior);
  48757. }
  48758. else if (this._autoRotationBehavior) {
  48759. this.removeBehavior(this._autoRotationBehavior);
  48760. this._autoRotationBehavior = null;
  48761. }
  48762. },
  48763. enumerable: true,
  48764. configurable: true
  48765. });
  48766. // Cache
  48767. ArcRotateCamera.prototype._initCache = function () {
  48768. _super.prototype._initCache.call(this);
  48769. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48770. this._cache.alpha = undefined;
  48771. this._cache.beta = undefined;
  48772. this._cache.radius = undefined;
  48773. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48774. };
  48775. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48776. if (!ignoreParentClass) {
  48777. _super.prototype._updateCache.call(this);
  48778. }
  48779. this._cache._target.copyFrom(this._getTargetPosition());
  48780. this._cache.alpha = this.alpha;
  48781. this._cache.beta = this.beta;
  48782. this._cache.radius = this.radius;
  48783. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48784. };
  48785. ArcRotateCamera.prototype._getTargetPosition = function () {
  48786. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48787. var pos = this._targetHost.getAbsolutePosition();
  48788. if (this._targetBoundingCenter) {
  48789. pos.addToRef(this._targetBoundingCenter, this._target);
  48790. }
  48791. else {
  48792. this._target.copyFrom(pos);
  48793. }
  48794. }
  48795. var lockedTargetPosition = this._getLockedTargetPosition();
  48796. if (lockedTargetPosition) {
  48797. return lockedTargetPosition;
  48798. }
  48799. return this._target;
  48800. };
  48801. ArcRotateCamera.prototype.storeState = function () {
  48802. this._storedAlpha = this.alpha;
  48803. this._storedBeta = this.beta;
  48804. this._storedRadius = this.radius;
  48805. this._storedTarget = this._getTargetPosition().clone();
  48806. return _super.prototype.storeState.call(this);
  48807. };
  48808. /**
  48809. * Restored camera state. You must call storeState() first
  48810. */
  48811. ArcRotateCamera.prototype._restoreStateValues = function () {
  48812. if (!_super.prototype._restoreStateValues.call(this)) {
  48813. return false;
  48814. }
  48815. this.alpha = this._storedAlpha;
  48816. this.beta = this._storedBeta;
  48817. this.radius = this._storedRadius;
  48818. this.setTarget(this._storedTarget.clone());
  48819. this.inertialAlphaOffset = 0;
  48820. this.inertialBetaOffset = 0;
  48821. this.inertialRadiusOffset = 0;
  48822. this.inertialPanningX = 0;
  48823. this.inertialPanningY = 0;
  48824. return true;
  48825. };
  48826. // Synchronized
  48827. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48828. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48829. return false;
  48830. return this._cache._target.equals(this._getTargetPosition())
  48831. && this._cache.alpha === this.alpha
  48832. && this._cache.beta === this.beta
  48833. && this._cache.radius === this.radius
  48834. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48835. };
  48836. // Methods
  48837. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48838. var _this = this;
  48839. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48840. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48841. this._useCtrlForPanning = useCtrlForPanning;
  48842. this._panningMouseButton = panningMouseButton;
  48843. this.inputs.attachElement(element, noPreventDefault);
  48844. this._reset = function () {
  48845. _this.inertialAlphaOffset = 0;
  48846. _this.inertialBetaOffset = 0;
  48847. _this.inertialRadiusOffset = 0;
  48848. _this.inertialPanningX = 0;
  48849. _this.inertialPanningY = 0;
  48850. };
  48851. };
  48852. ArcRotateCamera.prototype.detachControl = function (element) {
  48853. this.inputs.detachElement(element);
  48854. if (this._reset) {
  48855. this._reset();
  48856. }
  48857. };
  48858. ArcRotateCamera.prototype._checkInputs = function () {
  48859. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48860. if (this._collisionTriggered) {
  48861. return;
  48862. }
  48863. this.inputs.checkInputs();
  48864. // Inertia
  48865. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48866. var inertialAlphaOffset = this.inertialAlphaOffset;
  48867. if (this.beta <= 0)
  48868. inertialAlphaOffset *= -1;
  48869. if (this.getScene().useRightHandedSystem)
  48870. inertialAlphaOffset *= -1;
  48871. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48872. inertialAlphaOffset *= -1;
  48873. this.alpha += inertialAlphaOffset;
  48874. this.beta += this.inertialBetaOffset;
  48875. this.radius -= this.inertialRadiusOffset;
  48876. this.inertialAlphaOffset *= this.inertia;
  48877. this.inertialBetaOffset *= this.inertia;
  48878. this.inertialRadiusOffset *= this.inertia;
  48879. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48880. this.inertialAlphaOffset = 0;
  48881. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48882. this.inertialBetaOffset = 0;
  48883. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48884. this.inertialRadiusOffset = 0;
  48885. }
  48886. // Panning inertia
  48887. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48888. if (!this._localDirection) {
  48889. this._localDirection = BABYLON.Vector3.Zero();
  48890. this._transformedDirection = BABYLON.Vector3.Zero();
  48891. }
  48892. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48893. this._localDirection.multiplyInPlace(this.panningAxis);
  48894. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48895. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48896. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48897. if (!this.panningAxis.y) {
  48898. this._transformedDirection.y = 0;
  48899. }
  48900. if (!this._targetHost) {
  48901. if (this.panningDistanceLimit) {
  48902. this._transformedDirection.addInPlace(this._target);
  48903. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48904. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48905. this._target.copyFrom(this._transformedDirection);
  48906. }
  48907. }
  48908. else {
  48909. this._target.addInPlace(this._transformedDirection);
  48910. }
  48911. }
  48912. this.inertialPanningX *= this.panningInertia;
  48913. this.inertialPanningY *= this.panningInertia;
  48914. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48915. this.inertialPanningX = 0;
  48916. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48917. this.inertialPanningY = 0;
  48918. }
  48919. // Limits
  48920. this._checkLimits();
  48921. _super.prototype._checkInputs.call(this);
  48922. };
  48923. ArcRotateCamera.prototype._checkLimits = function () {
  48924. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48925. if (this.allowUpsideDown && this.beta > Math.PI) {
  48926. this.beta = this.beta - (2 * Math.PI);
  48927. }
  48928. }
  48929. else {
  48930. if (this.beta < this.lowerBetaLimit) {
  48931. this.beta = this.lowerBetaLimit;
  48932. }
  48933. }
  48934. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48935. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48936. this.beta = this.beta + (2 * Math.PI);
  48937. }
  48938. }
  48939. else {
  48940. if (this.beta > this.upperBetaLimit) {
  48941. this.beta = this.upperBetaLimit;
  48942. }
  48943. }
  48944. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48945. this.alpha = this.lowerAlphaLimit;
  48946. }
  48947. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48948. this.alpha = this.upperAlphaLimit;
  48949. }
  48950. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48951. this.radius = this.lowerRadiusLimit;
  48952. }
  48953. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48954. this.radius = this.upperRadiusLimit;
  48955. }
  48956. };
  48957. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48958. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48959. this.radius = this._computationVector.length();
  48960. if (this.radius === 0) {
  48961. this.radius = 0.0001; // Just to avoid division by zero
  48962. }
  48963. // Alpha
  48964. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48965. if (this._computationVector.z < 0) {
  48966. this.alpha = 2 * Math.PI - this.alpha;
  48967. }
  48968. // Beta
  48969. this.beta = Math.acos(this._computationVector.y / this.radius);
  48970. this._checkLimits();
  48971. };
  48972. ArcRotateCamera.prototype.setPosition = function (position) {
  48973. if (this.position.equals(position)) {
  48974. return;
  48975. }
  48976. this.position.copyFrom(position);
  48977. this.rebuildAnglesAndRadius();
  48978. };
  48979. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48980. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48981. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48982. if (target.getBoundingInfo) {
  48983. if (toBoundingCenter) {
  48984. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48985. }
  48986. else {
  48987. this._targetBoundingCenter = null;
  48988. }
  48989. this._targetHost = target;
  48990. this._target = this._getTargetPosition();
  48991. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48992. }
  48993. else {
  48994. var newTarget = target;
  48995. var currentTarget = this._getTargetPosition();
  48996. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48997. return;
  48998. }
  48999. this._targetHost = null;
  49000. this._target = newTarget;
  49001. this._targetBoundingCenter = null;
  49002. this.onMeshTargetChangedObservable.notifyObservers(null);
  49003. }
  49004. this.rebuildAnglesAndRadius();
  49005. };
  49006. ArcRotateCamera.prototype._getViewMatrix = function () {
  49007. // Compute
  49008. var cosa = Math.cos(this.alpha);
  49009. var sina = Math.sin(this.alpha);
  49010. var cosb = Math.cos(this.beta);
  49011. var sinb = Math.sin(this.beta);
  49012. if (sinb === 0) {
  49013. sinb = 0.0001;
  49014. }
  49015. var target = this._getTargetPosition();
  49016. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49017. target.addToRef(this._computationVector, this._newPosition);
  49018. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49019. if (!this._collider) {
  49020. this._collider = new BABYLON.Collider();
  49021. }
  49022. this._collider._radius = this.collisionRadius;
  49023. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49024. this._collisionTriggered = true;
  49025. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49026. }
  49027. else {
  49028. this.position.copyFrom(this._newPosition);
  49029. var up = this.upVector;
  49030. if (this.allowUpsideDown && sinb < 0) {
  49031. up = up.clone();
  49032. up = up.negate();
  49033. }
  49034. this._computeViewMatrix(this.position, target, up);
  49035. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49036. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49037. }
  49038. this._currentTarget = target;
  49039. return this._viewMatrix;
  49040. };
  49041. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49042. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49043. meshes = meshes || this.getScene().meshes;
  49044. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49045. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49046. this.radius = distance * this.zoomOnFactor;
  49047. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49048. };
  49049. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49050. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49051. var meshesOrMinMaxVector;
  49052. var distance;
  49053. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49054. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49055. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49056. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49057. }
  49058. else { //minMaxVector and distance
  49059. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49060. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49061. distance = minMaxVectorAndDistance.distance;
  49062. }
  49063. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49064. if (!doNotUpdateMaxZ) {
  49065. this.maxZ = distance * 2;
  49066. }
  49067. };
  49068. /**
  49069. * @override
  49070. * Override Camera.createRigCamera
  49071. */
  49072. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49073. var alphaShift = 0;
  49074. switch (this.cameraRigMode) {
  49075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49078. case BABYLON.Camera.RIG_MODE_VR:
  49079. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49080. break;
  49081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49082. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49083. break;
  49084. }
  49085. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49086. rigCam._cameraRigParams = {};
  49087. return rigCam;
  49088. };
  49089. /**
  49090. * @override
  49091. * Override Camera._updateRigCameras
  49092. */
  49093. ArcRotateCamera.prototype._updateRigCameras = function () {
  49094. var camLeft = this._rigCameras[0];
  49095. var camRight = this._rigCameras[1];
  49096. camLeft.beta = camRight.beta = this.beta;
  49097. camLeft.radius = camRight.radius = this.radius;
  49098. switch (this.cameraRigMode) {
  49099. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49102. case BABYLON.Camera.RIG_MODE_VR:
  49103. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49104. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49105. break;
  49106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49107. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49108. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49109. break;
  49110. }
  49111. _super.prototype._updateRigCameras.call(this);
  49112. };
  49113. ArcRotateCamera.prototype.dispose = function () {
  49114. this.inputs.clear();
  49115. _super.prototype.dispose.call(this);
  49116. };
  49117. ArcRotateCamera.prototype.getClassName = function () {
  49118. return "ArcRotateCamera";
  49119. };
  49120. __decorate([
  49121. BABYLON.serialize()
  49122. ], ArcRotateCamera.prototype, "alpha", void 0);
  49123. __decorate([
  49124. BABYLON.serialize()
  49125. ], ArcRotateCamera.prototype, "beta", void 0);
  49126. __decorate([
  49127. BABYLON.serialize()
  49128. ], ArcRotateCamera.prototype, "radius", void 0);
  49129. __decorate([
  49130. BABYLON.serializeAsVector3("target")
  49131. ], ArcRotateCamera.prototype, "_target", void 0);
  49132. __decorate([
  49133. BABYLON.serialize()
  49134. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49135. __decorate([
  49136. BABYLON.serialize()
  49137. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49138. __decorate([
  49139. BABYLON.serialize()
  49140. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49141. __decorate([
  49142. BABYLON.serialize()
  49143. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49144. __decorate([
  49145. BABYLON.serialize()
  49146. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49147. __decorate([
  49148. BABYLON.serialize()
  49149. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49150. __decorate([
  49151. BABYLON.serialize()
  49152. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49153. __decorate([
  49154. BABYLON.serialize()
  49155. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49156. __decorate([
  49157. BABYLON.serialize()
  49158. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49159. __decorate([
  49160. BABYLON.serialize()
  49161. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49162. __decorate([
  49163. BABYLON.serialize()
  49164. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49165. __decorate([
  49166. BABYLON.serialize()
  49167. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49171. __decorate([
  49172. BABYLON.serializeAsVector3()
  49173. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49174. __decorate([
  49175. BABYLON.serialize()
  49176. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49177. __decorate([
  49178. BABYLON.serialize()
  49179. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49180. __decorate([
  49181. BABYLON.serialize()
  49182. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49183. return ArcRotateCamera;
  49184. }(BABYLON.TargetCamera));
  49185. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49186. })(BABYLON || (BABYLON = {}));
  49187. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49188. var BABYLON;
  49189. (function (BABYLON) {
  49190. /**
  49191. * The HemisphericLight simulates the ambient environment light,
  49192. * so the passed direction is the light reflection direction, not the incoming direction.
  49193. */
  49194. var HemisphericLight = /** @class */ (function (_super) {
  49195. __extends(HemisphericLight, _super);
  49196. /**
  49197. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49198. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49199. * The HemisphericLight can't cast shadows.
  49200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49201. * @param name The friendly name of the light
  49202. * @param direction The direction of the light reflection
  49203. * @param scene The scene the light belongs to
  49204. */
  49205. function HemisphericLight(name, direction, scene) {
  49206. var _this = _super.call(this, name, scene) || this;
  49207. /**
  49208. * The groundColor is the light in the opposite direction to the one specified during creation.
  49209. * 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.
  49210. */
  49211. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49212. _this.direction = direction || BABYLON.Vector3.Up();
  49213. return _this;
  49214. }
  49215. HemisphericLight.prototype._buildUniformLayout = function () {
  49216. this._uniformBuffer.addUniform("vLightData", 4);
  49217. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49218. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49219. this._uniformBuffer.addUniform("vLightGround", 3);
  49220. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49221. this._uniformBuffer.addUniform("depthValues", 2);
  49222. this._uniformBuffer.create();
  49223. };
  49224. /**
  49225. * Returns the string "HemisphericLight".
  49226. * @return The class name
  49227. */
  49228. HemisphericLight.prototype.getClassName = function () {
  49229. return "HemisphericLight";
  49230. };
  49231. /**
  49232. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49233. * Returns the updated direction.
  49234. * @param target The target the direction should point to
  49235. * @return The computed direction
  49236. */
  49237. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49238. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49239. return this.direction;
  49240. };
  49241. /**
  49242. * Returns the shadow generator associated to the light.
  49243. * @returns Always null for hemispheric lights because it does not support shadows.
  49244. */
  49245. HemisphericLight.prototype.getShadowGenerator = function () {
  49246. return null;
  49247. };
  49248. /**
  49249. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49250. * @param effect The effect to update
  49251. * @param lightIndex The index of the light in the effect to update
  49252. * @returns The hemispheric light
  49253. */
  49254. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49255. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49256. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49257. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49258. return this;
  49259. };
  49260. /**
  49261. * @hidden internal use only.
  49262. */
  49263. HemisphericLight.prototype._getWorldMatrix = function () {
  49264. if (!this._worldMatrix) {
  49265. this._worldMatrix = BABYLON.Matrix.Identity();
  49266. }
  49267. return this._worldMatrix;
  49268. };
  49269. /**
  49270. * Returns the integer 3.
  49271. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49272. */
  49273. HemisphericLight.prototype.getTypeID = function () {
  49274. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49275. };
  49276. __decorate([
  49277. BABYLON.serializeAsColor3()
  49278. ], HemisphericLight.prototype, "groundColor", void 0);
  49279. __decorate([
  49280. BABYLON.serializeAsVector3()
  49281. ], HemisphericLight.prototype, "direction", void 0);
  49282. return HemisphericLight;
  49283. }(BABYLON.Light));
  49284. BABYLON.HemisphericLight = HemisphericLight;
  49285. })(BABYLON || (BABYLON = {}));
  49286. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49287. var BABYLON;
  49288. (function (BABYLON) {
  49289. /**
  49290. * Base implementation IShadowLight
  49291. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49292. */
  49293. var ShadowLight = /** @class */ (function (_super) {
  49294. __extends(ShadowLight, _super);
  49295. function ShadowLight() {
  49296. var _this = _super !== null && _super.apply(this, arguments) || this;
  49297. _this._needProjectionMatrixCompute = true;
  49298. return _this;
  49299. }
  49300. ShadowLight.prototype._setPosition = function (value) {
  49301. this._position = value;
  49302. };
  49303. Object.defineProperty(ShadowLight.prototype, "position", {
  49304. /**
  49305. * Sets the position the shadow will be casted from. Also use as the light position for both
  49306. * point and spot lights.
  49307. */
  49308. get: function () {
  49309. return this._position;
  49310. },
  49311. /**
  49312. * Sets the position the shadow will be casted from. Also use as the light position for both
  49313. * point and spot lights.
  49314. */
  49315. set: function (value) {
  49316. this._setPosition(value);
  49317. },
  49318. enumerable: true,
  49319. configurable: true
  49320. });
  49321. ShadowLight.prototype._setDirection = function (value) {
  49322. this._direction = value;
  49323. };
  49324. Object.defineProperty(ShadowLight.prototype, "direction", {
  49325. /**
  49326. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49327. * Also use as the light direction on spot and directional lights.
  49328. */
  49329. get: function () {
  49330. return this._direction;
  49331. },
  49332. /**
  49333. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49334. * Also use as the light direction on spot and directional lights.
  49335. */
  49336. set: function (value) {
  49337. this._setDirection(value);
  49338. },
  49339. enumerable: true,
  49340. configurable: true
  49341. });
  49342. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49343. /**
  49344. * Gets the shadow projection clipping minimum z value.
  49345. */
  49346. get: function () {
  49347. return this._shadowMinZ;
  49348. },
  49349. /**
  49350. * Sets the shadow projection clipping minimum z value.
  49351. */
  49352. set: function (value) {
  49353. this._shadowMinZ = value;
  49354. this.forceProjectionMatrixCompute();
  49355. },
  49356. enumerable: true,
  49357. configurable: true
  49358. });
  49359. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49360. /**
  49361. * Sets the shadow projection clipping maximum z value.
  49362. */
  49363. get: function () {
  49364. return this._shadowMaxZ;
  49365. },
  49366. /**
  49367. * Gets the shadow projection clipping maximum z value.
  49368. */
  49369. set: function (value) {
  49370. this._shadowMaxZ = value;
  49371. this.forceProjectionMatrixCompute();
  49372. },
  49373. enumerable: true,
  49374. configurable: true
  49375. });
  49376. /**
  49377. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49378. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49379. */
  49380. ShadowLight.prototype.computeTransformedInformation = function () {
  49381. if (this.parent && this.parent.getWorldMatrix) {
  49382. if (!this.transformedPosition) {
  49383. this.transformedPosition = BABYLON.Vector3.Zero();
  49384. }
  49385. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49386. // In case the direction is present.
  49387. if (this.direction) {
  49388. if (!this.transformedDirection) {
  49389. this.transformedDirection = BABYLON.Vector3.Zero();
  49390. }
  49391. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49392. }
  49393. return true;
  49394. }
  49395. return false;
  49396. };
  49397. /**
  49398. * Return the depth scale used for the shadow map.
  49399. * @returns the depth scale.
  49400. */
  49401. ShadowLight.prototype.getDepthScale = function () {
  49402. return 50.0;
  49403. };
  49404. /**
  49405. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49406. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49407. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49408. */
  49409. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49410. return this.transformedDirection ? this.transformedDirection : this.direction;
  49411. };
  49412. /**
  49413. * Returns the ShadowLight absolute position in the World.
  49414. * @returns the position vector in world space
  49415. */
  49416. ShadowLight.prototype.getAbsolutePosition = function () {
  49417. return this.transformedPosition ? this.transformedPosition : this.position;
  49418. };
  49419. /**
  49420. * Sets the ShadowLight direction toward the passed target.
  49421. * @param target The point tot target in local space
  49422. * @returns the updated ShadowLight direction
  49423. */
  49424. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49425. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49426. return this.direction;
  49427. };
  49428. /**
  49429. * Returns the light rotation in euler definition.
  49430. * @returns the x y z rotation in local space.
  49431. */
  49432. ShadowLight.prototype.getRotation = function () {
  49433. this.direction.normalize();
  49434. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49435. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49436. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49437. };
  49438. /**
  49439. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49440. * @returns true if a cube texture needs to be use
  49441. */
  49442. ShadowLight.prototype.needCube = function () {
  49443. return false;
  49444. };
  49445. /**
  49446. * Detects if the projection matrix requires to be recomputed this frame.
  49447. * @returns true if it requires to be recomputed otherwise, false.
  49448. */
  49449. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49450. return this._needProjectionMatrixCompute;
  49451. };
  49452. /**
  49453. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49454. */
  49455. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49456. this._needProjectionMatrixCompute = true;
  49457. };
  49458. /**
  49459. * Get the world matrix of the sahdow lights.
  49460. * @hidden Internal Use Only
  49461. */
  49462. ShadowLight.prototype._getWorldMatrix = function () {
  49463. if (!this._worldMatrix) {
  49464. this._worldMatrix = BABYLON.Matrix.Identity();
  49465. }
  49466. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49467. return this._worldMatrix;
  49468. };
  49469. /**
  49470. * Gets the minZ used for shadow according to both the scene and the light.
  49471. * @param activeCamera The camera we are returning the min for
  49472. * @returns the depth min z
  49473. */
  49474. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49475. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49476. };
  49477. /**
  49478. * Gets the maxZ used for shadow according to both the scene and the light.
  49479. * @param activeCamera The camera we are returning the max for
  49480. * @returns the depth max z
  49481. */
  49482. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49483. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49484. };
  49485. /**
  49486. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49487. * @param matrix The materix to updated with the projection information
  49488. * @param viewMatrix The transform matrix of the light
  49489. * @param renderList The list of mesh to render in the map
  49490. * @returns The current light
  49491. */
  49492. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49493. if (this.customProjectionMatrixBuilder) {
  49494. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49495. }
  49496. else {
  49497. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49498. }
  49499. return this;
  49500. };
  49501. __decorate([
  49502. BABYLON.serializeAsVector3()
  49503. ], ShadowLight.prototype, "position", null);
  49504. __decorate([
  49505. BABYLON.serializeAsVector3()
  49506. ], ShadowLight.prototype, "direction", null);
  49507. __decorate([
  49508. BABYLON.serialize()
  49509. ], ShadowLight.prototype, "shadowMinZ", null);
  49510. __decorate([
  49511. BABYLON.serialize()
  49512. ], ShadowLight.prototype, "shadowMaxZ", null);
  49513. return ShadowLight;
  49514. }(BABYLON.Light));
  49515. BABYLON.ShadowLight = ShadowLight;
  49516. })(BABYLON || (BABYLON = {}));
  49517. //# sourceMappingURL=babylon.shadowLight.js.map
  49518. var BABYLON;
  49519. (function (BABYLON) {
  49520. /**
  49521. * A point light is a light defined by an unique point in world space.
  49522. * The light is emitted in every direction from this point.
  49523. * A good example of a point light is a standard light bulb.
  49524. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49525. */
  49526. var PointLight = /** @class */ (function (_super) {
  49527. __extends(PointLight, _super);
  49528. /**
  49529. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49530. * A PointLight emits the light in every direction.
  49531. * It can cast shadows.
  49532. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49533. * ```javascript
  49534. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49535. * ```
  49536. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49537. * @param name The light friendly name
  49538. * @param position The position of the point light in the scene
  49539. * @param scene The scene the lights belongs to
  49540. */
  49541. function PointLight(name, position, scene) {
  49542. var _this = _super.call(this, name, scene) || this;
  49543. _this._shadowAngle = Math.PI / 2;
  49544. _this.position = position;
  49545. return _this;
  49546. }
  49547. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49548. /**
  49549. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49550. * This specifies what angle the shadow will use to be created.
  49551. *
  49552. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49553. */
  49554. get: function () {
  49555. return this._shadowAngle;
  49556. },
  49557. /**
  49558. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49559. * This specifies what angle the shadow will use to be created.
  49560. *
  49561. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49562. */
  49563. set: function (value) {
  49564. this._shadowAngle = value;
  49565. this.forceProjectionMatrixCompute();
  49566. },
  49567. enumerable: true,
  49568. configurable: true
  49569. });
  49570. Object.defineProperty(PointLight.prototype, "direction", {
  49571. /**
  49572. * Gets the direction if it has been set.
  49573. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49574. */
  49575. get: function () {
  49576. return this._direction;
  49577. },
  49578. /**
  49579. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49580. */
  49581. set: function (value) {
  49582. var previousNeedCube = this.needCube();
  49583. this._direction = value;
  49584. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49585. this._shadowGenerator.recreateShadowMap();
  49586. }
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. /**
  49592. * Returns the string "PointLight"
  49593. * @returns the class name
  49594. */
  49595. PointLight.prototype.getClassName = function () {
  49596. return "PointLight";
  49597. };
  49598. /**
  49599. * Returns the integer 0.
  49600. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49601. */
  49602. PointLight.prototype.getTypeID = function () {
  49603. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49604. };
  49605. /**
  49606. * Specifies wether or not the shadowmap should be a cube texture.
  49607. * @returns true if the shadowmap needs to be a cube texture.
  49608. */
  49609. PointLight.prototype.needCube = function () {
  49610. return !this.direction;
  49611. };
  49612. /**
  49613. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49614. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49615. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49616. */
  49617. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49618. if (this.direction) {
  49619. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49620. }
  49621. else {
  49622. switch (faceIndex) {
  49623. case 0:
  49624. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49625. case 1:
  49626. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49627. case 2:
  49628. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49629. case 3:
  49630. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49631. case 4:
  49632. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49633. case 5:
  49634. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49635. }
  49636. }
  49637. return BABYLON.Vector3.Zero();
  49638. };
  49639. /**
  49640. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49641. * - fov = PI / 2
  49642. * - aspect ratio : 1.0
  49643. * - z-near and far equal to the active camera minZ and maxZ.
  49644. * Returns the PointLight.
  49645. */
  49646. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49647. var activeCamera = this.getScene().activeCamera;
  49648. if (!activeCamera) {
  49649. return;
  49650. }
  49651. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49652. };
  49653. PointLight.prototype._buildUniformLayout = function () {
  49654. this._uniformBuffer.addUniform("vLightData", 4);
  49655. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49656. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49657. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49658. this._uniformBuffer.addUniform("depthValues", 2);
  49659. this._uniformBuffer.create();
  49660. };
  49661. /**
  49662. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49663. * @param effect The effect to update
  49664. * @param lightIndex The index of the light in the effect to update
  49665. * @returns The point light
  49666. */
  49667. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49668. if (this.computeTransformedInformation()) {
  49669. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49670. return this;
  49671. }
  49672. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49673. return this;
  49674. };
  49675. __decorate([
  49676. BABYLON.serialize()
  49677. ], PointLight.prototype, "shadowAngle", null);
  49678. return PointLight;
  49679. }(BABYLON.ShadowLight));
  49680. BABYLON.PointLight = PointLight;
  49681. })(BABYLON || (BABYLON = {}));
  49682. //# sourceMappingURL=babylon.pointLight.js.map
  49683. var BABYLON;
  49684. (function (BABYLON) {
  49685. /**
  49686. * A directional light is defined by a direction (what a surprise!).
  49687. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49688. * 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.
  49689. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49690. */
  49691. var DirectionalLight = /** @class */ (function (_super) {
  49692. __extends(DirectionalLight, _super);
  49693. /**
  49694. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49695. * The directional light is emitted from everywhere in the given direction.
  49696. * It can cast shawdows.
  49697. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49698. * @param name The friendly name of the light
  49699. * @param direction The direction of the light
  49700. * @param scene The scene the light belongs to
  49701. */
  49702. function DirectionalLight(name, direction, scene) {
  49703. var _this = _super.call(this, name, scene) || this;
  49704. _this._shadowFrustumSize = 0;
  49705. _this._shadowOrthoScale = 0.1;
  49706. /**
  49707. * Automatically compute the projection matrix to best fit (including all the casters)
  49708. * on each frame.
  49709. */
  49710. _this.autoUpdateExtends = true;
  49711. // Cache
  49712. _this._orthoLeft = Number.MAX_VALUE;
  49713. _this._orthoRight = Number.MIN_VALUE;
  49714. _this._orthoTop = Number.MIN_VALUE;
  49715. _this._orthoBottom = Number.MAX_VALUE;
  49716. _this.position = direction.scale(-1.0);
  49717. _this.direction = direction;
  49718. return _this;
  49719. }
  49720. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49721. /**
  49722. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49723. */
  49724. get: function () {
  49725. return this._shadowFrustumSize;
  49726. },
  49727. /**
  49728. * Specifies a fix frustum size for the shadow generation.
  49729. */
  49730. set: function (value) {
  49731. this._shadowFrustumSize = value;
  49732. this.forceProjectionMatrixCompute();
  49733. },
  49734. enumerable: true,
  49735. configurable: true
  49736. });
  49737. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49738. /**
  49739. * Gets the shadow projection scale against the optimal computed one.
  49740. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49741. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49742. */
  49743. get: function () {
  49744. return this._shadowOrthoScale;
  49745. },
  49746. /**
  49747. * Sets the shadow projection scale against the optimal computed one.
  49748. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49749. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49750. */
  49751. set: function (value) {
  49752. this._shadowOrthoScale = value;
  49753. this.forceProjectionMatrixCompute();
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. /**
  49759. * Returns the string "DirectionalLight".
  49760. * @return The class name
  49761. */
  49762. DirectionalLight.prototype.getClassName = function () {
  49763. return "DirectionalLight";
  49764. };
  49765. /**
  49766. * Returns the integer 1.
  49767. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49768. */
  49769. DirectionalLight.prototype.getTypeID = function () {
  49770. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49771. };
  49772. /**
  49773. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49774. * Returns the DirectionalLight Shadow projection matrix.
  49775. */
  49776. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49777. if (this.shadowFrustumSize > 0) {
  49778. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49779. }
  49780. else {
  49781. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49782. }
  49783. };
  49784. /**
  49785. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49786. * Returns the DirectionalLight Shadow projection matrix.
  49787. */
  49788. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49789. var activeCamera = this.getScene().activeCamera;
  49790. if (!activeCamera) {
  49791. return;
  49792. }
  49793. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49794. };
  49795. /**
  49796. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49797. * Returns the DirectionalLight Shadow projection matrix.
  49798. */
  49799. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49800. var activeCamera = this.getScene().activeCamera;
  49801. if (!activeCamera) {
  49802. return;
  49803. }
  49804. // Check extends
  49805. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49806. var tempVector3 = BABYLON.Vector3.Zero();
  49807. this._orthoLeft = Number.MAX_VALUE;
  49808. this._orthoRight = Number.MIN_VALUE;
  49809. this._orthoTop = Number.MIN_VALUE;
  49810. this._orthoBottom = Number.MAX_VALUE;
  49811. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49812. var mesh = renderList[meshIndex];
  49813. if (!mesh) {
  49814. continue;
  49815. }
  49816. var boundingInfo = mesh.getBoundingInfo();
  49817. var boundingBox = boundingInfo.boundingBox;
  49818. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49819. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49820. if (tempVector3.x < this._orthoLeft)
  49821. this._orthoLeft = tempVector3.x;
  49822. if (tempVector3.y < this._orthoBottom)
  49823. this._orthoBottom = tempVector3.y;
  49824. if (tempVector3.x > this._orthoRight)
  49825. this._orthoRight = tempVector3.x;
  49826. if (tempVector3.y > this._orthoTop)
  49827. this._orthoTop = tempVector3.y;
  49828. }
  49829. }
  49830. }
  49831. var xOffset = this._orthoRight - this._orthoLeft;
  49832. var yOffset = this._orthoTop - this._orthoBottom;
  49833. 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);
  49834. };
  49835. DirectionalLight.prototype._buildUniformLayout = function () {
  49836. this._uniformBuffer.addUniform("vLightData", 4);
  49837. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49838. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49839. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49840. this._uniformBuffer.addUniform("depthValues", 2);
  49841. this._uniformBuffer.create();
  49842. };
  49843. /**
  49844. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49845. * @param effect The effect to update
  49846. * @param lightIndex The index of the light in the effect to update
  49847. * @returns The directional light
  49848. */
  49849. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49850. if (this.computeTransformedInformation()) {
  49851. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49852. return this;
  49853. }
  49854. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49855. return this;
  49856. };
  49857. /**
  49858. * Gets the minZ used for shadow according to both the scene and the light.
  49859. *
  49860. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49861. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49862. * @param activeCamera The camera we are returning the min for
  49863. * @returns the depth min z
  49864. */
  49865. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49866. return 1;
  49867. };
  49868. /**
  49869. * Gets the maxZ used for shadow according to both the scene and the light.
  49870. *
  49871. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49872. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49873. * @param activeCamera The camera we are returning the max for
  49874. * @returns the depth max z
  49875. */
  49876. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49877. return 1;
  49878. };
  49879. __decorate([
  49880. BABYLON.serialize()
  49881. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49882. __decorate([
  49883. BABYLON.serialize()
  49884. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49885. __decorate([
  49886. BABYLON.serialize()
  49887. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49888. return DirectionalLight;
  49889. }(BABYLON.ShadowLight));
  49890. BABYLON.DirectionalLight = DirectionalLight;
  49891. })(BABYLON || (BABYLON = {}));
  49892. //# sourceMappingURL=babylon.directionalLight.js.map
  49893. var BABYLON;
  49894. (function (BABYLON) {
  49895. /**
  49896. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49897. * These values define a cone of light starting from the position, emitting toward the direction.
  49898. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49899. * and the exponent defines the speed of the decay of the light with distance (reach).
  49900. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49901. */
  49902. var SpotLight = /** @class */ (function (_super) {
  49903. __extends(SpotLight, _super);
  49904. /**
  49905. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49906. * It can cast shadows.
  49907. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49908. * @param name The light friendly name
  49909. * @param position The position of the spot light in the scene
  49910. * @param direction The direction of the light in the scene
  49911. * @param angle The cone angle of the light in Radians
  49912. * @param exponent The light decay speed with the distance from the emission spot
  49913. * @param scene The scene the lights belongs to
  49914. */
  49915. function SpotLight(name, position, direction, angle, exponent, scene) {
  49916. var _this = _super.call(this, name, scene) || this;
  49917. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49918. _this._projectionTextureLightNear = 1e-6;
  49919. _this._projectionTextureLightFar = 1000.0;
  49920. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49921. _this._projectionTextureViewLightDirty = true;
  49922. _this._projectionTextureProjectionLightDirty = true;
  49923. _this._projectionTextureDirty = true;
  49924. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49925. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49926. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49927. _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);
  49928. _this.position = position;
  49929. _this.direction = direction;
  49930. _this.angle = angle;
  49931. _this.exponent = exponent;
  49932. return _this;
  49933. }
  49934. Object.defineProperty(SpotLight.prototype, "angle", {
  49935. /**
  49936. * Gets the cone angle of the spot light in Radians.
  49937. */
  49938. get: function () {
  49939. return this._angle;
  49940. },
  49941. /**
  49942. * Sets the cone angle of the spot light in Radians.
  49943. */
  49944. set: function (value) {
  49945. this._angle = value;
  49946. this._projectionTextureProjectionLightDirty = true;
  49947. this.forceProjectionMatrixCompute();
  49948. },
  49949. enumerable: true,
  49950. configurable: true
  49951. });
  49952. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49953. /**
  49954. * Allows scaling the angle of the light for shadow generation only.
  49955. */
  49956. get: function () {
  49957. return this._shadowAngleScale;
  49958. },
  49959. /**
  49960. * Allows scaling the angle of the light for shadow generation only.
  49961. */
  49962. set: function (value) {
  49963. this._shadowAngleScale = value;
  49964. this.forceProjectionMatrixCompute();
  49965. },
  49966. enumerable: true,
  49967. configurable: true
  49968. });
  49969. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49970. /**
  49971. * Allows reading the projecton texture
  49972. */
  49973. get: function () {
  49974. return this._projectionTextureMatrix;
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49980. /**
  49981. * Gets the near clip of the Spotlight for texture projection.
  49982. */
  49983. get: function () {
  49984. return this._projectionTextureLightNear;
  49985. },
  49986. /**
  49987. * Sets the near clip of the Spotlight for texture projection.
  49988. */
  49989. set: function (value) {
  49990. this._projectionTextureLightNear = value;
  49991. this._projectionTextureProjectionLightDirty = true;
  49992. },
  49993. enumerable: true,
  49994. configurable: true
  49995. });
  49996. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49997. /**
  49998. * Gets the far clip of the Spotlight for texture projection.
  49999. */
  50000. get: function () {
  50001. return this._projectionTextureLightFar;
  50002. },
  50003. /**
  50004. * Sets the far clip of the Spotlight for texture projection.
  50005. */
  50006. set: function (value) {
  50007. this._projectionTextureLightFar = value;
  50008. this._projectionTextureProjectionLightDirty = true;
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50014. /**
  50015. * Gets the Up vector of the Spotlight for texture projection.
  50016. */
  50017. get: function () {
  50018. return this._projectionTextureUpDirection;
  50019. },
  50020. /**
  50021. * Sets the Up vector of the Spotlight for texture projection.
  50022. */
  50023. set: function (value) {
  50024. this._projectionTextureUpDirection = value;
  50025. this._projectionTextureProjectionLightDirty = true;
  50026. },
  50027. enumerable: true,
  50028. configurable: true
  50029. });
  50030. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50031. /**
  50032. * Gets the projection texture of the light.
  50033. */
  50034. get: function () {
  50035. return this._projectionTexture;
  50036. },
  50037. /**
  50038. * Sets the projection texture of the light.
  50039. */
  50040. set: function (value) {
  50041. this._projectionTexture = value;
  50042. this._projectionTextureDirty = true;
  50043. },
  50044. enumerable: true,
  50045. configurable: true
  50046. });
  50047. /**
  50048. * Returns the string "SpotLight".
  50049. * @returns the class name
  50050. */
  50051. SpotLight.prototype.getClassName = function () {
  50052. return "SpotLight";
  50053. };
  50054. /**
  50055. * Returns the integer 2.
  50056. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50057. */
  50058. SpotLight.prototype.getTypeID = function () {
  50059. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50060. };
  50061. /**
  50062. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50063. */
  50064. SpotLight.prototype._setDirection = function (value) {
  50065. _super.prototype._setDirection.call(this, value);
  50066. this._projectionTextureViewLightDirty = true;
  50067. };
  50068. /**
  50069. * Overrides the position setter to recompute the projection texture view light Matrix.
  50070. */
  50071. SpotLight.prototype._setPosition = function (value) {
  50072. _super.prototype._setPosition.call(this, value);
  50073. this._projectionTextureViewLightDirty = true;
  50074. };
  50075. /**
  50076. * 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.
  50077. * Returns the SpotLight.
  50078. */
  50079. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50080. var activeCamera = this.getScene().activeCamera;
  50081. if (!activeCamera) {
  50082. return;
  50083. }
  50084. this._shadowAngleScale = this._shadowAngleScale || 1;
  50085. var angle = this._shadowAngleScale * this._angle;
  50086. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50087. };
  50088. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50089. this._projectionTextureViewLightDirty = false;
  50090. this._projectionTextureDirty = true;
  50091. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50092. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50093. };
  50094. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50095. this._projectionTextureProjectionLightDirty = false;
  50096. this._projectionTextureDirty = true;
  50097. var light_far = this.projectionTextureLightFar;
  50098. var light_near = this.projectionTextureLightNear;
  50099. var P = light_far / (light_far - light_near);
  50100. var Q = -P * light_near;
  50101. var S = 1.0 / Math.tan(this._angle / 2.0);
  50102. var A = 1.0;
  50103. 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);
  50104. };
  50105. /**
  50106. * Main function for light texture projection matrix computing.
  50107. */
  50108. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50109. this._projectionTextureDirty = false;
  50110. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50111. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50112. };
  50113. SpotLight.prototype._buildUniformLayout = function () {
  50114. this._uniformBuffer.addUniform("vLightData", 4);
  50115. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50116. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50117. this._uniformBuffer.addUniform("vLightDirection", 3);
  50118. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50119. this._uniformBuffer.addUniform("depthValues", 2);
  50120. this._uniformBuffer.create();
  50121. };
  50122. /**
  50123. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50124. * @param effect The effect to update
  50125. * @param lightIndex The index of the light in the effect to update
  50126. * @returns The spot light
  50127. */
  50128. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50129. var normalizeDirection;
  50130. if (this.computeTransformedInformation()) {
  50131. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50132. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50133. }
  50134. else {
  50135. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50136. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50137. }
  50138. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50139. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50140. if (this._projectionTextureViewLightDirty) {
  50141. this._computeProjectionTextureViewLightMatrix();
  50142. }
  50143. if (this._projectionTextureProjectionLightDirty) {
  50144. this._computeProjectionTextureProjectionLightMatrix();
  50145. }
  50146. if (this._projectionTextureDirty) {
  50147. this._computeProjectionTextureMatrix();
  50148. }
  50149. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50150. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50151. }
  50152. return this;
  50153. };
  50154. /**
  50155. * Disposes the light and the associated resources.
  50156. */
  50157. SpotLight.prototype.dispose = function () {
  50158. _super.prototype.dispose.call(this);
  50159. if (this._projectionTexture) {
  50160. this._projectionTexture.dispose();
  50161. }
  50162. };
  50163. __decorate([
  50164. BABYLON.serialize()
  50165. ], SpotLight.prototype, "angle", null);
  50166. __decorate([
  50167. BABYLON.serialize()
  50168. ], SpotLight.prototype, "shadowAngleScale", null);
  50169. __decorate([
  50170. BABYLON.serialize()
  50171. ], SpotLight.prototype, "exponent", void 0);
  50172. __decorate([
  50173. BABYLON.serialize()
  50174. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50175. __decorate([
  50176. BABYLON.serialize()
  50177. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50178. __decorate([
  50179. BABYLON.serialize()
  50180. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50181. __decorate([
  50182. BABYLON.serializeAsTexture("projectedLightTexture")
  50183. ], SpotLight.prototype, "_projectionTexture", void 0);
  50184. return SpotLight;
  50185. }(BABYLON.ShadowLight));
  50186. BABYLON.SpotLight = SpotLight;
  50187. })(BABYLON || (BABYLON = {}));
  50188. //# sourceMappingURL=babylon.spotLight.js.map
  50189. var BABYLON;
  50190. (function (BABYLON) {
  50191. /**
  50192. * Class used to override all child animations of a given target
  50193. */
  50194. var AnimationPropertiesOverride = /** @class */ (function () {
  50195. function AnimationPropertiesOverride() {
  50196. /**
  50197. * Gets or sets a value indicating if animation blending must be used
  50198. */
  50199. this.enableBlending = false;
  50200. /**
  50201. * Gets or sets the blending speed to use when enableBlending is true
  50202. */
  50203. this.blendingSpeed = 0.01;
  50204. /**
  50205. * Gets or sets the default loop mode to use
  50206. */
  50207. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50208. }
  50209. return AnimationPropertiesOverride;
  50210. }());
  50211. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50212. })(BABYLON || (BABYLON = {}));
  50213. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50214. var BABYLON;
  50215. (function (BABYLON) {
  50216. /**
  50217. * Represents the range of an animation
  50218. */
  50219. var AnimationRange = /** @class */ (function () {
  50220. /**
  50221. * Initializes the range of an animation
  50222. * @param name The name of the animation range
  50223. * @param from The starting frame of the animation
  50224. * @param to The ending frame of the animation
  50225. */
  50226. function AnimationRange(
  50227. /**The name of the animation range**/
  50228. name,
  50229. /**The starting frame of the animation */
  50230. from,
  50231. /**The ending frame of the animation*/
  50232. to) {
  50233. this.name = name;
  50234. this.from = from;
  50235. this.to = to;
  50236. }
  50237. /**
  50238. * Makes a copy of the animation range
  50239. * @returns A copy of the animation range
  50240. */
  50241. AnimationRange.prototype.clone = function () {
  50242. return new AnimationRange(this.name, this.from, this.to);
  50243. };
  50244. return AnimationRange;
  50245. }());
  50246. BABYLON.AnimationRange = AnimationRange;
  50247. /**
  50248. * Composed of a frame, and an action function
  50249. */
  50250. var AnimationEvent = /** @class */ (function () {
  50251. /**
  50252. * Initializes the animation event
  50253. * @param frame The frame for which the event is triggered
  50254. * @param action The event to perform when triggered
  50255. * @param onlyOnce Specifies if the event should be triggered only once
  50256. */
  50257. function AnimationEvent(
  50258. /** The frame for which the event is triggered **/
  50259. frame,
  50260. /** The event to perform when triggered **/
  50261. action,
  50262. /** Specifies if the event should be triggered only once**/
  50263. onlyOnce) {
  50264. this.frame = frame;
  50265. this.action = action;
  50266. this.onlyOnce = onlyOnce;
  50267. /**
  50268. * Specifies if the animation event is done
  50269. */
  50270. this.isDone = false;
  50271. }
  50272. return AnimationEvent;
  50273. }());
  50274. BABYLON.AnimationEvent = AnimationEvent;
  50275. /**
  50276. * A cursor which tracks a point on a path
  50277. */
  50278. var PathCursor = /** @class */ (function () {
  50279. /**
  50280. * Initializes the path cursor
  50281. * @param path The path to track
  50282. */
  50283. function PathCursor(path) {
  50284. this.path = path;
  50285. /**
  50286. * Stores path cursor callbacks for when an onchange event is triggered
  50287. */
  50288. this._onchange = new Array();
  50289. /**
  50290. * The value of the path cursor
  50291. */
  50292. this.value = 0;
  50293. /**
  50294. * The animation array of the path cursor
  50295. */
  50296. this.animations = new Array();
  50297. }
  50298. /**
  50299. * Gets the cursor point on the path
  50300. * @returns A point on the path cursor at the cursor location
  50301. */
  50302. PathCursor.prototype.getPoint = function () {
  50303. var point = this.path.getPointAtLengthPosition(this.value);
  50304. return new BABYLON.Vector3(point.x, 0, point.y);
  50305. };
  50306. /**
  50307. * Moves the cursor ahead by the step amount
  50308. * @param step The amount to move the cursor forward
  50309. * @returns This path cursor
  50310. */
  50311. PathCursor.prototype.moveAhead = function (step) {
  50312. if (step === void 0) { step = 0.002; }
  50313. this.move(step);
  50314. return this;
  50315. };
  50316. /**
  50317. * Moves the cursor behind by the step amount
  50318. * @param step The amount to move the cursor back
  50319. * @returns This path cursor
  50320. */
  50321. PathCursor.prototype.moveBack = function (step) {
  50322. if (step === void 0) { step = 0.002; }
  50323. this.move(-step);
  50324. return this;
  50325. };
  50326. /**
  50327. * Moves the cursor by the step amount
  50328. * If the step amount is greater than one, an exception is thrown
  50329. * @param step The amount to move the cursor
  50330. * @returns This path cursor
  50331. */
  50332. PathCursor.prototype.move = function (step) {
  50333. if (Math.abs(step) > 1) {
  50334. throw "step size should be less than 1.";
  50335. }
  50336. this.value += step;
  50337. this.ensureLimits();
  50338. this.raiseOnChange();
  50339. return this;
  50340. };
  50341. /**
  50342. * Ensures that the value is limited between zero and one
  50343. * @returns This path cursor
  50344. */
  50345. PathCursor.prototype.ensureLimits = function () {
  50346. while (this.value > 1) {
  50347. this.value -= 1;
  50348. }
  50349. while (this.value < 0) {
  50350. this.value += 1;
  50351. }
  50352. return this;
  50353. };
  50354. /**
  50355. * Runs onchange callbacks on change (used by the animation engine)
  50356. * @returns This path cursor
  50357. */
  50358. PathCursor.prototype.raiseOnChange = function () {
  50359. var _this = this;
  50360. this._onchange.forEach(function (f) { return f(_this); });
  50361. return this;
  50362. };
  50363. /**
  50364. * Executes a function on change
  50365. * @param f A path cursor onchange callback
  50366. * @returns This path cursor
  50367. */
  50368. PathCursor.prototype.onchange = function (f) {
  50369. this._onchange.push(f);
  50370. return this;
  50371. };
  50372. return PathCursor;
  50373. }());
  50374. BABYLON.PathCursor = PathCursor;
  50375. /**
  50376. * Enum for the animation key frame interpolation type
  50377. */
  50378. var AnimationKeyInterpolation;
  50379. (function (AnimationKeyInterpolation) {
  50380. /**
  50381. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50382. */
  50383. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50384. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50385. /**
  50386. * Class used to store any kind of animation
  50387. */
  50388. var Animation = /** @class */ (function () {
  50389. /**
  50390. * Initializes the animation
  50391. * @param name Name of the animation
  50392. * @param targetProperty Property to animate
  50393. * @param framePerSecond The frames per second of the animation
  50394. * @param dataType The data type of the animation
  50395. * @param loopMode The loop mode of the animation
  50396. * @param enableBlendings Specifies if blending should be enabled
  50397. */
  50398. function Animation(
  50399. /**Name of the animation */
  50400. name,
  50401. /**Property to animate */
  50402. targetProperty,
  50403. /**The frames per second of the animation */
  50404. framePerSecond,
  50405. /**The data type of the animation */
  50406. dataType,
  50407. /**The loop mode of the animation */
  50408. loopMode,
  50409. /**Specifies if blending should be enabled */
  50410. enableBlending) {
  50411. this.name = name;
  50412. this.targetProperty = targetProperty;
  50413. this.framePerSecond = framePerSecond;
  50414. this.dataType = dataType;
  50415. this.loopMode = loopMode;
  50416. this.enableBlending = enableBlending;
  50417. /**
  50418. * @hidden Internal use only
  50419. */
  50420. this._runtimeAnimations = new Array();
  50421. /**
  50422. * The set of event that will be linked to this animation
  50423. */
  50424. this._events = new Array();
  50425. /**
  50426. * Stores the blending speed of the animation
  50427. */
  50428. this.blendingSpeed = 0.01;
  50429. /**
  50430. * Stores the animation ranges for the animation
  50431. */
  50432. this._ranges = {};
  50433. this.targetPropertyPath = targetProperty.split(".");
  50434. this.dataType = dataType;
  50435. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50436. }
  50437. /**
  50438. * @hidden Internal use
  50439. */
  50440. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50441. var dataType = undefined;
  50442. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50443. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50444. }
  50445. else if (from instanceof BABYLON.Quaternion) {
  50446. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50447. }
  50448. else if (from instanceof BABYLON.Vector3) {
  50449. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50450. }
  50451. else if (from instanceof BABYLON.Vector2) {
  50452. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50453. }
  50454. else if (from instanceof BABYLON.Color3) {
  50455. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50456. }
  50457. else if (from instanceof BABYLON.Size) {
  50458. dataType = Animation.ANIMATIONTYPE_SIZE;
  50459. }
  50460. if (dataType == undefined) {
  50461. return null;
  50462. }
  50463. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50464. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50465. animation.setKeys(keys);
  50466. if (easingFunction !== undefined) {
  50467. animation.setEasingFunction(easingFunction);
  50468. }
  50469. return animation;
  50470. };
  50471. /**
  50472. * Sets up an animation
  50473. * @param property The property to animate
  50474. * @param animationType The animation type to apply
  50475. * @param framePerSecond The frames per second of the animation
  50476. * @param easingFunction The easing function used in the animation
  50477. * @returns The created animation
  50478. */
  50479. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50480. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50481. animation.setEasingFunction(easingFunction);
  50482. return animation;
  50483. };
  50484. /**
  50485. * Create and start an animation on a node
  50486. * @param name defines the name of the global animation that will be run on all nodes
  50487. * @param node defines the root node where the animation will take place
  50488. * @param targetProperty defines property to animate
  50489. * @param framePerSecond defines the number of frame per second yo use
  50490. * @param totalFrame defines the number of frames in total
  50491. * @param from defines the initial value
  50492. * @param to defines the final value
  50493. * @param loopMode defines which loop mode you want to use (off by default)
  50494. * @param easingFunction defines the easing function to use (linear by default)
  50495. * @param onAnimationEnd defines the callback to call when animation end
  50496. * @returns the animatable created for this animation
  50497. */
  50498. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50499. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50500. if (!animation) {
  50501. return null;
  50502. }
  50503. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50504. };
  50505. /**
  50506. * Create and start an animation on a node and its descendants
  50507. * @param name defines the name of the global animation that will be run on all nodes
  50508. * @param node defines the root node where the animation will take place
  50509. * @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
  50510. * @param targetProperty defines property to animate
  50511. * @param framePerSecond defines the number of frame per second to use
  50512. * @param totalFrame defines the number of frames in total
  50513. * @param from defines the initial value
  50514. * @param to defines the final value
  50515. * @param loopMode defines which loop mode you want to use (off by default)
  50516. * @param easingFunction defines the easing function to use (linear by default)
  50517. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50518. * @returns the list of animatables created for all nodes
  50519. * @example https://www.babylonjs-playground.com/#MH0VLI
  50520. */
  50521. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50522. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50523. if (!animation) {
  50524. return null;
  50525. }
  50526. var scene = node.getScene();
  50527. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50528. };
  50529. /**
  50530. * Creates a new animation, merges it with the existing animations and starts it
  50531. * @param name Name of the animation
  50532. * @param node Node which contains the scene that begins the animations
  50533. * @param targetProperty Specifies which property to animate
  50534. * @param framePerSecond The frames per second of the animation
  50535. * @param totalFrame The total number of frames
  50536. * @param from The frame at the beginning of the animation
  50537. * @param to The frame at the end of the animation
  50538. * @param loopMode Specifies the loop mode of the animation
  50539. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50540. * @param onAnimationEnd Callback to run once the animation is complete
  50541. * @returns Nullable animation
  50542. */
  50543. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50544. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50545. if (!animation) {
  50546. return null;
  50547. }
  50548. node.animations.push(animation);
  50549. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50550. };
  50551. /**
  50552. * Transition property of the Camera to the target Value
  50553. * @param property The property to transition
  50554. * @param targetValue The target Value of the property
  50555. * @param host The object where the property to animate belongs
  50556. * @param scene Scene used to run the animation
  50557. * @param frameRate Framerate (in frame/s) to use
  50558. * @param transition The transition type we want to use
  50559. * @param duration The duration of the animation, in milliseconds
  50560. * @param onAnimationEnd Callback trigger at the end of the animation
  50561. * @returns Nullable animation
  50562. */
  50563. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50564. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50565. if (duration <= 0) {
  50566. host[property] = targetValue;
  50567. if (onAnimationEnd) {
  50568. onAnimationEnd();
  50569. }
  50570. return null;
  50571. }
  50572. var endFrame = frameRate * (duration / 1000);
  50573. transition.setKeys([{
  50574. frame: 0,
  50575. value: host[property].clone ? host[property].clone() : host[property]
  50576. },
  50577. {
  50578. frame: endFrame,
  50579. value: targetValue
  50580. }]);
  50581. if (!host.animations) {
  50582. host.animations = [];
  50583. }
  50584. host.animations.push(transition);
  50585. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50586. animation.onAnimationEnd = onAnimationEnd;
  50587. return animation;
  50588. };
  50589. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50590. /**
  50591. * Return the array of runtime animations currently using this animation
  50592. */
  50593. get: function () {
  50594. return this._runtimeAnimations;
  50595. },
  50596. enumerable: true,
  50597. configurable: true
  50598. });
  50599. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50600. /**
  50601. * Specifies if any of the runtime animations are currently running
  50602. */
  50603. get: function () {
  50604. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50605. var runtimeAnimation = _a[_i];
  50606. if (!runtimeAnimation.isStopped) {
  50607. return true;
  50608. }
  50609. }
  50610. return false;
  50611. },
  50612. enumerable: true,
  50613. configurable: true
  50614. });
  50615. // Methods
  50616. /**
  50617. * Converts the animation to a string
  50618. * @param fullDetails support for multiple levels of logging within scene loading
  50619. * @returns String form of the animation
  50620. */
  50621. Animation.prototype.toString = function (fullDetails) {
  50622. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50623. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50624. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50625. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50626. if (fullDetails) {
  50627. ret += ", Ranges: {";
  50628. var first = true;
  50629. for (var name in this._ranges) {
  50630. if (first) {
  50631. ret += ", ";
  50632. first = false;
  50633. }
  50634. ret += name;
  50635. }
  50636. ret += "}";
  50637. }
  50638. return ret;
  50639. };
  50640. /**
  50641. * Add an event to this animation
  50642. * @param event Event to add
  50643. */
  50644. Animation.prototype.addEvent = function (event) {
  50645. this._events.push(event);
  50646. };
  50647. /**
  50648. * Remove all events found at the given frame
  50649. * @param frame The frame to remove events from
  50650. */
  50651. Animation.prototype.removeEvents = function (frame) {
  50652. for (var index = 0; index < this._events.length; index++) {
  50653. if (this._events[index].frame === frame) {
  50654. this._events.splice(index, 1);
  50655. index--;
  50656. }
  50657. }
  50658. };
  50659. /**
  50660. * Retrieves all the events from the animation
  50661. * @returns Events from the animation
  50662. */
  50663. Animation.prototype.getEvents = function () {
  50664. return this._events;
  50665. };
  50666. /**
  50667. * Creates an animation range
  50668. * @param name Name of the animation range
  50669. * @param from Starting frame of the animation range
  50670. * @param to Ending frame of the animation
  50671. */
  50672. Animation.prototype.createRange = function (name, from, to) {
  50673. // check name not already in use; could happen for bones after serialized
  50674. if (!this._ranges[name]) {
  50675. this._ranges[name] = new AnimationRange(name, from, to);
  50676. }
  50677. };
  50678. /**
  50679. * Deletes an animation range by name
  50680. * @param name Name of the animation range to delete
  50681. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50682. */
  50683. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50684. if (deleteFrames === void 0) { deleteFrames = true; }
  50685. var range = this._ranges[name];
  50686. if (!range) {
  50687. return;
  50688. }
  50689. if (deleteFrames) {
  50690. var from = range.from;
  50691. var to = range.to;
  50692. // this loop MUST go high to low for multiple splices to work
  50693. for (var key = this._keys.length - 1; key >= 0; key--) {
  50694. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50695. this._keys.splice(key, 1);
  50696. }
  50697. }
  50698. }
  50699. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50700. };
  50701. /**
  50702. * Gets the animation range by name, or null if not defined
  50703. * @param name Name of the animation range
  50704. * @returns Nullable animation range
  50705. */
  50706. Animation.prototype.getRange = function (name) {
  50707. return this._ranges[name];
  50708. };
  50709. /**
  50710. * Gets the key frames from the animation
  50711. * @returns The key frames of the animation
  50712. */
  50713. Animation.prototype.getKeys = function () {
  50714. return this._keys;
  50715. };
  50716. /**
  50717. * Gets the highest frame rate of the animation
  50718. * @returns Highest frame rate of the animation
  50719. */
  50720. Animation.prototype.getHighestFrame = function () {
  50721. var ret = 0;
  50722. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50723. if (ret < this._keys[key].frame) {
  50724. ret = this._keys[key].frame;
  50725. }
  50726. }
  50727. return ret;
  50728. };
  50729. /**
  50730. * Gets the easing function of the animation
  50731. * @returns Easing function of the animation
  50732. */
  50733. Animation.prototype.getEasingFunction = function () {
  50734. return this._easingFunction;
  50735. };
  50736. /**
  50737. * Sets the easing function of the animation
  50738. * @param easingFunction A custom mathematical formula for animation
  50739. */
  50740. Animation.prototype.setEasingFunction = function (easingFunction) {
  50741. this._easingFunction = easingFunction;
  50742. };
  50743. /**
  50744. * Interpolates a scalar linearly
  50745. * @param startValue Start value of the animation curve
  50746. * @param endValue End value of the animation curve
  50747. * @param gradient Scalar amount to interpolate
  50748. * @returns Interpolated scalar value
  50749. */
  50750. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50751. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50752. };
  50753. /**
  50754. * Interpolates a scalar cubically
  50755. * @param startValue Start value of the animation curve
  50756. * @param outTangent End tangent of the animation
  50757. * @param endValue End value of the animation curve
  50758. * @param inTangent Start tangent of the animation curve
  50759. * @param gradient Scalar amount to interpolate
  50760. * @returns Interpolated scalar value
  50761. */
  50762. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50763. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50764. };
  50765. /**
  50766. * Interpolates a quaternion using a spherical linear interpolation
  50767. * @param startValue Start value of the animation curve
  50768. * @param endValue End value of the animation curve
  50769. * @param gradient Scalar amount to interpolate
  50770. * @returns Interpolated quaternion value
  50771. */
  50772. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50773. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50774. };
  50775. /**
  50776. * Interpolates a quaternion cubically
  50777. * @param startValue Start value of the animation curve
  50778. * @param outTangent End tangent of the animation curve
  50779. * @param endValue End value of the animation curve
  50780. * @param inTangent Start tangent of the animation curve
  50781. * @param gradient Scalar amount to interpolate
  50782. * @returns Interpolated quaternion value
  50783. */
  50784. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50785. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50786. };
  50787. /**
  50788. * Interpolates a Vector3 linearl
  50789. * @param startValue Start value of the animation curve
  50790. * @param endValue End value of the animation curve
  50791. * @param gradient Scalar amount to interpolate
  50792. * @returns Interpolated scalar value
  50793. */
  50794. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50795. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50796. };
  50797. /**
  50798. * Interpolates a Vector3 cubically
  50799. * @param startValue Start value of the animation curve
  50800. * @param outTangent End tangent of the animation
  50801. * @param endValue End value of the animation curve
  50802. * @param inTangent Start tangent of the animation curve
  50803. * @param gradient Scalar amount to interpolate
  50804. * @returns InterpolatedVector3 value
  50805. */
  50806. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50807. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50808. };
  50809. /**
  50810. * Interpolates a Vector2 linearly
  50811. * @param startValue Start value of the animation curve
  50812. * @param endValue End value of the animation curve
  50813. * @param gradient Scalar amount to interpolate
  50814. * @returns Interpolated Vector2 value
  50815. */
  50816. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50817. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50818. };
  50819. /**
  50820. * Interpolates a Vector2 cubically
  50821. * @param startValue Start value of the animation curve
  50822. * @param outTangent End tangent of the animation
  50823. * @param endValue End value of the animation curve
  50824. * @param inTangent Start tangent of the animation curve
  50825. * @param gradient Scalar amount to interpolate
  50826. * @returns Interpolated Vector2 value
  50827. */
  50828. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50829. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50830. };
  50831. /**
  50832. * Interpolates a size linearly
  50833. * @param startValue Start value of the animation curve
  50834. * @param endValue End value of the animation curve
  50835. * @param gradient Scalar amount to interpolate
  50836. * @returns Interpolated Size value
  50837. */
  50838. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50839. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50840. };
  50841. /**
  50842. * Interpolates a Color3 linearly
  50843. * @param startValue Start value of the animation curve
  50844. * @param endValue End value of the animation curve
  50845. * @param gradient Scalar amount to interpolate
  50846. * @returns Interpolated Color3 value
  50847. */
  50848. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50849. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50850. };
  50851. /**
  50852. * @hidden Internal use only
  50853. */
  50854. Animation.prototype._getKeyValue = function (value) {
  50855. if (typeof value === "function") {
  50856. return value();
  50857. }
  50858. return value;
  50859. };
  50860. /**
  50861. * @hidden Internal use only
  50862. */
  50863. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50864. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50865. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50866. }
  50867. var keys = this.getKeys();
  50868. // Try to get a hash to find the right key
  50869. 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));
  50870. if (keys[startKeyIndex].frame >= currentFrame) {
  50871. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50872. startKeyIndex--;
  50873. }
  50874. }
  50875. for (var key = startKeyIndex; key < keys.length; key++) {
  50876. var endKey = keys[key + 1];
  50877. if (endKey.frame >= currentFrame) {
  50878. var startKey = keys[key];
  50879. var startValue = this._getKeyValue(startKey.value);
  50880. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50881. return startValue;
  50882. }
  50883. var endValue = this._getKeyValue(endKey.value);
  50884. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50885. var frameDelta = endKey.frame - startKey.frame;
  50886. // gradient : percent of currentFrame between the frame inf and the frame sup
  50887. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50888. // check for easingFunction and correction of gradient
  50889. var easingFunction = this.getEasingFunction();
  50890. if (easingFunction != null) {
  50891. gradient = easingFunction.ease(gradient);
  50892. }
  50893. switch (this.dataType) {
  50894. // Float
  50895. case Animation.ANIMATIONTYPE_FLOAT:
  50896. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50897. switch (loopMode) {
  50898. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50899. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50900. return floatValue;
  50901. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50902. return offsetValue * repeatCount + floatValue;
  50903. }
  50904. break;
  50905. // Quaternion
  50906. case Animation.ANIMATIONTYPE_QUATERNION:
  50907. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50908. switch (loopMode) {
  50909. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50910. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50911. return quatValue;
  50912. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50913. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50914. }
  50915. return quatValue;
  50916. // Vector3
  50917. case Animation.ANIMATIONTYPE_VECTOR3:
  50918. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50919. switch (loopMode) {
  50920. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50921. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50922. return vec3Value;
  50923. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50924. return vec3Value.add(offsetValue.scale(repeatCount));
  50925. }
  50926. // Vector2
  50927. case Animation.ANIMATIONTYPE_VECTOR2:
  50928. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50929. switch (loopMode) {
  50930. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50931. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50932. return vec2Value;
  50933. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50934. return vec2Value.add(offsetValue.scale(repeatCount));
  50935. }
  50936. // Size
  50937. case Animation.ANIMATIONTYPE_SIZE:
  50938. switch (loopMode) {
  50939. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50940. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50941. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50942. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50943. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50944. }
  50945. // Color3
  50946. case Animation.ANIMATIONTYPE_COLOR3:
  50947. switch (loopMode) {
  50948. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50949. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50950. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50951. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50952. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50953. }
  50954. // Matrix
  50955. case Animation.ANIMATIONTYPE_MATRIX:
  50956. switch (loopMode) {
  50957. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50958. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50959. if (Animation.AllowMatricesInterpolation) {
  50960. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50961. }
  50962. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50963. return startValue;
  50964. }
  50965. default:
  50966. break;
  50967. }
  50968. break;
  50969. }
  50970. }
  50971. return this._getKeyValue(keys[keys.length - 1].value);
  50972. };
  50973. /**
  50974. * Defines the function to use to interpolate matrices
  50975. * @param startValue defines the start matrix
  50976. * @param endValue defines the end matrix
  50977. * @param gradient defines the gradient between both matrices
  50978. * @param result defines an optional target matrix where to store the interpolation
  50979. * @returns the interpolated matrix
  50980. */
  50981. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50982. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50983. if (result) {
  50984. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50985. return result;
  50986. }
  50987. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50988. }
  50989. if (result) {
  50990. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50991. return result;
  50992. }
  50993. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50994. };
  50995. /**
  50996. * Makes a copy of the animation
  50997. * @returns Cloned animation
  50998. */
  50999. Animation.prototype.clone = function () {
  51000. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51001. clone.enableBlending = this.enableBlending;
  51002. clone.blendingSpeed = this.blendingSpeed;
  51003. if (this._keys) {
  51004. clone.setKeys(this._keys);
  51005. }
  51006. if (this._ranges) {
  51007. clone._ranges = {};
  51008. for (var name in this._ranges) {
  51009. var range = this._ranges[name];
  51010. if (!range) {
  51011. continue;
  51012. }
  51013. clone._ranges[name] = range.clone();
  51014. }
  51015. }
  51016. return clone;
  51017. };
  51018. /**
  51019. * Sets the key frames of the animation
  51020. * @param values The animation key frames to set
  51021. */
  51022. Animation.prototype.setKeys = function (values) {
  51023. this._keys = values.slice(0);
  51024. };
  51025. /**
  51026. * Serializes the animation to an object
  51027. * @returns Serialized object
  51028. */
  51029. Animation.prototype.serialize = function () {
  51030. var serializationObject = {};
  51031. serializationObject.name = this.name;
  51032. serializationObject.property = this.targetProperty;
  51033. serializationObject.framePerSecond = this.framePerSecond;
  51034. serializationObject.dataType = this.dataType;
  51035. serializationObject.loopBehavior = this.loopMode;
  51036. serializationObject.enableBlending = this.enableBlending;
  51037. serializationObject.blendingSpeed = this.blendingSpeed;
  51038. var dataType = this.dataType;
  51039. serializationObject.keys = [];
  51040. var keys = this.getKeys();
  51041. for (var index = 0; index < keys.length; index++) {
  51042. var animationKey = keys[index];
  51043. var key = {};
  51044. key.frame = animationKey.frame;
  51045. switch (dataType) {
  51046. case Animation.ANIMATIONTYPE_FLOAT:
  51047. key.values = [animationKey.value];
  51048. break;
  51049. case Animation.ANIMATIONTYPE_QUATERNION:
  51050. case Animation.ANIMATIONTYPE_MATRIX:
  51051. case Animation.ANIMATIONTYPE_VECTOR3:
  51052. case Animation.ANIMATIONTYPE_COLOR3:
  51053. key.values = animationKey.value.asArray();
  51054. break;
  51055. }
  51056. serializationObject.keys.push(key);
  51057. }
  51058. serializationObject.ranges = [];
  51059. for (var name in this._ranges) {
  51060. var source = this._ranges[name];
  51061. if (!source) {
  51062. continue;
  51063. }
  51064. var range = {};
  51065. range.name = name;
  51066. range.from = source.from;
  51067. range.to = source.to;
  51068. serializationObject.ranges.push(range);
  51069. }
  51070. return serializationObject;
  51071. };
  51072. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51073. /**
  51074. * Get the float animation type
  51075. */
  51076. get: function () {
  51077. return Animation._ANIMATIONTYPE_FLOAT;
  51078. },
  51079. enumerable: true,
  51080. configurable: true
  51081. });
  51082. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51083. /**
  51084. * Get the Vector3 animation type
  51085. */
  51086. get: function () {
  51087. return Animation._ANIMATIONTYPE_VECTOR3;
  51088. },
  51089. enumerable: true,
  51090. configurable: true
  51091. });
  51092. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51093. /**
  51094. * Get the Vectpr2 animation type
  51095. */
  51096. get: function () {
  51097. return Animation._ANIMATIONTYPE_VECTOR2;
  51098. },
  51099. enumerable: true,
  51100. configurable: true
  51101. });
  51102. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51103. /**
  51104. * Get the Size animation type
  51105. */
  51106. get: function () {
  51107. return Animation._ANIMATIONTYPE_SIZE;
  51108. },
  51109. enumerable: true,
  51110. configurable: true
  51111. });
  51112. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51113. /**
  51114. * Get the Quaternion animation type
  51115. */
  51116. get: function () {
  51117. return Animation._ANIMATIONTYPE_QUATERNION;
  51118. },
  51119. enumerable: true,
  51120. configurable: true
  51121. });
  51122. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51123. /**
  51124. * Get the Matrix animation type
  51125. */
  51126. get: function () {
  51127. return Animation._ANIMATIONTYPE_MATRIX;
  51128. },
  51129. enumerable: true,
  51130. configurable: true
  51131. });
  51132. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51133. /**
  51134. * Get the Color3 animation type
  51135. */
  51136. get: function () {
  51137. return Animation._ANIMATIONTYPE_COLOR3;
  51138. },
  51139. enumerable: true,
  51140. configurable: true
  51141. });
  51142. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51143. /**
  51144. * Get the Relative Loop Mode
  51145. */
  51146. get: function () {
  51147. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51148. },
  51149. enumerable: true,
  51150. configurable: true
  51151. });
  51152. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51153. /**
  51154. * Get the Cycle Loop Mode
  51155. */
  51156. get: function () {
  51157. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51158. },
  51159. enumerable: true,
  51160. configurable: true
  51161. });
  51162. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51163. /**
  51164. * Get the Constant Loop Mode
  51165. */
  51166. get: function () {
  51167. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51168. },
  51169. enumerable: true,
  51170. configurable: true
  51171. });
  51172. /** @hidden */
  51173. Animation._UniversalLerp = function (left, right, amount) {
  51174. var constructor = left.constructor;
  51175. if (constructor.Lerp) { // Lerp supported
  51176. return constructor.Lerp(left, right, amount);
  51177. }
  51178. else if (constructor.Slerp) { // Slerp supported
  51179. return constructor.Slerp(left, right, amount);
  51180. }
  51181. else if (left.toFixed) { // Number
  51182. return left * (1.0 - amount) + amount * right;
  51183. }
  51184. else { // Blending not supported
  51185. return right;
  51186. }
  51187. };
  51188. /**
  51189. * Parses an animation object and creates an animation
  51190. * @param parsedAnimation Parsed animation object
  51191. * @returns Animation object
  51192. */
  51193. Animation.Parse = function (parsedAnimation) {
  51194. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51195. var dataType = parsedAnimation.dataType;
  51196. var keys = [];
  51197. var data;
  51198. var index;
  51199. if (parsedAnimation.enableBlending) {
  51200. animation.enableBlending = parsedAnimation.enableBlending;
  51201. }
  51202. if (parsedAnimation.blendingSpeed) {
  51203. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51204. }
  51205. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51206. var key = parsedAnimation.keys[index];
  51207. var inTangent;
  51208. var outTangent;
  51209. switch (dataType) {
  51210. case Animation.ANIMATIONTYPE_FLOAT:
  51211. data = key.values[0];
  51212. if (key.values.length >= 1) {
  51213. inTangent = key.values[1];
  51214. }
  51215. if (key.values.length >= 2) {
  51216. outTangent = key.values[2];
  51217. }
  51218. break;
  51219. case Animation.ANIMATIONTYPE_QUATERNION:
  51220. data = BABYLON.Quaternion.FromArray(key.values);
  51221. if (key.values.length >= 8) {
  51222. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51223. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51224. inTangent = _inTangent;
  51225. }
  51226. }
  51227. if (key.values.length >= 12) {
  51228. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51229. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51230. outTangent = _outTangent;
  51231. }
  51232. }
  51233. break;
  51234. case Animation.ANIMATIONTYPE_MATRIX:
  51235. data = BABYLON.Matrix.FromArray(key.values);
  51236. break;
  51237. case Animation.ANIMATIONTYPE_COLOR3:
  51238. data = BABYLON.Color3.FromArray(key.values);
  51239. break;
  51240. case Animation.ANIMATIONTYPE_VECTOR3:
  51241. default:
  51242. data = BABYLON.Vector3.FromArray(key.values);
  51243. break;
  51244. }
  51245. var keyData = {};
  51246. keyData.frame = key.frame;
  51247. keyData.value = data;
  51248. if (inTangent != undefined) {
  51249. keyData.inTangent = inTangent;
  51250. }
  51251. if (outTangent != undefined) {
  51252. keyData.outTangent = outTangent;
  51253. }
  51254. keys.push(keyData);
  51255. }
  51256. animation.setKeys(keys);
  51257. if (parsedAnimation.ranges) {
  51258. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51259. data = parsedAnimation.ranges[index];
  51260. animation.createRange(data.name, data.from, data.to);
  51261. }
  51262. }
  51263. return animation;
  51264. };
  51265. /**
  51266. * Appends the serialized animations from the source animations
  51267. * @param source Source containing the animations
  51268. * @param destination Target to store the animations
  51269. */
  51270. Animation.AppendSerializedAnimations = function (source, destination) {
  51271. if (source.animations) {
  51272. destination.animations = [];
  51273. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51274. var animation = source.animations[animationIndex];
  51275. destination.animations.push(animation.serialize());
  51276. }
  51277. }
  51278. };
  51279. /**
  51280. * Use matrix interpolation instead of using direct key value when animating matrices
  51281. */
  51282. Animation.AllowMatricesInterpolation = false;
  51283. /**
  51284. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51285. */
  51286. Animation.AllowMatrixDecomposeForInterpolation = true;
  51287. // Statics
  51288. /**
  51289. * Float animation type
  51290. */
  51291. Animation._ANIMATIONTYPE_FLOAT = 0;
  51292. /**
  51293. * Vector3 animation type
  51294. */
  51295. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51296. /**
  51297. * Quaternion animation type
  51298. */
  51299. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51300. /**
  51301. * Matrix animation type
  51302. */
  51303. Animation._ANIMATIONTYPE_MATRIX = 3;
  51304. /**
  51305. * Color3 animation type
  51306. */
  51307. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51308. /**
  51309. * Vector2 animation type
  51310. */
  51311. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51312. /**
  51313. * Size animation type
  51314. */
  51315. Animation._ANIMATIONTYPE_SIZE = 6;
  51316. /**
  51317. * Relative Loop Mode
  51318. */
  51319. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51320. /**
  51321. * Cycle Loop Mode
  51322. */
  51323. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51324. /**
  51325. * Constant Loop Mode
  51326. */
  51327. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51328. return Animation;
  51329. }());
  51330. BABYLON.Animation = Animation;
  51331. })(BABYLON || (BABYLON = {}));
  51332. //# sourceMappingURL=babylon.animation.js.map
  51333. var BABYLON;
  51334. (function (BABYLON) {
  51335. /**
  51336. * This class defines the direct association between an animation and a target
  51337. */
  51338. var TargetedAnimation = /** @class */ (function () {
  51339. function TargetedAnimation() {
  51340. }
  51341. return TargetedAnimation;
  51342. }());
  51343. BABYLON.TargetedAnimation = TargetedAnimation;
  51344. /**
  51345. * Use this class to create coordinated animations on multiple targets
  51346. */
  51347. var AnimationGroup = /** @class */ (function () {
  51348. function AnimationGroup(name, scene) {
  51349. if (scene === void 0) { scene = null; }
  51350. this.name = name;
  51351. this._targetedAnimations = new Array();
  51352. this._animatables = new Array();
  51353. this._from = Number.MAX_VALUE;
  51354. this._to = -Number.MAX_VALUE;
  51355. this._speedRatio = 1;
  51356. this.onAnimationEndObservable = new BABYLON.Observable();
  51357. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51358. this._scene.animationGroups.push(this);
  51359. }
  51360. Object.defineProperty(AnimationGroup.prototype, "from", {
  51361. /**
  51362. * Gets the first frame
  51363. */
  51364. get: function () {
  51365. return this._from;
  51366. },
  51367. enumerable: true,
  51368. configurable: true
  51369. });
  51370. Object.defineProperty(AnimationGroup.prototype, "to", {
  51371. /**
  51372. * Gets the last frame
  51373. */
  51374. get: function () {
  51375. return this._to;
  51376. },
  51377. enumerable: true,
  51378. configurable: true
  51379. });
  51380. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51381. /**
  51382. * Define if the animations are started
  51383. */
  51384. get: function () {
  51385. return this._isStarted;
  51386. },
  51387. enumerable: true,
  51388. configurable: true
  51389. });
  51390. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51391. /**
  51392. * Gets or sets the speed ratio to use for all animations
  51393. */
  51394. get: function () {
  51395. return this._speedRatio;
  51396. },
  51397. /**
  51398. * Gets or sets the speed ratio to use for all animations
  51399. */
  51400. set: function (value) {
  51401. if (this._speedRatio === value) {
  51402. return;
  51403. }
  51404. this._speedRatio = value;
  51405. for (var index = 0; index < this._animatables.length; index++) {
  51406. var animatable = this._animatables[index];
  51407. animatable.speedRatio = this._speedRatio;
  51408. }
  51409. },
  51410. enumerable: true,
  51411. configurable: true
  51412. });
  51413. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51414. /**
  51415. * Gets the targeted animations for this animation group
  51416. */
  51417. get: function () {
  51418. return this._targetedAnimations;
  51419. },
  51420. enumerable: true,
  51421. configurable: true
  51422. });
  51423. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51424. /**
  51425. * returning the list of animatables controlled by this animation group.
  51426. */
  51427. get: function () {
  51428. return this._animatables;
  51429. },
  51430. enumerable: true,
  51431. configurable: true
  51432. });
  51433. /**
  51434. * Add an animation (with its target) in the group
  51435. * @param animation defines the animation we want to add
  51436. * @param target defines the target of the animation
  51437. * @returns the {BABYLON.TargetedAnimation} object
  51438. */
  51439. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51440. var targetedAnimation = {
  51441. animation: animation,
  51442. target: target
  51443. };
  51444. var keys = animation.getKeys();
  51445. if (this._from > keys[0].frame) {
  51446. this._from = keys[0].frame;
  51447. }
  51448. if (this._to < keys[keys.length - 1].frame) {
  51449. this._to = keys[keys.length - 1].frame;
  51450. }
  51451. this._targetedAnimations.push(targetedAnimation);
  51452. return targetedAnimation;
  51453. };
  51454. /**
  51455. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51456. * It can add constant keys at begin or end
  51457. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51458. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51459. */
  51460. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51461. if (beginFrame === void 0) { beginFrame = null; }
  51462. if (endFrame === void 0) { endFrame = null; }
  51463. if (beginFrame == null)
  51464. beginFrame = this._from;
  51465. if (endFrame == null)
  51466. endFrame = this._to;
  51467. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51468. var targetedAnimation = this._targetedAnimations[index];
  51469. var keys = targetedAnimation.animation.getKeys();
  51470. var startKey = keys[0];
  51471. var endKey = keys[keys.length - 1];
  51472. if (startKey.frame > beginFrame) {
  51473. var newKey = {
  51474. frame: beginFrame,
  51475. value: startKey.value,
  51476. inTangent: startKey.inTangent,
  51477. outTangent: startKey.outTangent,
  51478. interpolation: startKey.interpolation
  51479. };
  51480. keys.splice(0, 0, newKey);
  51481. }
  51482. if (endKey.frame < endFrame) {
  51483. var newKey = {
  51484. frame: endFrame,
  51485. value: endKey.value,
  51486. inTangent: endKey.outTangent,
  51487. outTangent: endKey.outTangent,
  51488. interpolation: endKey.interpolation
  51489. };
  51490. keys.push(newKey);
  51491. }
  51492. }
  51493. this._from = beginFrame;
  51494. this._to = endFrame;
  51495. return this;
  51496. };
  51497. /**
  51498. * Start all animations on given targets
  51499. * @param loop defines if animations must loop
  51500. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51501. * @param from defines the from key (optional)
  51502. * @param to defines the to key (optional)
  51503. * @returns the current animation group
  51504. */
  51505. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51506. var _this = this;
  51507. if (loop === void 0) { loop = false; }
  51508. if (speedRatio === void 0) { speedRatio = 1; }
  51509. if (this._isStarted || this._targetedAnimations.length === 0) {
  51510. return this;
  51511. }
  51512. var _loop_1 = function (targetedAnimation) {
  51513. 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 () {
  51514. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51515. }));
  51516. };
  51517. var this_1 = this;
  51518. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51519. var targetedAnimation = _a[_i];
  51520. _loop_1(targetedAnimation);
  51521. }
  51522. this._speedRatio = speedRatio;
  51523. this._isStarted = true;
  51524. return this;
  51525. };
  51526. /**
  51527. * Pause all animations
  51528. */
  51529. AnimationGroup.prototype.pause = function () {
  51530. if (!this._isStarted) {
  51531. return this;
  51532. }
  51533. for (var index = 0; index < this._animatables.length; index++) {
  51534. var animatable = this._animatables[index];
  51535. animatable.pause();
  51536. }
  51537. return this;
  51538. };
  51539. /**
  51540. * Play all animations to initial state
  51541. * This function will start() the animations if they were not started or will restart() them if they were paused
  51542. * @param loop defines if animations must loop
  51543. */
  51544. AnimationGroup.prototype.play = function (loop) {
  51545. if (this.isStarted) {
  51546. if (loop !== undefined) {
  51547. for (var index = 0; index < this._animatables.length; index++) {
  51548. var animatable = this._animatables[index];
  51549. animatable.loopAnimation = loop;
  51550. }
  51551. }
  51552. this.restart();
  51553. }
  51554. else {
  51555. this.start(loop, this._speedRatio);
  51556. }
  51557. return this;
  51558. };
  51559. /**
  51560. * Reset all animations to initial state
  51561. */
  51562. AnimationGroup.prototype.reset = function () {
  51563. if (!this._isStarted) {
  51564. return this;
  51565. }
  51566. for (var index = 0; index < this._animatables.length; index++) {
  51567. var animatable = this._animatables[index];
  51568. animatable.reset();
  51569. }
  51570. return this;
  51571. };
  51572. /**
  51573. * Restart animations from key 0
  51574. */
  51575. AnimationGroup.prototype.restart = function () {
  51576. if (!this._isStarted) {
  51577. return this;
  51578. }
  51579. for (var index = 0; index < this._animatables.length; index++) {
  51580. var animatable = this._animatables[index];
  51581. animatable.restart();
  51582. }
  51583. return this;
  51584. };
  51585. /**
  51586. * Stop all animations
  51587. */
  51588. AnimationGroup.prototype.stop = function () {
  51589. if (!this._isStarted) {
  51590. return this;
  51591. }
  51592. for (var index = 0; index < this._animatables.length; index++) {
  51593. var animatable = this._animatables[index];
  51594. animatable.stop();
  51595. }
  51596. this._isStarted = false;
  51597. return this;
  51598. };
  51599. /**
  51600. * Set animation weight for all animatables
  51601. * @param weight defines the weight to use
  51602. * @return the animationGroup
  51603. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51604. */
  51605. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51606. for (var index = 0; index < this._animatables.length; index++) {
  51607. var animatable = this._animatables[index];
  51608. animatable.weight = weight;
  51609. }
  51610. return this;
  51611. };
  51612. /**
  51613. * Synchronize and normalize all animatables with a source animatable
  51614. * @param root defines the root animatable to synchronize with
  51615. * @return the animationGroup
  51616. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51617. */
  51618. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51619. for (var index = 0; index < this._animatables.length; index++) {
  51620. var animatable = this._animatables[index];
  51621. animatable.syncWith(root);
  51622. }
  51623. return this;
  51624. };
  51625. /**
  51626. * Goes to a specific frame in this animation group
  51627. * @param frame the frame number to go to
  51628. * @return the animationGroup
  51629. */
  51630. AnimationGroup.prototype.goToFrame = function (frame) {
  51631. if (!this._isStarted) {
  51632. return this;
  51633. }
  51634. for (var index = 0; index < this._animatables.length; index++) {
  51635. var animatable = this._animatables[index];
  51636. animatable.goToFrame(frame);
  51637. }
  51638. return this;
  51639. };
  51640. /**
  51641. * Dispose all associated resources
  51642. */
  51643. AnimationGroup.prototype.dispose = function () {
  51644. this._targetedAnimations = [];
  51645. this._animatables = [];
  51646. var index = this._scene.animationGroups.indexOf(this);
  51647. if (index > -1) {
  51648. this._scene.animationGroups.splice(index, 1);
  51649. }
  51650. };
  51651. return AnimationGroup;
  51652. }());
  51653. BABYLON.AnimationGroup = AnimationGroup;
  51654. })(BABYLON || (BABYLON = {}));
  51655. //# sourceMappingURL=babylon.animationGroup.js.map
  51656. var BABYLON;
  51657. (function (BABYLON) {
  51658. /**
  51659. * Defines a runtime animation
  51660. */
  51661. var RuntimeAnimation = /** @class */ (function () {
  51662. /**
  51663. * Create a new RuntimeAnimation object
  51664. * @param target defines the target of the animation
  51665. * @param animation defines the source animation object
  51666. * @param scene defines the hosting scene
  51667. * @param host defines the initiating Animatable
  51668. */
  51669. function RuntimeAnimation(target, animation, scene, host) {
  51670. /**
  51671. * The current frame of the runtime animation
  51672. */
  51673. this._currentFrame = 0;
  51674. /**
  51675. * The original value of the runtime animation
  51676. */
  51677. this._originalValue = new Array();
  51678. /**
  51679. * The offsets cache of the runtime animation
  51680. */
  51681. this._offsetsCache = {};
  51682. /**
  51683. * The high limits cache of the runtime animation
  51684. */
  51685. this._highLimitsCache = {};
  51686. /**
  51687. * Specifies if the runtime animation has been stopped
  51688. */
  51689. this._stopped = false;
  51690. /**
  51691. * The blending factor of the runtime animation
  51692. */
  51693. this._blendingFactor = 0;
  51694. /**
  51695. * The target path of the runtime animation
  51696. */
  51697. this._targetPath = "";
  51698. /**
  51699. * The weight of the runtime animation
  51700. */
  51701. this._weight = 1.0;
  51702. /**
  51703. * The ratio offset of the runtime animation
  51704. */
  51705. this._ratioOffset = 0;
  51706. /**
  51707. * The previous delay of the runtime animation
  51708. */
  51709. this._previousDelay = 0;
  51710. /**
  51711. * The previous ratio of the runtime animation
  51712. */
  51713. this._previousRatio = 0;
  51714. this._animation = animation;
  51715. this._target = target;
  51716. this._scene = scene;
  51717. this._host = host;
  51718. animation._runtimeAnimations.push(this);
  51719. }
  51720. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51721. /**
  51722. * Gets the current frame of the runtime animation
  51723. */
  51724. get: function () {
  51725. return this._currentFrame;
  51726. },
  51727. enumerable: true,
  51728. configurable: true
  51729. });
  51730. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51731. /**
  51732. * Gets the weight of the runtime animation
  51733. */
  51734. get: function () {
  51735. return this._weight;
  51736. },
  51737. enumerable: true,
  51738. configurable: true
  51739. });
  51740. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51741. /**
  51742. * Gets the current value of the runtime animation
  51743. */
  51744. get: function () {
  51745. return this._currentValue;
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51751. /**
  51752. * Gets the target path of the runtime animation
  51753. */
  51754. get: function () {
  51755. return this._targetPath;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51761. /**
  51762. * Gets the actual target of the runtime animation
  51763. */
  51764. get: function () {
  51765. return this._activeTarget;
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51771. /**
  51772. * Gets the animation from the runtime animation
  51773. */
  51774. get: function () {
  51775. return this._animation;
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. /**
  51781. * Resets the runtime animation to the beginning
  51782. * @param restoreOriginal defines whether to restore the target property to the original value
  51783. */
  51784. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51785. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51786. if (restoreOriginal) {
  51787. if (this._target instanceof Array) {
  51788. var index = 0;
  51789. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51790. var target = _a[_i];
  51791. if (this._originalValue[index] !== undefined) {
  51792. this._setValue(target, this._originalValue[index], -1);
  51793. }
  51794. index++;
  51795. }
  51796. }
  51797. else {
  51798. if (this._originalValue[0] !== undefined) {
  51799. this._setValue(this._target, this._originalValue[0], -1);
  51800. }
  51801. }
  51802. }
  51803. this._offsetsCache = {};
  51804. this._highLimitsCache = {};
  51805. this._currentFrame = 0;
  51806. this._blendingFactor = 0;
  51807. this._originalValue = new Array();
  51808. };
  51809. /**
  51810. * Specifies if the runtime animation is stopped
  51811. * @returns Boolean specifying if the runtime animation is stopped
  51812. */
  51813. RuntimeAnimation.prototype.isStopped = function () {
  51814. return this._stopped;
  51815. };
  51816. /**
  51817. * Disposes of the runtime animation
  51818. */
  51819. RuntimeAnimation.prototype.dispose = function () {
  51820. var index = this._animation.runtimeAnimations.indexOf(this);
  51821. if (index > -1) {
  51822. this._animation.runtimeAnimations.splice(index, 1);
  51823. }
  51824. };
  51825. /**
  51826. * Interpolates the animation from the current frame
  51827. * @param currentFrame The frame to interpolate the animation to
  51828. * @param repeatCount The number of times that the animation should loop
  51829. * @param loopMode The type of looping mode to use
  51830. * @param offsetValue Animation offset value
  51831. * @param highLimitValue The high limit value
  51832. * @returns The interpolated value
  51833. */
  51834. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51835. this._currentFrame = currentFrame;
  51836. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51837. this._workValue = BABYLON.Matrix.Zero();
  51838. }
  51839. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51840. };
  51841. /**
  51842. * Apply the interpolated value to the target
  51843. * @param currentValue defines the value computed by the animation
  51844. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51845. */
  51846. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51847. if (weight === void 0) { weight = 1.0; }
  51848. if (this._target instanceof Array) {
  51849. var index = 0;
  51850. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51851. var target = _a[_i];
  51852. this._setValue(target, currentValue, weight, index);
  51853. index++;
  51854. }
  51855. }
  51856. else {
  51857. this._setValue(this._target, currentValue, weight);
  51858. }
  51859. };
  51860. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51861. if (targetIndex === void 0) { targetIndex = 0; }
  51862. // Set value
  51863. var path;
  51864. var destination;
  51865. var targetPropertyPath = this._animation.targetPropertyPath;
  51866. if (targetPropertyPath.length > 1) {
  51867. var property = target[targetPropertyPath[0]];
  51868. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51869. property = property[targetPropertyPath[index]];
  51870. }
  51871. path = targetPropertyPath[targetPropertyPath.length - 1];
  51872. destination = property;
  51873. }
  51874. else {
  51875. path = targetPropertyPath[0];
  51876. destination = target;
  51877. }
  51878. this._targetPath = path;
  51879. this._activeTarget = destination;
  51880. this._weight = weight;
  51881. if (this._originalValue[targetIndex] === undefined) {
  51882. var originalValue = void 0;
  51883. if (destination.getRestPose && path === "_matrix") { // For bones
  51884. originalValue = destination.getRestPose();
  51885. }
  51886. else {
  51887. originalValue = destination[path];
  51888. }
  51889. if (originalValue && originalValue.clone) {
  51890. this._originalValue[targetIndex] = originalValue.clone();
  51891. }
  51892. else {
  51893. this._originalValue[targetIndex] = originalValue;
  51894. }
  51895. }
  51896. // Blending
  51897. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51898. if (enableBlending && this._blendingFactor <= 1.0) {
  51899. if (!this._originalBlendValue) {
  51900. var originalValue = destination[path];
  51901. if (originalValue.clone) {
  51902. this._originalBlendValue = originalValue.clone();
  51903. }
  51904. else {
  51905. this._originalBlendValue = originalValue;
  51906. }
  51907. }
  51908. if (this._originalBlendValue.m) { // Matrix
  51909. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51910. if (this._currentValue) {
  51911. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51912. }
  51913. else {
  51914. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51915. }
  51916. }
  51917. else {
  51918. if (this._currentValue) {
  51919. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51920. }
  51921. else {
  51922. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51923. }
  51924. }
  51925. }
  51926. else {
  51927. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51928. }
  51929. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51930. this._blendingFactor += blendingSpeed;
  51931. }
  51932. else {
  51933. this._currentValue = currentValue;
  51934. }
  51935. if (weight !== -1.0) {
  51936. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51937. }
  51938. else {
  51939. destination[path] = this._currentValue;
  51940. }
  51941. if (target.markAsDirty) {
  51942. target.markAsDirty(this._animation.targetProperty);
  51943. }
  51944. };
  51945. /**
  51946. * Gets the loop pmode of the runtime animation
  51947. * @returns Loop Mode
  51948. */
  51949. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51950. if (this._target && this._target.animationPropertiesOverride) {
  51951. return this._target.animationPropertiesOverride.loopMode;
  51952. }
  51953. return this._animation.loopMode;
  51954. };
  51955. /**
  51956. * Move the current animation to a given frame
  51957. * @param frame defines the frame to move to
  51958. */
  51959. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51960. var keys = this._animation.getKeys();
  51961. if (frame < keys[0].frame) {
  51962. frame = keys[0].frame;
  51963. }
  51964. else if (frame > keys[keys.length - 1].frame) {
  51965. frame = keys[keys.length - 1].frame;
  51966. }
  51967. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51968. this.setValue(currentValue, -1);
  51969. };
  51970. /**
  51971. * @hidden Internal use only
  51972. */
  51973. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51974. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51975. this._ratioOffset = this._previousRatio - newRatio;
  51976. };
  51977. /**
  51978. * Execute the current animation
  51979. * @param delay defines the delay to add to the current frame
  51980. * @param from defines the lower bound of the animation range
  51981. * @param to defines the upper bound of the animation range
  51982. * @param loop defines if the current animation must loop
  51983. * @param speedRatio defines the current speed ratio
  51984. * @param weight defines the weight of the animation (default is -1 so no weight)
  51985. * @returns a boolean indicating if the animation has ended
  51986. */
  51987. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51988. if (weight === void 0) { weight = -1.0; }
  51989. var targetPropertyPath = this._animation.targetPropertyPath;
  51990. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51991. this._stopped = true;
  51992. return false;
  51993. }
  51994. var returnValue = true;
  51995. var keys = this._animation.getKeys();
  51996. // Adding a start key at frame 0 if missing
  51997. if (keys[0].frame !== 0) {
  51998. var newKey = { frame: 0, value: keys[0].value };
  51999. keys.splice(0, 0, newKey);
  52000. }
  52001. // Check limits
  52002. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52003. from = keys[0].frame;
  52004. }
  52005. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52006. to = keys[keys.length - 1].frame;
  52007. }
  52008. //to and from cannot be the same key
  52009. if (from === to) {
  52010. if (from > keys[0].frame) {
  52011. from--;
  52012. }
  52013. else if (to < keys[keys.length - 1].frame) {
  52014. to++;
  52015. }
  52016. }
  52017. // Compute ratio
  52018. var range = to - from;
  52019. var offsetValue;
  52020. // ratio represents the frame delta between from and to
  52021. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52022. var highLimitValue = 0;
  52023. this._previousDelay = delay;
  52024. this._previousRatio = ratio;
  52025. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52026. returnValue = false;
  52027. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52028. }
  52029. else {
  52030. // Get max value if required
  52031. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52032. var keyOffset = to.toString() + from.toString();
  52033. if (!this._offsetsCache[keyOffset]) {
  52034. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52035. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52036. switch (this._animation.dataType) {
  52037. // Float
  52038. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52039. this._offsetsCache[keyOffset] = toValue - fromValue;
  52040. break;
  52041. // Quaternion
  52042. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52043. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52044. break;
  52045. // Vector3
  52046. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52047. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52048. // Vector2
  52049. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52050. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52051. // Size
  52052. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52053. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52054. // Color3
  52055. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52056. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52057. default:
  52058. break;
  52059. }
  52060. this._highLimitsCache[keyOffset] = toValue;
  52061. }
  52062. highLimitValue = this._highLimitsCache[keyOffset];
  52063. offsetValue = this._offsetsCache[keyOffset];
  52064. }
  52065. }
  52066. if (offsetValue === undefined) {
  52067. switch (this._animation.dataType) {
  52068. // Float
  52069. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52070. offsetValue = 0;
  52071. break;
  52072. // Quaternion
  52073. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52074. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52075. break;
  52076. // Vector3
  52077. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52078. offsetValue = BABYLON.Vector3.Zero();
  52079. break;
  52080. // Vector2
  52081. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52082. offsetValue = BABYLON.Vector2.Zero();
  52083. break;
  52084. // Size
  52085. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52086. offsetValue = BABYLON.Size.Zero();
  52087. break;
  52088. // Color3
  52089. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52090. offsetValue = BABYLON.Color3.Black();
  52091. }
  52092. }
  52093. // Compute value
  52094. var repeatCount = (ratio / range) >> 0;
  52095. var currentFrame = returnValue ? from + ratio % range : to;
  52096. // Need to normalize?
  52097. if (this._host && this._host.syncRoot) {
  52098. var syncRoot = this._host.syncRoot;
  52099. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52100. currentFrame = from + (to - from) * hostNormalizedFrame;
  52101. }
  52102. // Reset events if looping
  52103. var events = this._animation.getEvents();
  52104. if (range > 0 && this.currentFrame > currentFrame ||
  52105. range < 0 && this.currentFrame < currentFrame) {
  52106. // Need to reset animation events
  52107. for (var index = 0; index < events.length; index++) {
  52108. if (!events[index].onlyOnce) {
  52109. // reset event, the animation is looping
  52110. events[index].isDone = false;
  52111. }
  52112. }
  52113. }
  52114. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52115. // Set value
  52116. this.setValue(currentValue, weight);
  52117. // Check events
  52118. for (var index = 0; index < events.length; index++) {
  52119. // Make sure current frame has passed event frame and that event frame is within the current range
  52120. // Also, handle both forward and reverse animations
  52121. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52122. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52123. var event = events[index];
  52124. if (!event.isDone) {
  52125. // If event should be done only once, remove it.
  52126. if (event.onlyOnce) {
  52127. events.splice(index, 1);
  52128. index--;
  52129. }
  52130. event.isDone = true;
  52131. event.action();
  52132. } // Don't do anything if the event has already be done.
  52133. }
  52134. }
  52135. if (!returnValue) {
  52136. this._stopped = true;
  52137. }
  52138. return returnValue;
  52139. };
  52140. return RuntimeAnimation;
  52141. }());
  52142. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52143. })(BABYLON || (BABYLON = {}));
  52144. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52145. var BABYLON;
  52146. (function (BABYLON) {
  52147. var Animatable = /** @class */ (function () {
  52148. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52149. if (fromFrame === void 0) { fromFrame = 0; }
  52150. if (toFrame === void 0) { toFrame = 100; }
  52151. if (loopAnimation === void 0) { loopAnimation = false; }
  52152. if (speedRatio === void 0) { speedRatio = 1.0; }
  52153. this.target = target;
  52154. this.fromFrame = fromFrame;
  52155. this.toFrame = toFrame;
  52156. this.loopAnimation = loopAnimation;
  52157. this.onAnimationEnd = onAnimationEnd;
  52158. this._localDelayOffset = null;
  52159. this._pausedDelay = null;
  52160. this._runtimeAnimations = new Array();
  52161. this._paused = false;
  52162. this._speedRatio = 1;
  52163. this._weight = -1.0;
  52164. this.animationStarted = false;
  52165. this._scene = scene;
  52166. if (animations) {
  52167. this.appendAnimations(target, animations);
  52168. }
  52169. this._speedRatio = speedRatio;
  52170. scene._activeAnimatables.push(this);
  52171. }
  52172. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52173. /**
  52174. * Gets the root Animatable used to synchronize and normalize animations
  52175. */
  52176. get: function () {
  52177. return this._syncRoot;
  52178. },
  52179. enumerable: true,
  52180. configurable: true
  52181. });
  52182. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52183. /**
  52184. * Gets the current frame of the first RuntimeAnimation
  52185. * Used to synchronize Animatables
  52186. */
  52187. get: function () {
  52188. if (this._runtimeAnimations.length === 0) {
  52189. return 0;
  52190. }
  52191. return this._runtimeAnimations[0].currentFrame;
  52192. },
  52193. enumerable: true,
  52194. configurable: true
  52195. });
  52196. Object.defineProperty(Animatable.prototype, "weight", {
  52197. /**
  52198. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52199. */
  52200. get: function () {
  52201. return this._weight;
  52202. },
  52203. set: function (value) {
  52204. if (value === -1) { // -1 is ok and means no weight
  52205. this._weight = -1;
  52206. return;
  52207. }
  52208. // Else weight must be in [0, 1] range
  52209. this._weight = Math.min(Math.max(value, 0), 1.0);
  52210. },
  52211. enumerable: true,
  52212. configurable: true
  52213. });
  52214. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52215. /**
  52216. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52217. */
  52218. get: function () {
  52219. return this._speedRatio;
  52220. },
  52221. set: function (value) {
  52222. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52223. var animation = this._runtimeAnimations[index];
  52224. animation._prepareForSpeedRatioChange(value);
  52225. }
  52226. this._speedRatio = value;
  52227. },
  52228. enumerable: true,
  52229. configurable: true
  52230. });
  52231. // Methods
  52232. /**
  52233. * Synchronize and normalize current Animatable with a source Animatable
  52234. * This is useful when using animation weights and when animations are not of the same length
  52235. * @param root defines the root Animatable to synchronize with
  52236. * @returns the current Animatable
  52237. */
  52238. Animatable.prototype.syncWith = function (root) {
  52239. this._syncRoot = root;
  52240. if (root) {
  52241. // Make sure this animatable will animate after the root
  52242. var index = this._scene._activeAnimatables.indexOf(this);
  52243. if (index > -1) {
  52244. this._scene._activeAnimatables.splice(index, 1);
  52245. this._scene._activeAnimatables.push(this);
  52246. }
  52247. }
  52248. return this;
  52249. };
  52250. Animatable.prototype.getAnimations = function () {
  52251. return this._runtimeAnimations;
  52252. };
  52253. Animatable.prototype.appendAnimations = function (target, animations) {
  52254. for (var index = 0; index < animations.length; index++) {
  52255. var animation = animations[index];
  52256. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52257. }
  52258. };
  52259. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52260. var runtimeAnimations = this._runtimeAnimations;
  52261. for (var index = 0; index < runtimeAnimations.length; index++) {
  52262. if (runtimeAnimations[index].animation.targetProperty === property) {
  52263. return runtimeAnimations[index].animation;
  52264. }
  52265. }
  52266. return null;
  52267. };
  52268. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52269. var runtimeAnimations = this._runtimeAnimations;
  52270. for (var index = 0; index < runtimeAnimations.length; index++) {
  52271. if (runtimeAnimations[index].animation.targetProperty === property) {
  52272. return runtimeAnimations[index];
  52273. }
  52274. }
  52275. return null;
  52276. };
  52277. Animatable.prototype.reset = function () {
  52278. var runtimeAnimations = this._runtimeAnimations;
  52279. for (var index = 0; index < runtimeAnimations.length; index++) {
  52280. runtimeAnimations[index].reset(true);
  52281. }
  52282. this._localDelayOffset = null;
  52283. this._pausedDelay = null;
  52284. };
  52285. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52286. var runtimeAnimations = this._runtimeAnimations;
  52287. for (var index = 0; index < runtimeAnimations.length; index++) {
  52288. runtimeAnimations[index].animation.enableBlending = true;
  52289. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52290. }
  52291. };
  52292. Animatable.prototype.disableBlending = function () {
  52293. var runtimeAnimations = this._runtimeAnimations;
  52294. for (var index = 0; index < runtimeAnimations.length; index++) {
  52295. runtimeAnimations[index].animation.enableBlending = false;
  52296. }
  52297. };
  52298. Animatable.prototype.goToFrame = function (frame) {
  52299. var runtimeAnimations = this._runtimeAnimations;
  52300. if (runtimeAnimations[0]) {
  52301. var fps = runtimeAnimations[0].animation.framePerSecond;
  52302. var currentFrame = runtimeAnimations[0].currentFrame;
  52303. var adjustTime = frame - currentFrame;
  52304. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52305. if (this._localDelayOffset === null) {
  52306. this._localDelayOffset = 0;
  52307. }
  52308. this._localDelayOffset -= delay;
  52309. }
  52310. for (var index = 0; index < runtimeAnimations.length; index++) {
  52311. runtimeAnimations[index].goToFrame(frame);
  52312. }
  52313. };
  52314. Animatable.prototype.pause = function () {
  52315. if (this._paused) {
  52316. return;
  52317. }
  52318. this._paused = true;
  52319. };
  52320. Animatable.prototype.restart = function () {
  52321. this._paused = false;
  52322. };
  52323. Animatable.prototype.stop = function (animationName) {
  52324. if (animationName) {
  52325. var idx = this._scene._activeAnimatables.indexOf(this);
  52326. if (idx > -1) {
  52327. var runtimeAnimations = this._runtimeAnimations;
  52328. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52329. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52330. continue;
  52331. }
  52332. runtimeAnimations[index].dispose();
  52333. runtimeAnimations.splice(index, 1);
  52334. }
  52335. if (runtimeAnimations.length == 0) {
  52336. this._scene._activeAnimatables.splice(idx, 1);
  52337. if (this.onAnimationEnd) {
  52338. this.onAnimationEnd();
  52339. }
  52340. }
  52341. }
  52342. }
  52343. else {
  52344. var index = this._scene._activeAnimatables.indexOf(this);
  52345. if (index > -1) {
  52346. this._scene._activeAnimatables.splice(index, 1);
  52347. var runtimeAnimations = this._runtimeAnimations;
  52348. for (var index = 0; index < runtimeAnimations.length; index++) {
  52349. runtimeAnimations[index].dispose();
  52350. }
  52351. if (this.onAnimationEnd) {
  52352. this.onAnimationEnd();
  52353. }
  52354. }
  52355. }
  52356. };
  52357. Animatable.prototype._animate = function (delay) {
  52358. if (this._paused) {
  52359. this.animationStarted = false;
  52360. if (this._pausedDelay === null) {
  52361. this._pausedDelay = delay;
  52362. }
  52363. return true;
  52364. }
  52365. if (this._localDelayOffset === null) {
  52366. this._localDelayOffset = delay;
  52367. this._pausedDelay = null;
  52368. }
  52369. else if (this._pausedDelay !== null) {
  52370. this._localDelayOffset += delay - this._pausedDelay;
  52371. this._pausedDelay = null;
  52372. }
  52373. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52374. return true;
  52375. }
  52376. // Animating
  52377. var running = false;
  52378. var runtimeAnimations = this._runtimeAnimations;
  52379. var index;
  52380. for (index = 0; index < runtimeAnimations.length; index++) {
  52381. var animation = runtimeAnimations[index];
  52382. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52383. running = running || isRunning;
  52384. }
  52385. this.animationStarted = running;
  52386. if (!running) {
  52387. // Remove from active animatables
  52388. index = this._scene._activeAnimatables.indexOf(this);
  52389. this._scene._activeAnimatables.splice(index, 1);
  52390. // Dispose all runtime animations
  52391. for (index = 0; index < runtimeAnimations.length; index++) {
  52392. runtimeAnimations[index].dispose();
  52393. }
  52394. }
  52395. if (!running && this.onAnimationEnd) {
  52396. this.onAnimationEnd();
  52397. this.onAnimationEnd = null;
  52398. }
  52399. return running;
  52400. };
  52401. return Animatable;
  52402. }());
  52403. BABYLON.Animatable = Animatable;
  52404. })(BABYLON || (BABYLON = {}));
  52405. //# sourceMappingURL=babylon.animatable.js.map
  52406. var BABYLON;
  52407. (function (BABYLON) {
  52408. var EasingFunction = /** @class */ (function () {
  52409. function EasingFunction() {
  52410. // Properties
  52411. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52412. }
  52413. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52414. get: function () {
  52415. return EasingFunction._EASINGMODE_EASEIN;
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52421. get: function () {
  52422. return EasingFunction._EASINGMODE_EASEOUT;
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52428. get: function () {
  52429. return EasingFunction._EASINGMODE_EASEINOUT;
  52430. },
  52431. enumerable: true,
  52432. configurable: true
  52433. });
  52434. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52435. var n = Math.min(Math.max(easingMode, 0), 2);
  52436. this._easingMode = n;
  52437. };
  52438. EasingFunction.prototype.getEasingMode = function () {
  52439. return this._easingMode;
  52440. };
  52441. EasingFunction.prototype.easeInCore = function (gradient) {
  52442. throw new Error('You must implement this method');
  52443. };
  52444. EasingFunction.prototype.ease = function (gradient) {
  52445. switch (this._easingMode) {
  52446. case EasingFunction.EASINGMODE_EASEIN:
  52447. return this.easeInCore(gradient);
  52448. case EasingFunction.EASINGMODE_EASEOUT:
  52449. return (1 - this.easeInCore(1 - gradient));
  52450. }
  52451. if (gradient >= 0.5) {
  52452. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52453. }
  52454. return (this.easeInCore(gradient * 2) * 0.5);
  52455. };
  52456. //Statics
  52457. EasingFunction._EASINGMODE_EASEIN = 0;
  52458. EasingFunction._EASINGMODE_EASEOUT = 1;
  52459. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52460. return EasingFunction;
  52461. }());
  52462. BABYLON.EasingFunction = EasingFunction;
  52463. var CircleEase = /** @class */ (function (_super) {
  52464. __extends(CircleEase, _super);
  52465. function CircleEase() {
  52466. return _super !== null && _super.apply(this, arguments) || this;
  52467. }
  52468. CircleEase.prototype.easeInCore = function (gradient) {
  52469. gradient = Math.max(0, Math.min(1, gradient));
  52470. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52471. };
  52472. return CircleEase;
  52473. }(EasingFunction));
  52474. BABYLON.CircleEase = CircleEase;
  52475. var BackEase = /** @class */ (function (_super) {
  52476. __extends(BackEase, _super);
  52477. function BackEase(amplitude) {
  52478. if (amplitude === void 0) { amplitude = 1; }
  52479. var _this = _super.call(this) || this;
  52480. _this.amplitude = amplitude;
  52481. return _this;
  52482. }
  52483. BackEase.prototype.easeInCore = function (gradient) {
  52484. var num = Math.max(0, this.amplitude);
  52485. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52486. };
  52487. return BackEase;
  52488. }(EasingFunction));
  52489. BABYLON.BackEase = BackEase;
  52490. var BounceEase = /** @class */ (function (_super) {
  52491. __extends(BounceEase, _super);
  52492. function BounceEase(bounces, bounciness) {
  52493. if (bounces === void 0) { bounces = 3; }
  52494. if (bounciness === void 0) { bounciness = 2; }
  52495. var _this = _super.call(this) || this;
  52496. _this.bounces = bounces;
  52497. _this.bounciness = bounciness;
  52498. return _this;
  52499. }
  52500. BounceEase.prototype.easeInCore = function (gradient) {
  52501. var y = Math.max(0.0, this.bounces);
  52502. var bounciness = this.bounciness;
  52503. if (bounciness <= 1.0) {
  52504. bounciness = 1.001;
  52505. }
  52506. var num9 = Math.pow(bounciness, y);
  52507. var num5 = 1.0 - bounciness;
  52508. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52509. var num15 = gradient * num4;
  52510. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52511. var num3 = Math.floor(num65);
  52512. var num13 = num3 + 1.0;
  52513. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52514. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52515. var num7 = (num8 + num12) * 0.5;
  52516. var num6 = gradient - num7;
  52517. var num2 = num7 - num8;
  52518. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52519. };
  52520. return BounceEase;
  52521. }(EasingFunction));
  52522. BABYLON.BounceEase = BounceEase;
  52523. var CubicEase = /** @class */ (function (_super) {
  52524. __extends(CubicEase, _super);
  52525. function CubicEase() {
  52526. return _super !== null && _super.apply(this, arguments) || this;
  52527. }
  52528. CubicEase.prototype.easeInCore = function (gradient) {
  52529. return (gradient * gradient * gradient);
  52530. };
  52531. return CubicEase;
  52532. }(EasingFunction));
  52533. BABYLON.CubicEase = CubicEase;
  52534. var ElasticEase = /** @class */ (function (_super) {
  52535. __extends(ElasticEase, _super);
  52536. function ElasticEase(oscillations, springiness) {
  52537. if (oscillations === void 0) { oscillations = 3; }
  52538. if (springiness === void 0) { springiness = 3; }
  52539. var _this = _super.call(this) || this;
  52540. _this.oscillations = oscillations;
  52541. _this.springiness = springiness;
  52542. return _this;
  52543. }
  52544. ElasticEase.prototype.easeInCore = function (gradient) {
  52545. var num2;
  52546. var num3 = Math.max(0.0, this.oscillations);
  52547. var num = Math.max(0.0, this.springiness);
  52548. if (num == 0) {
  52549. num2 = gradient;
  52550. }
  52551. else {
  52552. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52553. }
  52554. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52555. };
  52556. return ElasticEase;
  52557. }(EasingFunction));
  52558. BABYLON.ElasticEase = ElasticEase;
  52559. var ExponentialEase = /** @class */ (function (_super) {
  52560. __extends(ExponentialEase, _super);
  52561. function ExponentialEase(exponent) {
  52562. if (exponent === void 0) { exponent = 2; }
  52563. var _this = _super.call(this) || this;
  52564. _this.exponent = exponent;
  52565. return _this;
  52566. }
  52567. ExponentialEase.prototype.easeInCore = function (gradient) {
  52568. if (this.exponent <= 0) {
  52569. return gradient;
  52570. }
  52571. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52572. };
  52573. return ExponentialEase;
  52574. }(EasingFunction));
  52575. BABYLON.ExponentialEase = ExponentialEase;
  52576. var PowerEase = /** @class */ (function (_super) {
  52577. __extends(PowerEase, _super);
  52578. function PowerEase(power) {
  52579. if (power === void 0) { power = 2; }
  52580. var _this = _super.call(this) || this;
  52581. _this.power = power;
  52582. return _this;
  52583. }
  52584. PowerEase.prototype.easeInCore = function (gradient) {
  52585. var y = Math.max(0.0, this.power);
  52586. return Math.pow(gradient, y);
  52587. };
  52588. return PowerEase;
  52589. }(EasingFunction));
  52590. BABYLON.PowerEase = PowerEase;
  52591. var QuadraticEase = /** @class */ (function (_super) {
  52592. __extends(QuadraticEase, _super);
  52593. function QuadraticEase() {
  52594. return _super !== null && _super.apply(this, arguments) || this;
  52595. }
  52596. QuadraticEase.prototype.easeInCore = function (gradient) {
  52597. return (gradient * gradient);
  52598. };
  52599. return QuadraticEase;
  52600. }(EasingFunction));
  52601. BABYLON.QuadraticEase = QuadraticEase;
  52602. var QuarticEase = /** @class */ (function (_super) {
  52603. __extends(QuarticEase, _super);
  52604. function QuarticEase() {
  52605. return _super !== null && _super.apply(this, arguments) || this;
  52606. }
  52607. QuarticEase.prototype.easeInCore = function (gradient) {
  52608. return (gradient * gradient * gradient * gradient);
  52609. };
  52610. return QuarticEase;
  52611. }(EasingFunction));
  52612. BABYLON.QuarticEase = QuarticEase;
  52613. var QuinticEase = /** @class */ (function (_super) {
  52614. __extends(QuinticEase, _super);
  52615. function QuinticEase() {
  52616. return _super !== null && _super.apply(this, arguments) || this;
  52617. }
  52618. QuinticEase.prototype.easeInCore = function (gradient) {
  52619. return (gradient * gradient * gradient * gradient * gradient);
  52620. };
  52621. return QuinticEase;
  52622. }(EasingFunction));
  52623. BABYLON.QuinticEase = QuinticEase;
  52624. var SineEase = /** @class */ (function (_super) {
  52625. __extends(SineEase, _super);
  52626. function SineEase() {
  52627. return _super !== null && _super.apply(this, arguments) || this;
  52628. }
  52629. SineEase.prototype.easeInCore = function (gradient) {
  52630. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52631. };
  52632. return SineEase;
  52633. }(EasingFunction));
  52634. BABYLON.SineEase = SineEase;
  52635. var BezierCurveEase = /** @class */ (function (_super) {
  52636. __extends(BezierCurveEase, _super);
  52637. function BezierCurveEase(x1, y1, x2, y2) {
  52638. if (x1 === void 0) { x1 = 0; }
  52639. if (y1 === void 0) { y1 = 0; }
  52640. if (x2 === void 0) { x2 = 1; }
  52641. if (y2 === void 0) { y2 = 1; }
  52642. var _this = _super.call(this) || this;
  52643. _this.x1 = x1;
  52644. _this.y1 = y1;
  52645. _this.x2 = x2;
  52646. _this.y2 = y2;
  52647. return _this;
  52648. }
  52649. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52650. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52651. };
  52652. return BezierCurveEase;
  52653. }(EasingFunction));
  52654. BABYLON.BezierCurveEase = BezierCurveEase;
  52655. })(BABYLON || (BABYLON = {}));
  52656. //# sourceMappingURL=babylon.easing.js.map
  52657. var BABYLON;
  52658. (function (BABYLON) {
  52659. /**
  52660. * A Condition applied to an Action
  52661. */
  52662. var Condition = /** @class */ (function () {
  52663. /**
  52664. * Creates a new Condition
  52665. * @param actionManager the manager of the action the condition is applied to
  52666. */
  52667. function Condition(actionManager) {
  52668. this._actionManager = actionManager;
  52669. }
  52670. /**
  52671. * Check if the current condition is valid
  52672. * @returns a boolean
  52673. */
  52674. Condition.prototype.isValid = function () {
  52675. return true;
  52676. };
  52677. /**
  52678. * Internal only
  52679. * @hidden
  52680. */
  52681. Condition.prototype._getProperty = function (propertyPath) {
  52682. return this._actionManager._getProperty(propertyPath);
  52683. };
  52684. /**
  52685. * Internal only
  52686. * @hidden
  52687. */
  52688. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52689. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52690. };
  52691. /**
  52692. * Serialize placeholder for child classes
  52693. * @returns the serialized object
  52694. */
  52695. Condition.prototype.serialize = function () {
  52696. };
  52697. /**
  52698. * Internal only
  52699. * @hidden
  52700. */
  52701. Condition.prototype._serialize = function (serializedCondition) {
  52702. return {
  52703. type: 2,
  52704. children: [],
  52705. name: serializedCondition.name,
  52706. properties: serializedCondition.properties
  52707. };
  52708. };
  52709. return Condition;
  52710. }());
  52711. BABYLON.Condition = Condition;
  52712. /**
  52713. * Defines specific conditional operators as extensions of Condition
  52714. */
  52715. var ValueCondition = /** @class */ (function (_super) {
  52716. __extends(ValueCondition, _super);
  52717. /**
  52718. * Creates a new ValueCondition
  52719. * @param actionManager manager for the action the condition applies to
  52720. * @param target for the action
  52721. * @param propertyPath path to specify the property of the target the conditional operator uses
  52722. * @param value the value compared by the conditional operator against the current value of the property
  52723. * @param operator the conditional operator, default ValueCondition.IsEqual
  52724. */
  52725. function ValueCondition(actionManager, target,
  52726. /** path to specify the property of the target the conditional operator uses */
  52727. propertyPath,
  52728. /** the value compared by the conditional operator against the current value of the property */
  52729. value,
  52730. /** the conditional operator, default ValueCondition.IsEqual */
  52731. operator) {
  52732. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52733. var _this = _super.call(this, actionManager) || this;
  52734. _this.propertyPath = propertyPath;
  52735. _this.value = value;
  52736. _this.operator = operator;
  52737. _this._target = target;
  52738. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52739. _this._property = _this._getProperty(_this.propertyPath);
  52740. return _this;
  52741. }
  52742. Object.defineProperty(ValueCondition, "IsEqual", {
  52743. /**
  52744. * returns the number for IsEqual
  52745. */
  52746. get: function () {
  52747. return ValueCondition._IsEqual;
  52748. },
  52749. enumerable: true,
  52750. configurable: true
  52751. });
  52752. Object.defineProperty(ValueCondition, "IsDifferent", {
  52753. /**
  52754. * Returns the number for IsDifferent
  52755. */
  52756. get: function () {
  52757. return ValueCondition._IsDifferent;
  52758. },
  52759. enumerable: true,
  52760. configurable: true
  52761. });
  52762. Object.defineProperty(ValueCondition, "IsGreater", {
  52763. /**
  52764. * Returns the number for IsGreater
  52765. */
  52766. get: function () {
  52767. return ValueCondition._IsGreater;
  52768. },
  52769. enumerable: true,
  52770. configurable: true
  52771. });
  52772. Object.defineProperty(ValueCondition, "IsLesser", {
  52773. /**
  52774. * Returns the number for IsLesser
  52775. */
  52776. get: function () {
  52777. return ValueCondition._IsLesser;
  52778. },
  52779. enumerable: true,
  52780. configurable: true
  52781. });
  52782. /**
  52783. * Compares the given value with the property value for the specified conditional operator
  52784. * @returns the result of the comparison
  52785. */
  52786. ValueCondition.prototype.isValid = function () {
  52787. switch (this.operator) {
  52788. case ValueCondition.IsGreater:
  52789. return this._effectiveTarget[this._property] > this.value;
  52790. case ValueCondition.IsLesser:
  52791. return this._effectiveTarget[this._property] < this.value;
  52792. case ValueCondition.IsEqual:
  52793. case ValueCondition.IsDifferent:
  52794. var check;
  52795. if (this.value.equals) {
  52796. check = this.value.equals(this._effectiveTarget[this._property]);
  52797. }
  52798. else {
  52799. check = this.value === this._effectiveTarget[this._property];
  52800. }
  52801. return this.operator === ValueCondition.IsEqual ? check : !check;
  52802. }
  52803. return false;
  52804. };
  52805. /**
  52806. * Serialize the ValueCondition into a JSON compatible object
  52807. * @returns serialization object
  52808. */
  52809. ValueCondition.prototype.serialize = function () {
  52810. return this._serialize({
  52811. name: "ValueCondition",
  52812. properties: [
  52813. BABYLON.Action._GetTargetProperty(this._target),
  52814. { name: "propertyPath", value: this.propertyPath },
  52815. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52816. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52817. ]
  52818. });
  52819. };
  52820. /**
  52821. * Gets the name of the conditional operator for the ValueCondition
  52822. * @param operator the conditional operator
  52823. * @returns the name
  52824. */
  52825. ValueCondition.GetOperatorName = function (operator) {
  52826. switch (operator) {
  52827. case ValueCondition._IsEqual: return "IsEqual";
  52828. case ValueCondition._IsDifferent: return "IsDifferent";
  52829. case ValueCondition._IsGreater: return "IsGreater";
  52830. case ValueCondition._IsLesser: return "IsLesser";
  52831. default: return "";
  52832. }
  52833. };
  52834. /**
  52835. * Internal only
  52836. * @hidden
  52837. */
  52838. ValueCondition._IsEqual = 0;
  52839. /**
  52840. * Internal only
  52841. * @hidden
  52842. */
  52843. ValueCondition._IsDifferent = 1;
  52844. /**
  52845. * Internal only
  52846. * @hidden
  52847. */
  52848. ValueCondition._IsGreater = 2;
  52849. /**
  52850. * Internal only
  52851. * @hidden
  52852. */
  52853. ValueCondition._IsLesser = 3;
  52854. return ValueCondition;
  52855. }(Condition));
  52856. BABYLON.ValueCondition = ValueCondition;
  52857. /**
  52858. * Defines a predicate condition as an extension of Condition
  52859. */
  52860. var PredicateCondition = /** @class */ (function (_super) {
  52861. __extends(PredicateCondition, _super);
  52862. /**
  52863. * Creates a new PredicateCondition
  52864. * @param actionManager manager for the action the condition applies to
  52865. * @param predicate defines the predicate function used to validate the condition
  52866. */
  52867. function PredicateCondition(actionManager,
  52868. /** defines the predicate function used to validate the condition */
  52869. predicate) {
  52870. var _this = _super.call(this, actionManager) || this;
  52871. _this.predicate = predicate;
  52872. return _this;
  52873. }
  52874. /**
  52875. * @returns the validity of the predicate condition
  52876. */
  52877. PredicateCondition.prototype.isValid = function () {
  52878. return this.predicate();
  52879. };
  52880. return PredicateCondition;
  52881. }(Condition));
  52882. BABYLON.PredicateCondition = PredicateCondition;
  52883. /**
  52884. * Defines a state condition as an extension of Condition
  52885. */
  52886. var StateCondition = /** @class */ (function (_super) {
  52887. __extends(StateCondition, _super);
  52888. /**
  52889. * Creates a new StateCondition
  52890. * @param actionManager manager for the action the condition applies to
  52891. * @param target of the condition
  52892. * @param value to compare with target state
  52893. */
  52894. function StateCondition(actionManager, target, value) {
  52895. var _this = _super.call(this, actionManager) || this;
  52896. _this.value = value;
  52897. _this._target = target;
  52898. return _this;
  52899. }
  52900. /**
  52901. * @returns the validity of the state
  52902. */
  52903. StateCondition.prototype.isValid = function () {
  52904. return this._target.state === this.value;
  52905. };
  52906. /**
  52907. * Serialize the StateCondition into a JSON compatible object
  52908. * @returns serialization object
  52909. */
  52910. StateCondition.prototype.serialize = function () {
  52911. return this._serialize({
  52912. name: "StateCondition",
  52913. properties: [
  52914. BABYLON.Action._GetTargetProperty(this._target),
  52915. { name: "value", value: this.value }
  52916. ]
  52917. });
  52918. };
  52919. return StateCondition;
  52920. }(Condition));
  52921. BABYLON.StateCondition = StateCondition;
  52922. })(BABYLON || (BABYLON = {}));
  52923. //# sourceMappingURL=babylon.condition.js.map
  52924. var BABYLON;
  52925. (function (BABYLON) {
  52926. /**
  52927. * The action to be carried out following a trigger
  52928. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52929. */
  52930. var Action = /** @class */ (function () {
  52931. /**
  52932. * Creates a new Action
  52933. * @param triggerOptions the trigger, with or without parameters, for the action
  52934. * @param condition an optional determinant of action
  52935. */
  52936. function Action(
  52937. /** the trigger, with or without parameters, for the action */
  52938. triggerOptions, condition) {
  52939. this.triggerOptions = triggerOptions;
  52940. /**
  52941. * An event triggered prior to action being executed.
  52942. */
  52943. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52944. if (triggerOptions.parameter) {
  52945. this.trigger = triggerOptions.trigger;
  52946. this._triggerParameter = triggerOptions.parameter;
  52947. }
  52948. else {
  52949. this.trigger = triggerOptions;
  52950. }
  52951. this._nextActiveAction = this;
  52952. this._condition = condition;
  52953. }
  52954. /**
  52955. * Internal only
  52956. * @hidden
  52957. */
  52958. Action.prototype._prepare = function () {
  52959. };
  52960. /**
  52961. * Gets the trigger parameters
  52962. * @returns the trigger parameters
  52963. */
  52964. Action.prototype.getTriggerParameter = function () {
  52965. return this._triggerParameter;
  52966. };
  52967. /**
  52968. * Internal only - executes current action event
  52969. * @hidden
  52970. */
  52971. Action.prototype._executeCurrent = function (evt) {
  52972. if (this._nextActiveAction._condition) {
  52973. var condition = this._nextActiveAction._condition;
  52974. var currentRenderId = this._actionManager.getScene().getRenderId();
  52975. // We cache the current evaluation for the current frame
  52976. if (condition._evaluationId === currentRenderId) {
  52977. if (!condition._currentResult) {
  52978. return;
  52979. }
  52980. }
  52981. else {
  52982. condition._evaluationId = currentRenderId;
  52983. if (!condition.isValid()) {
  52984. condition._currentResult = false;
  52985. return;
  52986. }
  52987. condition._currentResult = true;
  52988. }
  52989. }
  52990. this.onBeforeExecuteObservable.notifyObservers(this);
  52991. this._nextActiveAction.execute(evt);
  52992. this.skipToNextActiveAction();
  52993. };
  52994. /**
  52995. * Execute placeholder for child classes
  52996. * @param evt optional action event
  52997. */
  52998. Action.prototype.execute = function (evt) {
  52999. };
  53000. /**
  53001. * Skips to next active action
  53002. */
  53003. Action.prototype.skipToNextActiveAction = function () {
  53004. if (this._nextActiveAction._child) {
  53005. if (!this._nextActiveAction._child._actionManager) {
  53006. this._nextActiveAction._child._actionManager = this._actionManager;
  53007. }
  53008. this._nextActiveAction = this._nextActiveAction._child;
  53009. }
  53010. else {
  53011. this._nextActiveAction = this;
  53012. }
  53013. };
  53014. /**
  53015. * Adds action to chain of actions, may be a DoNothingAction
  53016. * @param action defines the next action to execute
  53017. * @returns The action passed in
  53018. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53019. */
  53020. Action.prototype.then = function (action) {
  53021. this._child = action;
  53022. action._actionManager = this._actionManager;
  53023. action._prepare();
  53024. return action;
  53025. };
  53026. /**
  53027. * Internal only
  53028. * @hidden
  53029. */
  53030. Action.prototype._getProperty = function (propertyPath) {
  53031. return this._actionManager._getProperty(propertyPath);
  53032. };
  53033. /**
  53034. * Internal only
  53035. * @hidden
  53036. */
  53037. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53038. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53039. };
  53040. /**
  53041. * Serialize placeholder for child classes
  53042. * @param parent of child
  53043. * @returns the serialized object
  53044. */
  53045. Action.prototype.serialize = function (parent) {
  53046. };
  53047. /**
  53048. * Internal only called by serialize
  53049. * @hidden
  53050. */
  53051. Action.prototype._serialize = function (serializedAction, parent) {
  53052. var serializationObject = {
  53053. type: 1,
  53054. children: [],
  53055. name: serializedAction.name,
  53056. properties: serializedAction.properties || []
  53057. };
  53058. // Serialize child
  53059. if (this._child) {
  53060. this._child.serialize(serializationObject);
  53061. }
  53062. // Check if "this" has a condition
  53063. if (this._condition) {
  53064. var serializedCondition = this._condition.serialize();
  53065. serializedCondition.children.push(serializationObject);
  53066. if (parent) {
  53067. parent.children.push(serializedCondition);
  53068. }
  53069. return serializedCondition;
  53070. }
  53071. if (parent) {
  53072. parent.children.push(serializationObject);
  53073. }
  53074. return serializationObject;
  53075. };
  53076. /**
  53077. * Internal only
  53078. * @hidden
  53079. */
  53080. Action._SerializeValueAsString = function (value) {
  53081. if (typeof value === "number") {
  53082. return value.toString();
  53083. }
  53084. if (typeof value === "boolean") {
  53085. return value ? "true" : "false";
  53086. }
  53087. if (value instanceof BABYLON.Vector2) {
  53088. return value.x + ", " + value.y;
  53089. }
  53090. if (value instanceof BABYLON.Vector3) {
  53091. return value.x + ", " + value.y + ", " + value.z;
  53092. }
  53093. if (value instanceof BABYLON.Color3) {
  53094. return value.r + ", " + value.g + ", " + value.b;
  53095. }
  53096. if (value instanceof BABYLON.Color4) {
  53097. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53098. }
  53099. return value; // string
  53100. };
  53101. /**
  53102. * Internal only
  53103. * @hidden
  53104. */
  53105. Action._GetTargetProperty = function (target) {
  53106. return {
  53107. name: "target",
  53108. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53109. : target instanceof BABYLON.Light ? "LightProperties"
  53110. : target instanceof BABYLON.Camera ? "CameraProperties"
  53111. : "SceneProperties",
  53112. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53113. };
  53114. };
  53115. return Action;
  53116. }());
  53117. BABYLON.Action = Action;
  53118. })(BABYLON || (BABYLON = {}));
  53119. //# sourceMappingURL=babylon.action.js.map
  53120. var BABYLON;
  53121. (function (BABYLON) {
  53122. /**
  53123. * ActionEvent is the event being sent when an action is triggered.
  53124. */
  53125. var ActionEvent = /** @class */ (function () {
  53126. /**
  53127. * Creates a new ActionEvent
  53128. * @param source The mesh or sprite that triggered the action
  53129. * @param pointerX The X mouse cursor position at the time of the event
  53130. * @param pointerY The Y mouse cursor position at the time of the event
  53131. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53132. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53133. * @param additionalData additional data for the event
  53134. */
  53135. function ActionEvent(
  53136. /** The mesh or sprite that triggered the action */
  53137. source,
  53138. /** The X mouse cursor position at the time of the event */
  53139. pointerX,
  53140. /** The Y mouse cursor position at the time of the event */
  53141. pointerY,
  53142. /** The mesh that is currently pointed at (can be null) */
  53143. meshUnderPointer,
  53144. /** the original (browser) event that triggered the ActionEvent */
  53145. sourceEvent,
  53146. /** additional data for the event */
  53147. additionalData) {
  53148. this.source = source;
  53149. this.pointerX = pointerX;
  53150. this.pointerY = pointerY;
  53151. this.meshUnderPointer = meshUnderPointer;
  53152. this.sourceEvent = sourceEvent;
  53153. this.additionalData = additionalData;
  53154. }
  53155. /**
  53156. * Helper function to auto-create an ActionEvent from a source mesh.
  53157. * @param source The source mesh that triggered the event
  53158. * @param evt The original (browser) event
  53159. * @param additionalData additional data for the event
  53160. * @returns the new ActionEvent
  53161. */
  53162. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53163. var scene = source.getScene();
  53164. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53165. };
  53166. /**
  53167. * Helper function to auto-create an ActionEvent from a source sprite
  53168. * @param source The source sprite that triggered the event
  53169. * @param scene Scene associated with the sprite
  53170. * @param evt The original (browser) event
  53171. * @param additionalData additional data for the event
  53172. * @returns the new ActionEvent
  53173. */
  53174. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53175. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53176. };
  53177. /**
  53178. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53179. * @param scene the scene where the event occurred
  53180. * @param evt The original (browser) event
  53181. * @returns the new ActionEvent
  53182. */
  53183. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53184. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53185. };
  53186. /**
  53187. * Helper function to auto-create an ActionEvent from a primitive
  53188. * @param prim defines the target primitive
  53189. * @param pointerPos defines the pointer position
  53190. * @param evt The original (browser) event
  53191. * @param additionalData additional data for the event
  53192. * @returns the new ActionEvent
  53193. */
  53194. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53195. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53196. };
  53197. return ActionEvent;
  53198. }());
  53199. BABYLON.ActionEvent = ActionEvent;
  53200. /**
  53201. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53202. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53204. */
  53205. var ActionManager = /** @class */ (function () {
  53206. /**
  53207. * Creates a new action manager
  53208. * @param scene defines the hosting scene
  53209. */
  53210. function ActionManager(scene) {
  53211. // Members
  53212. /** Gets the list of actions */
  53213. this.actions = new Array();
  53214. /** Gets the cursor to use when hovering items */
  53215. this.hoverCursor = '';
  53216. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53217. scene._actionManagers.push(this);
  53218. }
  53219. Object.defineProperty(ActionManager, "NothingTrigger", {
  53220. /**
  53221. * Nothing
  53222. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53223. */
  53224. get: function () {
  53225. return ActionManager._NothingTrigger;
  53226. },
  53227. enumerable: true,
  53228. configurable: true
  53229. });
  53230. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53231. /**
  53232. * On pick
  53233. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53234. */
  53235. get: function () {
  53236. return ActionManager._OnPickTrigger;
  53237. },
  53238. enumerable: true,
  53239. configurable: true
  53240. });
  53241. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53242. /**
  53243. * On left pick
  53244. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53245. */
  53246. get: function () {
  53247. return ActionManager._OnLeftPickTrigger;
  53248. },
  53249. enumerable: true,
  53250. configurable: true
  53251. });
  53252. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53253. /**
  53254. * On right pick
  53255. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53256. */
  53257. get: function () {
  53258. return ActionManager._OnRightPickTrigger;
  53259. },
  53260. enumerable: true,
  53261. configurable: true
  53262. });
  53263. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53264. /**
  53265. * On center pick
  53266. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53267. */
  53268. get: function () {
  53269. return ActionManager._OnCenterPickTrigger;
  53270. },
  53271. enumerable: true,
  53272. configurable: true
  53273. });
  53274. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53275. /**
  53276. * On pick down
  53277. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53278. */
  53279. get: function () {
  53280. return ActionManager._OnPickDownTrigger;
  53281. },
  53282. enumerable: true,
  53283. configurable: true
  53284. });
  53285. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53286. /**
  53287. * On double pick
  53288. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53289. */
  53290. get: function () {
  53291. return ActionManager._OnDoublePickTrigger;
  53292. },
  53293. enumerable: true,
  53294. configurable: true
  53295. });
  53296. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53297. /**
  53298. * On pick up
  53299. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53300. */
  53301. get: function () {
  53302. return ActionManager._OnPickUpTrigger;
  53303. },
  53304. enumerable: true,
  53305. configurable: true
  53306. });
  53307. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53308. /**
  53309. * On pick out.
  53310. * This trigger will only be raised if you also declared a OnPickDown
  53311. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53312. */
  53313. get: function () {
  53314. return ActionManager._OnPickOutTrigger;
  53315. },
  53316. enumerable: true,
  53317. configurable: true
  53318. });
  53319. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53320. /**
  53321. * On long press
  53322. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53323. */
  53324. get: function () {
  53325. return ActionManager._OnLongPressTrigger;
  53326. },
  53327. enumerable: true,
  53328. configurable: true
  53329. });
  53330. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53331. /**
  53332. * On pointer over
  53333. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53334. */
  53335. get: function () {
  53336. return ActionManager._OnPointerOverTrigger;
  53337. },
  53338. enumerable: true,
  53339. configurable: true
  53340. });
  53341. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53342. /**
  53343. * On pointer out
  53344. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53345. */
  53346. get: function () {
  53347. return ActionManager._OnPointerOutTrigger;
  53348. },
  53349. enumerable: true,
  53350. configurable: true
  53351. });
  53352. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53353. /**
  53354. * On every frame
  53355. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53356. */
  53357. get: function () {
  53358. return ActionManager._OnEveryFrameTrigger;
  53359. },
  53360. enumerable: true,
  53361. configurable: true
  53362. });
  53363. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53364. /**
  53365. * On intersection enter
  53366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53367. */
  53368. get: function () {
  53369. return ActionManager._OnIntersectionEnterTrigger;
  53370. },
  53371. enumerable: true,
  53372. configurable: true
  53373. });
  53374. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53375. /**
  53376. * On intersection exit
  53377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53378. */
  53379. get: function () {
  53380. return ActionManager._OnIntersectionExitTrigger;
  53381. },
  53382. enumerable: true,
  53383. configurable: true
  53384. });
  53385. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53386. /**
  53387. * On key down
  53388. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53389. */
  53390. get: function () {
  53391. return ActionManager._OnKeyDownTrigger;
  53392. },
  53393. enumerable: true,
  53394. configurable: true
  53395. });
  53396. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53397. /**
  53398. * On key up
  53399. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53400. */
  53401. get: function () {
  53402. return ActionManager._OnKeyUpTrigger;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. // Methods
  53408. /**
  53409. * Releases all associated resources
  53410. */
  53411. ActionManager.prototype.dispose = function () {
  53412. var index = this._scene._actionManagers.indexOf(this);
  53413. for (var i = 0; i < this.actions.length; i++) {
  53414. var action = this.actions[i];
  53415. ActionManager.Triggers[action.trigger]--;
  53416. if (ActionManager.Triggers[action.trigger] === 0) {
  53417. delete ActionManager.Triggers[action.trigger];
  53418. }
  53419. }
  53420. if (index > -1) {
  53421. this._scene._actionManagers.splice(index, 1);
  53422. }
  53423. };
  53424. /**
  53425. * Gets hosting scene
  53426. * @returns the hosting scene
  53427. */
  53428. ActionManager.prototype.getScene = function () {
  53429. return this._scene;
  53430. };
  53431. /**
  53432. * Does this action manager handles actions of any of the given triggers
  53433. * @param triggers defines the triggers to be tested
  53434. * @return a boolean indicating whether one (or more) of the triggers is handled
  53435. */
  53436. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53437. for (var index = 0; index < this.actions.length; index++) {
  53438. var action = this.actions[index];
  53439. if (triggers.indexOf(action.trigger) > -1) {
  53440. return true;
  53441. }
  53442. }
  53443. return false;
  53444. };
  53445. /**
  53446. * Does this action manager handles actions of a given trigger
  53447. * @param trigger defines the trigger to be tested
  53448. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53449. * @return whether the trigger is handled
  53450. */
  53451. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53452. for (var index = 0; index < this.actions.length; index++) {
  53453. var action = this.actions[index];
  53454. if (action.trigger === trigger) {
  53455. if (parameterPredicate) {
  53456. if (parameterPredicate(action.getTriggerParameter())) {
  53457. return true;
  53458. }
  53459. }
  53460. else {
  53461. return true;
  53462. }
  53463. }
  53464. }
  53465. return false;
  53466. };
  53467. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53468. /**
  53469. * Does this action manager has pointer triggers
  53470. */
  53471. get: function () {
  53472. for (var index = 0; index < this.actions.length; index++) {
  53473. var action = this.actions[index];
  53474. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53475. return true;
  53476. }
  53477. }
  53478. return false;
  53479. },
  53480. enumerable: true,
  53481. configurable: true
  53482. });
  53483. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53484. /**
  53485. * Does this action manager has pick triggers
  53486. */
  53487. get: function () {
  53488. for (var index = 0; index < this.actions.length; index++) {
  53489. var action = this.actions[index];
  53490. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53491. return true;
  53492. }
  53493. }
  53494. return false;
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(ActionManager, "HasTriggers", {
  53500. /**
  53501. * Does exist one action manager with at least one trigger
  53502. **/
  53503. get: function () {
  53504. for (var t in ActionManager.Triggers) {
  53505. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53506. return true;
  53507. }
  53508. }
  53509. return false;
  53510. },
  53511. enumerable: true,
  53512. configurable: true
  53513. });
  53514. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53515. /**
  53516. * Does exist one action manager with at least one pick trigger
  53517. **/
  53518. get: function () {
  53519. for (var t in ActionManager.Triggers) {
  53520. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53521. var t_int = parseInt(t);
  53522. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53523. return true;
  53524. }
  53525. }
  53526. }
  53527. return false;
  53528. },
  53529. enumerable: true,
  53530. configurable: true
  53531. });
  53532. /**
  53533. * Does exist one action manager that handles actions of a given trigger
  53534. * @param trigger defines the trigger to be tested
  53535. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53536. **/
  53537. ActionManager.HasSpecificTrigger = function (trigger) {
  53538. for (var t in ActionManager.Triggers) {
  53539. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53540. var t_int = parseInt(t);
  53541. if (t_int === trigger) {
  53542. return true;
  53543. }
  53544. }
  53545. }
  53546. return false;
  53547. };
  53548. /**
  53549. * Registers an action to this action manager
  53550. * @param action defines the action to be registered
  53551. * @return the action amended (prepared) after registration
  53552. */
  53553. ActionManager.prototype.registerAction = function (action) {
  53554. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53555. if (this.getScene().actionManager !== this) {
  53556. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53557. return null;
  53558. }
  53559. }
  53560. this.actions.push(action);
  53561. if (ActionManager.Triggers[action.trigger]) {
  53562. ActionManager.Triggers[action.trigger]++;
  53563. }
  53564. else {
  53565. ActionManager.Triggers[action.trigger] = 1;
  53566. }
  53567. action._actionManager = this;
  53568. action._prepare();
  53569. return action;
  53570. };
  53571. /**
  53572. * Unregisters an action to this action manager
  53573. * @param action defines the action to be unregistered
  53574. * @return a boolean indicating whether the action has been unregistered
  53575. */
  53576. ActionManager.prototype.unregisterAction = function (action) {
  53577. var index = this.actions.indexOf(action);
  53578. if (index !== -1) {
  53579. this.actions.splice(index, 1);
  53580. ActionManager.Triggers[action.trigger] -= 1;
  53581. if (ActionManager.Triggers[action.trigger] === 0) {
  53582. delete ActionManager.Triggers[action.trigger];
  53583. }
  53584. delete action._actionManager;
  53585. return true;
  53586. }
  53587. return false;
  53588. };
  53589. /**
  53590. * Process a specific trigger
  53591. * @param trigger defines the trigger to process
  53592. * @param evt defines the event details to be processed
  53593. */
  53594. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53595. for (var index = 0; index < this.actions.length; index++) {
  53596. var action = this.actions[index];
  53597. if (action.trigger === trigger) {
  53598. if (evt) {
  53599. if (trigger === ActionManager.OnKeyUpTrigger
  53600. || trigger === ActionManager.OnKeyDownTrigger) {
  53601. var parameter = action.getTriggerParameter();
  53602. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53603. if (!parameter.toLowerCase) {
  53604. continue;
  53605. }
  53606. var lowerCase = parameter.toLowerCase();
  53607. if (lowerCase !== evt.sourceEvent.key) {
  53608. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53609. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53610. if (actualkey !== lowerCase) {
  53611. continue;
  53612. }
  53613. }
  53614. }
  53615. }
  53616. }
  53617. action._executeCurrent(evt);
  53618. }
  53619. }
  53620. };
  53621. /** @hidden */
  53622. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53623. var properties = propertyPath.split(".");
  53624. for (var index = 0; index < properties.length - 1; index++) {
  53625. target = target[properties[index]];
  53626. }
  53627. return target;
  53628. };
  53629. /** @hidden */
  53630. ActionManager.prototype._getProperty = function (propertyPath) {
  53631. var properties = propertyPath.split(".");
  53632. return properties[properties.length - 1];
  53633. };
  53634. /**
  53635. * Serialize this manager to a JSON object
  53636. * @param name defines the property name to store this manager
  53637. * @returns a JSON representation of this manager
  53638. */
  53639. ActionManager.prototype.serialize = function (name) {
  53640. var root = {
  53641. children: new Array(),
  53642. name: name,
  53643. type: 3,
  53644. properties: new Array() // Empty for root but required
  53645. };
  53646. for (var i = 0; i < this.actions.length; i++) {
  53647. var triggerObject = {
  53648. type: 0,
  53649. children: new Array(),
  53650. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53651. properties: new Array()
  53652. };
  53653. var triggerOptions = this.actions[i].triggerOptions;
  53654. if (triggerOptions && typeof triggerOptions !== "number") {
  53655. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53656. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53657. }
  53658. else {
  53659. var parameter = {};
  53660. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53661. if (triggerOptions.parameter.mesh) {
  53662. parameter._meshId = triggerOptions.parameter.mesh.id;
  53663. }
  53664. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53665. }
  53666. }
  53667. // Serialize child action, recursively
  53668. this.actions[i].serialize(triggerObject);
  53669. // Add serialized trigger
  53670. root.children.push(triggerObject);
  53671. }
  53672. return root;
  53673. };
  53674. /**
  53675. * Creates a new ActionManager from a JSON data
  53676. * @param parsedActions defines the JSON data to read from
  53677. * @param object defines the hosting mesh
  53678. * @param scene defines the hosting scene
  53679. */
  53680. ActionManager.Parse = function (parsedActions, object, scene) {
  53681. var actionManager = new ActionManager(scene);
  53682. if (object === null)
  53683. scene.actionManager = actionManager;
  53684. else
  53685. object.actionManager = actionManager;
  53686. // instanciate a new object
  53687. var instanciate = function (name, params) {
  53688. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53689. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53690. newInstance.constructor.apply(newInstance, params);
  53691. return newInstance;
  53692. };
  53693. var parseParameter = function (name, value, target, propertyPath) {
  53694. if (propertyPath === null) {
  53695. // String, boolean or float
  53696. var floatValue = parseFloat(value);
  53697. if (value === "true" || value === "false")
  53698. return value === "true";
  53699. else
  53700. return isNaN(floatValue) ? value : floatValue;
  53701. }
  53702. var effectiveTarget = propertyPath.split(".");
  53703. var values = value.split(",");
  53704. // Get effective Target
  53705. for (var i = 0; i < effectiveTarget.length; i++) {
  53706. target = target[effectiveTarget[i]];
  53707. }
  53708. // Return appropriate value with its type
  53709. if (typeof (target) === "boolean")
  53710. return values[0] === "true";
  53711. if (typeof (target) === "string")
  53712. return values[0];
  53713. // Parameters with multiple values such as Vector3 etc.
  53714. var split = new Array();
  53715. for (var i = 0; i < values.length; i++)
  53716. split.push(parseFloat(values[i]));
  53717. if (target instanceof BABYLON.Vector3)
  53718. return BABYLON.Vector3.FromArray(split);
  53719. if (target instanceof BABYLON.Vector4)
  53720. return BABYLON.Vector4.FromArray(split);
  53721. if (target instanceof BABYLON.Color3)
  53722. return BABYLON.Color3.FromArray(split);
  53723. if (target instanceof BABYLON.Color4)
  53724. return BABYLON.Color4.FromArray(split);
  53725. return parseFloat(values[0]);
  53726. };
  53727. // traverse graph per trigger
  53728. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53729. if (combineArray === void 0) { combineArray = null; }
  53730. if (parsedAction.detached)
  53731. return;
  53732. var parameters = new Array();
  53733. var target = null;
  53734. var propertyPath = null;
  53735. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53736. // Parameters
  53737. if (parsedAction.type === 2)
  53738. parameters.push(actionManager);
  53739. else
  53740. parameters.push(trigger);
  53741. if (combine) {
  53742. var actions = new Array();
  53743. for (var j = 0; j < parsedAction.combine.length; j++) {
  53744. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53745. }
  53746. parameters.push(actions);
  53747. }
  53748. else {
  53749. for (var i = 0; i < parsedAction.properties.length; i++) {
  53750. var value = parsedAction.properties[i].value;
  53751. var name = parsedAction.properties[i].name;
  53752. var targetType = parsedAction.properties[i].targetType;
  53753. if (name === "target")
  53754. if (targetType !== null && targetType === "SceneProperties")
  53755. value = target = scene;
  53756. else
  53757. value = target = scene.getNodeByName(value);
  53758. else if (name === "parent")
  53759. value = scene.getNodeByName(value);
  53760. else if (name === "sound")
  53761. value = scene.getSoundByName(value);
  53762. else if (name !== "propertyPath") {
  53763. if (parsedAction.type === 2 && name === "operator")
  53764. value = BABYLON.ValueCondition[value];
  53765. else
  53766. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53767. }
  53768. else {
  53769. propertyPath = value;
  53770. }
  53771. parameters.push(value);
  53772. }
  53773. }
  53774. if (combineArray === null) {
  53775. parameters.push(condition);
  53776. }
  53777. else {
  53778. parameters.push(null);
  53779. }
  53780. // If interpolate value action
  53781. if (parsedAction.name === "InterpolateValueAction") {
  53782. var param = parameters[parameters.length - 2];
  53783. parameters[parameters.length - 1] = param;
  53784. parameters[parameters.length - 2] = condition;
  53785. }
  53786. // Action or condition(s) and not CombineAction
  53787. var newAction = instanciate(parsedAction.name, parameters);
  53788. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53789. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53790. if (action)
  53791. action.then(nothing);
  53792. else
  53793. actionManager.registerAction(nothing);
  53794. action = nothing;
  53795. }
  53796. if (combineArray === null) {
  53797. if (newAction instanceof BABYLON.Condition) {
  53798. condition = newAction;
  53799. newAction = action;
  53800. }
  53801. else {
  53802. condition = null;
  53803. if (action)
  53804. action.then(newAction);
  53805. else
  53806. actionManager.registerAction(newAction);
  53807. }
  53808. }
  53809. else {
  53810. combineArray.push(newAction);
  53811. }
  53812. for (var i = 0; i < parsedAction.children.length; i++)
  53813. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53814. };
  53815. // triggers
  53816. for (var i = 0; i < parsedActions.children.length; i++) {
  53817. var triggerParams;
  53818. var trigger = parsedActions.children[i];
  53819. if (trigger.properties.length > 0) {
  53820. var param = trigger.properties[0].value;
  53821. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53822. if (value._meshId) {
  53823. value.mesh = scene.getMeshByID(value._meshId);
  53824. }
  53825. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53826. }
  53827. else
  53828. triggerParams = ActionManager[trigger.name];
  53829. for (var j = 0; j < trigger.children.length; j++) {
  53830. if (!trigger.detached)
  53831. traverse(trigger.children[j], triggerParams, null, null);
  53832. }
  53833. }
  53834. };
  53835. /**
  53836. * Get a trigger name by index
  53837. * @param trigger defines the trigger index
  53838. * @returns a trigger name
  53839. */
  53840. ActionManager.GetTriggerName = function (trigger) {
  53841. switch (trigger) {
  53842. case 0: return "NothingTrigger";
  53843. case 1: return "OnPickTrigger";
  53844. case 2: return "OnLeftPickTrigger";
  53845. case 3: return "OnRightPickTrigger";
  53846. case 4: return "OnCenterPickTrigger";
  53847. case 5: return "OnPickDownTrigger";
  53848. case 6: return "OnPickUpTrigger";
  53849. case 7: return "OnLongPressTrigger";
  53850. case 8: return "OnPointerOverTrigger";
  53851. case 9: return "OnPointerOutTrigger";
  53852. case 10: return "OnEveryFrameTrigger";
  53853. case 11: return "OnIntersectionEnterTrigger";
  53854. case 12: return "OnIntersectionExitTrigger";
  53855. case 13: return "OnKeyDownTrigger";
  53856. case 14: return "OnKeyUpTrigger";
  53857. case 15: return "OnPickOutTrigger";
  53858. default: return "";
  53859. }
  53860. };
  53861. // Statics
  53862. ActionManager._NothingTrigger = 0;
  53863. ActionManager._OnPickTrigger = 1;
  53864. ActionManager._OnLeftPickTrigger = 2;
  53865. ActionManager._OnRightPickTrigger = 3;
  53866. ActionManager._OnCenterPickTrigger = 4;
  53867. ActionManager._OnPickDownTrigger = 5;
  53868. ActionManager._OnDoublePickTrigger = 6;
  53869. ActionManager._OnPickUpTrigger = 7;
  53870. ActionManager._OnLongPressTrigger = 8;
  53871. ActionManager._OnPointerOverTrigger = 9;
  53872. ActionManager._OnPointerOutTrigger = 10;
  53873. ActionManager._OnEveryFrameTrigger = 11;
  53874. ActionManager._OnIntersectionEnterTrigger = 12;
  53875. ActionManager._OnIntersectionExitTrigger = 13;
  53876. ActionManager._OnKeyDownTrigger = 14;
  53877. ActionManager._OnKeyUpTrigger = 15;
  53878. ActionManager._OnPickOutTrigger = 16;
  53879. /** Gets the list of active triggers */
  53880. ActionManager.Triggers = {};
  53881. return ActionManager;
  53882. }());
  53883. BABYLON.ActionManager = ActionManager;
  53884. })(BABYLON || (BABYLON = {}));
  53885. //# sourceMappingURL=babylon.actionManager.js.map
  53886. var BABYLON;
  53887. (function (BABYLON) {
  53888. var InterpolateValueAction = /** @class */ (function (_super) {
  53889. __extends(InterpolateValueAction, _super);
  53890. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53891. if (duration === void 0) { duration = 1000; }
  53892. var _this = _super.call(this, triggerOptions, condition) || this;
  53893. _this.propertyPath = propertyPath;
  53894. _this.value = value;
  53895. _this.duration = duration;
  53896. _this.stopOtherAnimations = stopOtherAnimations;
  53897. _this.onInterpolationDone = onInterpolationDone;
  53898. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53899. _this._target = _this._effectiveTarget = target;
  53900. return _this;
  53901. }
  53902. InterpolateValueAction.prototype._prepare = function () {
  53903. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53904. this._property = this._getProperty(this.propertyPath);
  53905. };
  53906. InterpolateValueAction.prototype.execute = function () {
  53907. var _this = this;
  53908. var scene = this._actionManager.getScene();
  53909. var keys = [
  53910. {
  53911. frame: 0,
  53912. value: this._effectiveTarget[this._property]
  53913. }, {
  53914. frame: 100,
  53915. value: this.value
  53916. }
  53917. ];
  53918. var dataType;
  53919. if (typeof this.value === "number") {
  53920. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53921. }
  53922. else if (this.value instanceof BABYLON.Color3) {
  53923. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53924. }
  53925. else if (this.value instanceof BABYLON.Vector3) {
  53926. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53927. }
  53928. else if (this.value instanceof BABYLON.Matrix) {
  53929. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53930. }
  53931. else if (this.value instanceof BABYLON.Quaternion) {
  53932. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53933. }
  53934. else {
  53935. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53936. return;
  53937. }
  53938. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53939. animation.setKeys(keys);
  53940. if (this.stopOtherAnimations) {
  53941. scene.stopAnimation(this._effectiveTarget);
  53942. }
  53943. var wrapper = function () {
  53944. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53945. if (_this.onInterpolationDone) {
  53946. _this.onInterpolationDone();
  53947. }
  53948. };
  53949. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53950. };
  53951. InterpolateValueAction.prototype.serialize = function (parent) {
  53952. return _super.prototype._serialize.call(this, {
  53953. name: "InterpolateValueAction",
  53954. properties: [
  53955. BABYLON.Action._GetTargetProperty(this._target),
  53956. { name: "propertyPath", value: this.propertyPath },
  53957. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53958. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53959. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53960. ]
  53961. }, parent);
  53962. };
  53963. return InterpolateValueAction;
  53964. }(BABYLON.Action));
  53965. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53966. })(BABYLON || (BABYLON = {}));
  53967. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53968. var BABYLON;
  53969. (function (BABYLON) {
  53970. var SwitchBooleanAction = /** @class */ (function (_super) {
  53971. __extends(SwitchBooleanAction, _super);
  53972. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53973. var _this = _super.call(this, triggerOptions, condition) || this;
  53974. _this.propertyPath = propertyPath;
  53975. _this._target = _this._effectiveTarget = target;
  53976. return _this;
  53977. }
  53978. SwitchBooleanAction.prototype._prepare = function () {
  53979. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53980. this._property = this._getProperty(this.propertyPath);
  53981. };
  53982. SwitchBooleanAction.prototype.execute = function () {
  53983. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53984. };
  53985. SwitchBooleanAction.prototype.serialize = function (parent) {
  53986. return _super.prototype._serialize.call(this, {
  53987. name: "SwitchBooleanAction",
  53988. properties: [
  53989. BABYLON.Action._GetTargetProperty(this._target),
  53990. { name: "propertyPath", value: this.propertyPath }
  53991. ]
  53992. }, parent);
  53993. };
  53994. return SwitchBooleanAction;
  53995. }(BABYLON.Action));
  53996. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53997. var SetStateAction = /** @class */ (function (_super) {
  53998. __extends(SetStateAction, _super);
  53999. function SetStateAction(triggerOptions, target, value, condition) {
  54000. var _this = _super.call(this, triggerOptions, condition) || this;
  54001. _this.value = value;
  54002. _this._target = target;
  54003. return _this;
  54004. }
  54005. SetStateAction.prototype.execute = function () {
  54006. this._target.state = this.value;
  54007. };
  54008. SetStateAction.prototype.serialize = function (parent) {
  54009. return _super.prototype._serialize.call(this, {
  54010. name: "SetStateAction",
  54011. properties: [
  54012. BABYLON.Action._GetTargetProperty(this._target),
  54013. { name: "value", value: this.value }
  54014. ]
  54015. }, parent);
  54016. };
  54017. return SetStateAction;
  54018. }(BABYLON.Action));
  54019. BABYLON.SetStateAction = SetStateAction;
  54020. var SetValueAction = /** @class */ (function (_super) {
  54021. __extends(SetValueAction, _super);
  54022. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54023. var _this = _super.call(this, triggerOptions, condition) || this;
  54024. _this.propertyPath = propertyPath;
  54025. _this.value = value;
  54026. _this._target = _this._effectiveTarget = target;
  54027. return _this;
  54028. }
  54029. SetValueAction.prototype._prepare = function () {
  54030. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54031. this._property = this._getProperty(this.propertyPath);
  54032. };
  54033. SetValueAction.prototype.execute = function () {
  54034. this._effectiveTarget[this._property] = this.value;
  54035. if (this._target.markAsDirty) {
  54036. this._target.markAsDirty(this._property);
  54037. }
  54038. };
  54039. SetValueAction.prototype.serialize = function (parent) {
  54040. return _super.prototype._serialize.call(this, {
  54041. name: "SetValueAction",
  54042. properties: [
  54043. BABYLON.Action._GetTargetProperty(this._target),
  54044. { name: "propertyPath", value: this.propertyPath },
  54045. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54046. ]
  54047. }, parent);
  54048. };
  54049. return SetValueAction;
  54050. }(BABYLON.Action));
  54051. BABYLON.SetValueAction = SetValueAction;
  54052. var IncrementValueAction = /** @class */ (function (_super) {
  54053. __extends(IncrementValueAction, _super);
  54054. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54055. var _this = _super.call(this, triggerOptions, condition) || this;
  54056. _this.propertyPath = propertyPath;
  54057. _this.value = value;
  54058. _this._target = _this._effectiveTarget = target;
  54059. return _this;
  54060. }
  54061. IncrementValueAction.prototype._prepare = function () {
  54062. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54063. this._property = this._getProperty(this.propertyPath);
  54064. if (typeof this._effectiveTarget[this._property] !== "number") {
  54065. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54066. }
  54067. };
  54068. IncrementValueAction.prototype.execute = function () {
  54069. this._effectiveTarget[this._property] += this.value;
  54070. if (this._target.markAsDirty) {
  54071. this._target.markAsDirty(this._property);
  54072. }
  54073. };
  54074. IncrementValueAction.prototype.serialize = function (parent) {
  54075. return _super.prototype._serialize.call(this, {
  54076. name: "IncrementValueAction",
  54077. properties: [
  54078. BABYLON.Action._GetTargetProperty(this._target),
  54079. { name: "propertyPath", value: this.propertyPath },
  54080. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54081. ]
  54082. }, parent);
  54083. };
  54084. return IncrementValueAction;
  54085. }(BABYLON.Action));
  54086. BABYLON.IncrementValueAction = IncrementValueAction;
  54087. var PlayAnimationAction = /** @class */ (function (_super) {
  54088. __extends(PlayAnimationAction, _super);
  54089. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54090. var _this = _super.call(this, triggerOptions, condition) || this;
  54091. _this.from = from;
  54092. _this.to = to;
  54093. _this.loop = loop;
  54094. _this._target = target;
  54095. return _this;
  54096. }
  54097. PlayAnimationAction.prototype._prepare = function () {
  54098. };
  54099. PlayAnimationAction.prototype.execute = function () {
  54100. var scene = this._actionManager.getScene();
  54101. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54102. };
  54103. PlayAnimationAction.prototype.serialize = function (parent) {
  54104. return _super.prototype._serialize.call(this, {
  54105. name: "PlayAnimationAction",
  54106. properties: [
  54107. BABYLON.Action._GetTargetProperty(this._target),
  54108. { name: "from", value: String(this.from) },
  54109. { name: "to", value: String(this.to) },
  54110. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54111. ]
  54112. }, parent);
  54113. };
  54114. return PlayAnimationAction;
  54115. }(BABYLON.Action));
  54116. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54117. var StopAnimationAction = /** @class */ (function (_super) {
  54118. __extends(StopAnimationAction, _super);
  54119. function StopAnimationAction(triggerOptions, target, condition) {
  54120. var _this = _super.call(this, triggerOptions, condition) || this;
  54121. _this._target = target;
  54122. return _this;
  54123. }
  54124. StopAnimationAction.prototype._prepare = function () {
  54125. };
  54126. StopAnimationAction.prototype.execute = function () {
  54127. var scene = this._actionManager.getScene();
  54128. scene.stopAnimation(this._target);
  54129. };
  54130. StopAnimationAction.prototype.serialize = function (parent) {
  54131. return _super.prototype._serialize.call(this, {
  54132. name: "StopAnimationAction",
  54133. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54134. }, parent);
  54135. };
  54136. return StopAnimationAction;
  54137. }(BABYLON.Action));
  54138. BABYLON.StopAnimationAction = StopAnimationAction;
  54139. var DoNothingAction = /** @class */ (function (_super) {
  54140. __extends(DoNothingAction, _super);
  54141. function DoNothingAction(triggerOptions, condition) {
  54142. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54143. return _super.call(this, triggerOptions, condition) || this;
  54144. }
  54145. DoNothingAction.prototype.execute = function () {
  54146. };
  54147. DoNothingAction.prototype.serialize = function (parent) {
  54148. return _super.prototype._serialize.call(this, {
  54149. name: "DoNothingAction",
  54150. properties: []
  54151. }, parent);
  54152. };
  54153. return DoNothingAction;
  54154. }(BABYLON.Action));
  54155. BABYLON.DoNothingAction = DoNothingAction;
  54156. var CombineAction = /** @class */ (function (_super) {
  54157. __extends(CombineAction, _super);
  54158. function CombineAction(triggerOptions, children, condition) {
  54159. var _this = _super.call(this, triggerOptions, condition) || this;
  54160. _this.children = children;
  54161. return _this;
  54162. }
  54163. CombineAction.prototype._prepare = function () {
  54164. for (var index = 0; index < this.children.length; index++) {
  54165. this.children[index]._actionManager = this._actionManager;
  54166. this.children[index]._prepare();
  54167. }
  54168. };
  54169. CombineAction.prototype.execute = function (evt) {
  54170. for (var index = 0; index < this.children.length; index++) {
  54171. this.children[index].execute(evt);
  54172. }
  54173. };
  54174. CombineAction.prototype.serialize = function (parent) {
  54175. var serializationObject = _super.prototype._serialize.call(this, {
  54176. name: "CombineAction",
  54177. properties: [],
  54178. combine: []
  54179. }, parent);
  54180. for (var i = 0; i < this.children.length; i++) {
  54181. serializationObject.combine.push(this.children[i].serialize(null));
  54182. }
  54183. return serializationObject;
  54184. };
  54185. return CombineAction;
  54186. }(BABYLON.Action));
  54187. BABYLON.CombineAction = CombineAction;
  54188. var ExecuteCodeAction = /** @class */ (function (_super) {
  54189. __extends(ExecuteCodeAction, _super);
  54190. function ExecuteCodeAction(triggerOptions, func, condition) {
  54191. var _this = _super.call(this, triggerOptions, condition) || this;
  54192. _this.func = func;
  54193. return _this;
  54194. }
  54195. ExecuteCodeAction.prototype.execute = function (evt) {
  54196. this.func(evt);
  54197. };
  54198. return ExecuteCodeAction;
  54199. }(BABYLON.Action));
  54200. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54201. var SetParentAction = /** @class */ (function (_super) {
  54202. __extends(SetParentAction, _super);
  54203. function SetParentAction(triggerOptions, target, parent, condition) {
  54204. var _this = _super.call(this, triggerOptions, condition) || this;
  54205. _this._target = target;
  54206. _this._parent = parent;
  54207. return _this;
  54208. }
  54209. SetParentAction.prototype._prepare = function () {
  54210. };
  54211. SetParentAction.prototype.execute = function () {
  54212. if (this._target.parent === this._parent) {
  54213. return;
  54214. }
  54215. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54216. invertParentWorldMatrix.invert();
  54217. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54218. this._target.parent = this._parent;
  54219. };
  54220. SetParentAction.prototype.serialize = function (parent) {
  54221. return _super.prototype._serialize.call(this, {
  54222. name: "SetParentAction",
  54223. properties: [
  54224. BABYLON.Action._GetTargetProperty(this._target),
  54225. BABYLON.Action._GetTargetProperty(this._parent),
  54226. ]
  54227. }, parent);
  54228. };
  54229. return SetParentAction;
  54230. }(BABYLON.Action));
  54231. BABYLON.SetParentAction = SetParentAction;
  54232. var PlaySoundAction = /** @class */ (function (_super) {
  54233. __extends(PlaySoundAction, _super);
  54234. function PlaySoundAction(triggerOptions, sound, condition) {
  54235. var _this = _super.call(this, triggerOptions, condition) || this;
  54236. _this._sound = sound;
  54237. return _this;
  54238. }
  54239. PlaySoundAction.prototype._prepare = function () {
  54240. };
  54241. PlaySoundAction.prototype.execute = function () {
  54242. if (this._sound !== undefined)
  54243. this._sound.play();
  54244. };
  54245. PlaySoundAction.prototype.serialize = function (parent) {
  54246. return _super.prototype._serialize.call(this, {
  54247. name: "PlaySoundAction",
  54248. properties: [{ name: "sound", value: this._sound.name }]
  54249. }, parent);
  54250. };
  54251. return PlaySoundAction;
  54252. }(BABYLON.Action));
  54253. BABYLON.PlaySoundAction = PlaySoundAction;
  54254. var StopSoundAction = /** @class */ (function (_super) {
  54255. __extends(StopSoundAction, _super);
  54256. function StopSoundAction(triggerOptions, sound, condition) {
  54257. var _this = _super.call(this, triggerOptions, condition) || this;
  54258. _this._sound = sound;
  54259. return _this;
  54260. }
  54261. StopSoundAction.prototype._prepare = function () {
  54262. };
  54263. StopSoundAction.prototype.execute = function () {
  54264. if (this._sound !== undefined)
  54265. this._sound.stop();
  54266. };
  54267. StopSoundAction.prototype.serialize = function (parent) {
  54268. return _super.prototype._serialize.call(this, {
  54269. name: "StopSoundAction",
  54270. properties: [{ name: "sound", value: this._sound.name }]
  54271. }, parent);
  54272. };
  54273. return StopSoundAction;
  54274. }(BABYLON.Action));
  54275. BABYLON.StopSoundAction = StopSoundAction;
  54276. })(BABYLON || (BABYLON = {}));
  54277. //# sourceMappingURL=babylon.directActions.js.map
  54278. var BABYLON;
  54279. (function (BABYLON) {
  54280. var SpriteManager = /** @class */ (function () {
  54281. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54282. if (epsilon === void 0) { epsilon = 0.01; }
  54283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54284. this.name = name;
  54285. this.sprites = new Array();
  54286. this.renderingGroupId = 0;
  54287. this.layerMask = 0x0FFFFFFF;
  54288. this.fogEnabled = true;
  54289. this.isPickable = false;
  54290. /**
  54291. * An event triggered when the manager is disposed.
  54292. */
  54293. this.onDisposeObservable = new BABYLON.Observable();
  54294. this._vertexBuffers = {};
  54295. this._capacity = capacity;
  54296. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54297. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54298. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54299. if (cellSize.width && cellSize.height) {
  54300. this.cellWidth = cellSize.width;
  54301. this.cellHeight = cellSize.height;
  54302. }
  54303. else if (cellSize !== undefined) {
  54304. this.cellWidth = cellSize;
  54305. this.cellHeight = cellSize;
  54306. }
  54307. else {
  54308. return;
  54309. }
  54310. this._epsilon = epsilon;
  54311. this._scene = scene;
  54312. this._scene.spriteManagers.push(this);
  54313. var indices = [];
  54314. var index = 0;
  54315. for (var count = 0; count < capacity; count++) {
  54316. indices.push(index);
  54317. indices.push(index + 1);
  54318. indices.push(index + 2);
  54319. indices.push(index);
  54320. indices.push(index + 2);
  54321. indices.push(index + 3);
  54322. index += 4;
  54323. }
  54324. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54325. // VBO
  54326. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54327. this._vertexData = new Float32Array(capacity * 16 * 4);
  54328. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54329. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54330. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54331. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54332. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54333. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54334. this._vertexBuffers["options"] = options;
  54335. this._vertexBuffers["cellInfo"] = cellInfo;
  54336. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54337. // Effects
  54338. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54339. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54340. }
  54341. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54342. set: function (callback) {
  54343. if (this._onDisposeObserver) {
  54344. this.onDisposeObservable.remove(this._onDisposeObserver);
  54345. }
  54346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54347. },
  54348. enumerable: true,
  54349. configurable: true
  54350. });
  54351. Object.defineProperty(SpriteManager.prototype, "texture", {
  54352. get: function () {
  54353. return this._spriteTexture;
  54354. },
  54355. set: function (value) {
  54356. this._spriteTexture = value;
  54357. },
  54358. enumerable: true,
  54359. configurable: true
  54360. });
  54361. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54362. var arrayOffset = index * 16;
  54363. if (offsetX === 0)
  54364. offsetX = this._epsilon;
  54365. else if (offsetX === 1)
  54366. offsetX = 1 - this._epsilon;
  54367. if (offsetY === 0)
  54368. offsetY = this._epsilon;
  54369. else if (offsetY === 1)
  54370. offsetY = 1 - this._epsilon;
  54371. this._vertexData[arrayOffset] = sprite.position.x;
  54372. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54373. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54374. this._vertexData[arrayOffset + 3] = sprite.angle;
  54375. this._vertexData[arrayOffset + 4] = sprite.width;
  54376. this._vertexData[arrayOffset + 5] = sprite.height;
  54377. this._vertexData[arrayOffset + 6] = offsetX;
  54378. this._vertexData[arrayOffset + 7] = offsetY;
  54379. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54380. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54381. var offset = (sprite.cellIndex / rowSize) >> 0;
  54382. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54383. this._vertexData[arrayOffset + 11] = offset;
  54384. // Color
  54385. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54386. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54387. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54388. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54389. };
  54390. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54391. var count = Math.min(this._capacity, this.sprites.length);
  54392. var min = BABYLON.Vector3.Zero();
  54393. var max = BABYLON.Vector3.Zero();
  54394. var distance = Number.MAX_VALUE;
  54395. var currentSprite = null;
  54396. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54397. var cameraView = camera.getViewMatrix();
  54398. for (var index = 0; index < count; index++) {
  54399. var sprite = this.sprites[index];
  54400. if (!sprite) {
  54401. continue;
  54402. }
  54403. if (predicate) {
  54404. if (!predicate(sprite)) {
  54405. continue;
  54406. }
  54407. }
  54408. else if (!sprite.isPickable) {
  54409. continue;
  54410. }
  54411. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54412. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54413. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54414. if (ray.intersectsBoxMinMax(min, max)) {
  54415. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54416. if (distance > currentDistance) {
  54417. distance = currentDistance;
  54418. currentSprite = sprite;
  54419. if (fastCheck) {
  54420. break;
  54421. }
  54422. }
  54423. }
  54424. }
  54425. if (currentSprite) {
  54426. var result = new BABYLON.PickingInfo();
  54427. result.hit = true;
  54428. result.pickedSprite = currentSprite;
  54429. result.distance = distance;
  54430. return result;
  54431. }
  54432. return null;
  54433. };
  54434. SpriteManager.prototype.render = function () {
  54435. // Check
  54436. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54437. return;
  54438. var engine = this._scene.getEngine();
  54439. var baseSize = this._spriteTexture.getBaseSize();
  54440. // Sprites
  54441. var deltaTime = engine.getDeltaTime();
  54442. var max = Math.min(this._capacity, this.sprites.length);
  54443. var rowSize = baseSize.width / this.cellWidth;
  54444. var offset = 0;
  54445. for (var index = 0; index < max; index++) {
  54446. var sprite = this.sprites[index];
  54447. if (!sprite) {
  54448. continue;
  54449. }
  54450. sprite._animate(deltaTime);
  54451. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54452. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54453. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54454. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54455. }
  54456. this._buffer.update(this._vertexData);
  54457. // Render
  54458. var effect = this._effectBase;
  54459. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54460. effect = this._effectFog;
  54461. }
  54462. engine.enableEffect(effect);
  54463. var viewMatrix = this._scene.getViewMatrix();
  54464. effect.setTexture("diffuseSampler", this._spriteTexture);
  54465. effect.setMatrix("view", viewMatrix);
  54466. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54467. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54468. // Fog
  54469. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54470. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54471. effect.setColor3("vFogColor", this._scene.fogColor);
  54472. }
  54473. // VBOs
  54474. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54475. // Draw order
  54476. engine.setDepthFunctionToLessOrEqual();
  54477. effect.setBool("alphaTest", true);
  54478. engine.setColorWrite(false);
  54479. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54480. engine.setColorWrite(true);
  54481. effect.setBool("alphaTest", false);
  54482. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54483. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54484. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54485. };
  54486. SpriteManager.prototype.dispose = function () {
  54487. if (this._buffer) {
  54488. this._buffer.dispose();
  54489. this._buffer = null;
  54490. }
  54491. if (this._indexBuffer) {
  54492. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54493. this._indexBuffer = null;
  54494. }
  54495. if (this._spriteTexture) {
  54496. this._spriteTexture.dispose();
  54497. this._spriteTexture = null;
  54498. }
  54499. // Remove from scene
  54500. var index = this._scene.spriteManagers.indexOf(this);
  54501. this._scene.spriteManagers.splice(index, 1);
  54502. // Callback
  54503. this.onDisposeObservable.notifyObservers(this);
  54504. this.onDisposeObservable.clear();
  54505. };
  54506. return SpriteManager;
  54507. }());
  54508. BABYLON.SpriteManager = SpriteManager;
  54509. })(BABYLON || (BABYLON = {}));
  54510. //# sourceMappingURL=babylon.spriteManager.js.map
  54511. var BABYLON;
  54512. (function (BABYLON) {
  54513. var Sprite = /** @class */ (function () {
  54514. function Sprite(name, manager) {
  54515. this.name = name;
  54516. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54517. this.width = 1.0;
  54518. this.height = 1.0;
  54519. this.angle = 0;
  54520. this.cellIndex = 0;
  54521. this.invertU = 0;
  54522. this.invertV = 0;
  54523. this.animations = new Array();
  54524. this.isPickable = false;
  54525. this._animationStarted = false;
  54526. this._loopAnimation = false;
  54527. this._fromIndex = 0;
  54528. this._toIndex = 0;
  54529. this._delay = 0;
  54530. this._direction = 1;
  54531. this._time = 0;
  54532. this._manager = manager;
  54533. this._manager.sprites.push(this);
  54534. this.position = BABYLON.Vector3.Zero();
  54535. }
  54536. Object.defineProperty(Sprite.prototype, "size", {
  54537. get: function () {
  54538. return this.width;
  54539. },
  54540. set: function (value) {
  54541. this.width = value;
  54542. this.height = value;
  54543. },
  54544. enumerable: true,
  54545. configurable: true
  54546. });
  54547. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54548. this._fromIndex = from;
  54549. this._toIndex = to;
  54550. this._loopAnimation = loop;
  54551. this._delay = delay;
  54552. this._animationStarted = true;
  54553. this._direction = from < to ? 1 : -1;
  54554. this.cellIndex = from;
  54555. this._time = 0;
  54556. this._onAnimationEnd = onAnimationEnd;
  54557. };
  54558. Sprite.prototype.stopAnimation = function () {
  54559. this._animationStarted = false;
  54560. };
  54561. Sprite.prototype._animate = function (deltaTime) {
  54562. if (!this._animationStarted)
  54563. return;
  54564. this._time += deltaTime;
  54565. if (this._time > this._delay) {
  54566. this._time = this._time % this._delay;
  54567. this.cellIndex += this._direction;
  54568. if (this.cellIndex > this._toIndex) {
  54569. if (this._loopAnimation) {
  54570. this.cellIndex = this._fromIndex;
  54571. }
  54572. else {
  54573. this.cellIndex = this._toIndex;
  54574. this._animationStarted = false;
  54575. if (this._onAnimationEnd) {
  54576. this._onAnimationEnd();
  54577. }
  54578. if (this.disposeWhenFinishedAnimating) {
  54579. this.dispose();
  54580. }
  54581. }
  54582. }
  54583. }
  54584. };
  54585. Sprite.prototype.dispose = function () {
  54586. for (var i = 0; i < this._manager.sprites.length; i++) {
  54587. if (this._manager.sprites[i] == this) {
  54588. this._manager.sprites.splice(i, 1);
  54589. }
  54590. }
  54591. };
  54592. return Sprite;
  54593. }());
  54594. BABYLON.Sprite = Sprite;
  54595. })(BABYLON || (BABYLON = {}));
  54596. //# sourceMappingURL=babylon.sprite.js.map
  54597. var BABYLON;
  54598. (function (BABYLON) {
  54599. var IntersectionInfo = /** @class */ (function () {
  54600. function IntersectionInfo(bu, bv, distance) {
  54601. this.bu = bu;
  54602. this.bv = bv;
  54603. this.distance = distance;
  54604. this.faceId = 0;
  54605. this.subMeshId = 0;
  54606. }
  54607. return IntersectionInfo;
  54608. }());
  54609. BABYLON.IntersectionInfo = IntersectionInfo;
  54610. var PickingInfo = /** @class */ (function () {
  54611. function PickingInfo() {
  54612. this.hit = false;
  54613. this.distance = 0;
  54614. this.pickedPoint = null;
  54615. this.pickedMesh = null;
  54616. this.bu = 0;
  54617. this.bv = 0;
  54618. this.faceId = -1;
  54619. this.subMeshId = 0;
  54620. this.pickedSprite = null;
  54621. }
  54622. // Methods
  54623. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54624. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54625. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54626. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54627. return null;
  54628. }
  54629. var indices = this.pickedMesh.getIndices();
  54630. if (!indices) {
  54631. return null;
  54632. }
  54633. var result;
  54634. if (useVerticesNormals) {
  54635. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54636. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54637. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54638. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54639. normal0 = normal0.scale(this.bu);
  54640. normal1 = normal1.scale(this.bv);
  54641. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54642. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54643. }
  54644. else {
  54645. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54646. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54647. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54648. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54649. var p1p2 = vertex1.subtract(vertex2);
  54650. var p3p2 = vertex3.subtract(vertex2);
  54651. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54652. }
  54653. if (useWorldCoordinates) {
  54654. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54655. }
  54656. return BABYLON.Vector3.Normalize(result);
  54657. };
  54658. PickingInfo.prototype.getTextureCoordinates = function () {
  54659. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54660. return null;
  54661. }
  54662. var indices = this.pickedMesh.getIndices();
  54663. if (!indices) {
  54664. return null;
  54665. }
  54666. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54667. if (!uvs) {
  54668. return null;
  54669. }
  54670. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54671. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54672. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54673. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54674. uv1 = uv1.scale(this.bu);
  54675. uv2 = uv2.scale(this.bv);
  54676. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54677. };
  54678. return PickingInfo;
  54679. }());
  54680. BABYLON.PickingInfo = PickingInfo;
  54681. })(BABYLON || (BABYLON = {}));
  54682. //# sourceMappingURL=babylon.pickingInfo.js.map
  54683. var BABYLON;
  54684. (function (BABYLON) {
  54685. var Ray = /** @class */ (function () {
  54686. function Ray(origin, direction, length) {
  54687. if (length === void 0) { length = Number.MAX_VALUE; }
  54688. this.origin = origin;
  54689. this.direction = direction;
  54690. this.length = length;
  54691. }
  54692. // Methods
  54693. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54694. var d = 0.0;
  54695. var maxValue = Number.MAX_VALUE;
  54696. var inv;
  54697. var min;
  54698. var max;
  54699. var temp;
  54700. if (Math.abs(this.direction.x) < 0.0000001) {
  54701. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54702. return false;
  54703. }
  54704. }
  54705. else {
  54706. inv = 1.0 / this.direction.x;
  54707. min = (minimum.x - this.origin.x) * inv;
  54708. max = (maximum.x - this.origin.x) * inv;
  54709. if (max === -Infinity) {
  54710. max = Infinity;
  54711. }
  54712. if (min > max) {
  54713. temp = min;
  54714. min = max;
  54715. max = temp;
  54716. }
  54717. d = Math.max(min, d);
  54718. maxValue = Math.min(max, maxValue);
  54719. if (d > maxValue) {
  54720. return false;
  54721. }
  54722. }
  54723. if (Math.abs(this.direction.y) < 0.0000001) {
  54724. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54725. return false;
  54726. }
  54727. }
  54728. else {
  54729. inv = 1.0 / this.direction.y;
  54730. min = (minimum.y - this.origin.y) * inv;
  54731. max = (maximum.y - this.origin.y) * inv;
  54732. if (max === -Infinity) {
  54733. max = Infinity;
  54734. }
  54735. if (min > max) {
  54736. temp = min;
  54737. min = max;
  54738. max = temp;
  54739. }
  54740. d = Math.max(min, d);
  54741. maxValue = Math.min(max, maxValue);
  54742. if (d > maxValue) {
  54743. return false;
  54744. }
  54745. }
  54746. if (Math.abs(this.direction.z) < 0.0000001) {
  54747. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54748. return false;
  54749. }
  54750. }
  54751. else {
  54752. inv = 1.0 / this.direction.z;
  54753. min = (minimum.z - this.origin.z) * inv;
  54754. max = (maximum.z - this.origin.z) * inv;
  54755. if (max === -Infinity) {
  54756. max = Infinity;
  54757. }
  54758. if (min > max) {
  54759. temp = min;
  54760. min = max;
  54761. max = temp;
  54762. }
  54763. d = Math.max(min, d);
  54764. maxValue = Math.min(max, maxValue);
  54765. if (d > maxValue) {
  54766. return false;
  54767. }
  54768. }
  54769. return true;
  54770. };
  54771. Ray.prototype.intersectsBox = function (box) {
  54772. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54773. };
  54774. Ray.prototype.intersectsSphere = function (sphere) {
  54775. var x = sphere.center.x - this.origin.x;
  54776. var y = sphere.center.y - this.origin.y;
  54777. var z = sphere.center.z - this.origin.z;
  54778. var pyth = (x * x) + (y * y) + (z * z);
  54779. var rr = sphere.radius * sphere.radius;
  54780. if (pyth <= rr) {
  54781. return true;
  54782. }
  54783. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54784. if (dot < 0.0) {
  54785. return false;
  54786. }
  54787. var temp = pyth - (dot * dot);
  54788. return temp <= rr;
  54789. };
  54790. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54791. if (!this._edge1) {
  54792. this._edge1 = BABYLON.Vector3.Zero();
  54793. this._edge2 = BABYLON.Vector3.Zero();
  54794. this._pvec = BABYLON.Vector3.Zero();
  54795. this._tvec = BABYLON.Vector3.Zero();
  54796. this._qvec = BABYLON.Vector3.Zero();
  54797. }
  54798. vertex1.subtractToRef(vertex0, this._edge1);
  54799. vertex2.subtractToRef(vertex0, this._edge2);
  54800. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54801. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54802. if (det === 0) {
  54803. return null;
  54804. }
  54805. var invdet = 1 / det;
  54806. this.origin.subtractToRef(vertex0, this._tvec);
  54807. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54808. if (bu < 0 || bu > 1.0) {
  54809. return null;
  54810. }
  54811. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54812. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54813. if (bv < 0 || bu + bv > 1.0) {
  54814. return null;
  54815. }
  54816. //check if the distance is longer than the predefined length.
  54817. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54818. if (distance > this.length) {
  54819. return null;
  54820. }
  54821. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54822. };
  54823. Ray.prototype.intersectsPlane = function (plane) {
  54824. var distance;
  54825. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54826. if (Math.abs(result1) < 9.99999997475243E-07) {
  54827. return null;
  54828. }
  54829. else {
  54830. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54831. distance = (-plane.d - result2) / result1;
  54832. if (distance < 0.0) {
  54833. if (distance < -9.99999997475243E-07) {
  54834. return null;
  54835. }
  54836. else {
  54837. return 0;
  54838. }
  54839. }
  54840. return distance;
  54841. }
  54842. };
  54843. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54844. var tm = BABYLON.Tmp.Matrix[0];
  54845. mesh.getWorldMatrix().invertToRef(tm);
  54846. if (this._tmpRay) {
  54847. Ray.TransformToRef(this, tm, this._tmpRay);
  54848. }
  54849. else {
  54850. this._tmpRay = Ray.Transform(this, tm);
  54851. }
  54852. return mesh.intersects(this._tmpRay, fastCheck);
  54853. };
  54854. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54855. if (results) {
  54856. results.length = 0;
  54857. }
  54858. else {
  54859. results = [];
  54860. }
  54861. for (var i = 0; i < meshes.length; i++) {
  54862. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54863. if (pickInfo.hit) {
  54864. results.push(pickInfo);
  54865. }
  54866. }
  54867. results.sort(this._comparePickingInfo);
  54868. return results;
  54869. };
  54870. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54871. if (pickingInfoA.distance < pickingInfoB.distance) {
  54872. return -1;
  54873. }
  54874. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54875. return 1;
  54876. }
  54877. else {
  54878. return 0;
  54879. }
  54880. };
  54881. /**
  54882. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54883. * @param sega the first point of the segment to test the intersection against
  54884. * @param segb the second point of the segment to test the intersection against
  54885. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54886. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54887. */
  54888. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54889. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54890. var u = segb.subtract(sega);
  54891. var v = rsegb.subtract(this.origin);
  54892. var w = sega.subtract(this.origin);
  54893. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54894. var b = BABYLON.Vector3.Dot(u, v);
  54895. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54896. var d = BABYLON.Vector3.Dot(u, w);
  54897. var e = BABYLON.Vector3.Dot(v, w);
  54898. var D = a * c - b * b; // always >= 0
  54899. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54900. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54901. // compute the line parameters of the two closest points
  54902. if (D < Ray.smallnum) { // the lines are almost parallel
  54903. sN = 0.0; // force using point P0 on segment S1
  54904. sD = 1.0; // to prevent possible division by 0.0 later
  54905. tN = e;
  54906. tD = c;
  54907. }
  54908. else { // get the closest points on the infinite lines
  54909. sN = (b * e - c * d);
  54910. tN = (a * e - b * d);
  54911. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54912. sN = 0.0;
  54913. tN = e;
  54914. tD = c;
  54915. }
  54916. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54917. sN = sD;
  54918. tN = e + b;
  54919. tD = c;
  54920. }
  54921. }
  54922. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54923. tN = 0.0;
  54924. // recompute sc for this edge
  54925. if (-d < 0.0) {
  54926. sN = 0.0;
  54927. }
  54928. else if (-d > a)
  54929. sN = sD;
  54930. else {
  54931. sN = -d;
  54932. sD = a;
  54933. }
  54934. }
  54935. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54936. tN = tD;
  54937. // recompute sc for this edge
  54938. if ((-d + b) < 0.0) {
  54939. sN = 0;
  54940. }
  54941. else if ((-d + b) > a) {
  54942. sN = sD;
  54943. }
  54944. else {
  54945. sN = (-d + b);
  54946. sD = a;
  54947. }
  54948. }
  54949. // finally do the division to get sc and tc
  54950. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54951. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54952. // get the difference of the two closest points
  54953. var qtc = v.multiplyByFloats(tc, tc, tc);
  54954. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54955. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54956. if (isIntersected) {
  54957. return qtc.length();
  54958. }
  54959. return -1;
  54960. };
  54961. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54962. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54963. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54964. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54965. this.direction.normalize();
  54966. return this;
  54967. };
  54968. // Statics
  54969. Ray.Zero = function () {
  54970. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54971. };
  54972. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54973. var result = Ray.Zero();
  54974. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54975. };
  54976. /**
  54977. * 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
  54978. * transformed to the given world matrix.
  54979. * @param origin The origin point
  54980. * @param end The end point
  54981. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54982. */
  54983. Ray.CreateNewFromTo = function (origin, end, world) {
  54984. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54985. var direction = end.subtract(origin);
  54986. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54987. direction.normalize();
  54988. return Ray.Transform(new Ray(origin, direction, length), world);
  54989. };
  54990. Ray.Transform = function (ray, matrix) {
  54991. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54992. Ray.TransformToRef(ray, matrix, result);
  54993. return result;
  54994. };
  54995. Ray.TransformToRef = function (ray, matrix, result) {
  54996. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54997. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54998. result.length = ray.length;
  54999. var dir = result.direction;
  55000. var len = dir.length();
  55001. if (!(len === 0 || len === 1)) {
  55002. var num = 1.0 / len;
  55003. dir.x *= num;
  55004. dir.y *= num;
  55005. dir.z *= num;
  55006. result.length *= len;
  55007. }
  55008. };
  55009. Ray.smallnum = 0.00000001;
  55010. Ray.rayl = 10e8;
  55011. return Ray;
  55012. }());
  55013. BABYLON.Ray = Ray;
  55014. })(BABYLON || (BABYLON = {}));
  55015. //# sourceMappingURL=babylon.ray.js.map
  55016. var BABYLON;
  55017. (function (BABYLON) {
  55018. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55019. if (boxMin.x > sphereCenter.x + sphereRadius)
  55020. return false;
  55021. if (sphereCenter.x - sphereRadius > boxMax.x)
  55022. return false;
  55023. if (boxMin.y > sphereCenter.y + sphereRadius)
  55024. return false;
  55025. if (sphereCenter.y - sphereRadius > boxMax.y)
  55026. return false;
  55027. if (boxMin.z > sphereCenter.z + sphereRadius)
  55028. return false;
  55029. if (sphereCenter.z - sphereRadius > boxMax.z)
  55030. return false;
  55031. return true;
  55032. };
  55033. var getLowestRoot = (function () {
  55034. var result = { root: 0, found: false };
  55035. return function (a, b, c, maxR) {
  55036. result.root = 0;
  55037. result.found = false;
  55038. var determinant = b * b - 4.0 * a * c;
  55039. if (determinant < 0)
  55040. return result;
  55041. var sqrtD = Math.sqrt(determinant);
  55042. var r1 = (-b - sqrtD) / (2.0 * a);
  55043. var r2 = (-b + sqrtD) / (2.0 * a);
  55044. if (r1 > r2) {
  55045. var temp = r2;
  55046. r2 = r1;
  55047. r1 = temp;
  55048. }
  55049. if (r1 > 0 && r1 < maxR) {
  55050. result.root = r1;
  55051. result.found = true;
  55052. return result;
  55053. }
  55054. if (r2 > 0 && r2 < maxR) {
  55055. result.root = r2;
  55056. result.found = true;
  55057. return result;
  55058. }
  55059. return result;
  55060. };
  55061. })();
  55062. var Collider = /** @class */ (function () {
  55063. function Collider() {
  55064. this._collisionPoint = BABYLON.Vector3.Zero();
  55065. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55066. this._tempVector = BABYLON.Vector3.Zero();
  55067. this._tempVector2 = BABYLON.Vector3.Zero();
  55068. this._tempVector3 = BABYLON.Vector3.Zero();
  55069. this._tempVector4 = BABYLON.Vector3.Zero();
  55070. this._edge = BABYLON.Vector3.Zero();
  55071. this._baseToVertex = BABYLON.Vector3.Zero();
  55072. this._destinationPoint = BABYLON.Vector3.Zero();
  55073. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55074. this._displacementVector = BABYLON.Vector3.Zero();
  55075. this._radius = BABYLON.Vector3.One();
  55076. this._retry = 0;
  55077. this._basePointWorld = BABYLON.Vector3.Zero();
  55078. this._velocityWorld = BABYLON.Vector3.Zero();
  55079. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55080. this._collisionMask = -1;
  55081. }
  55082. Object.defineProperty(Collider.prototype, "collisionMask", {
  55083. get: function () {
  55084. return this._collisionMask;
  55085. },
  55086. set: function (mask) {
  55087. this._collisionMask = !isNaN(mask) ? mask : -1;
  55088. },
  55089. enumerable: true,
  55090. configurable: true
  55091. });
  55092. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55093. /**
  55094. * Gets the plane normal used to compute the sliding response (in local space)
  55095. */
  55096. get: function () {
  55097. return this._slidePlaneNormal;
  55098. },
  55099. enumerable: true,
  55100. configurable: true
  55101. });
  55102. // Methods
  55103. Collider.prototype._initialize = function (source, dir, e) {
  55104. this._velocity = dir;
  55105. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55106. this._basePoint = source;
  55107. source.multiplyToRef(this._radius, this._basePointWorld);
  55108. dir.multiplyToRef(this._radius, this._velocityWorld);
  55109. this._velocityWorldLength = this._velocityWorld.length();
  55110. this._epsilon = e;
  55111. this.collisionFound = false;
  55112. };
  55113. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55114. pa.subtractToRef(point, this._tempVector);
  55115. pb.subtractToRef(point, this._tempVector2);
  55116. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55117. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55118. if (d < 0)
  55119. return false;
  55120. pc.subtractToRef(point, this._tempVector3);
  55121. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55122. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55123. if (d < 0)
  55124. return false;
  55125. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55126. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55127. return d >= 0;
  55128. };
  55129. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55130. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55131. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55132. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55133. return false;
  55134. }
  55135. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55136. return false;
  55137. return true;
  55138. };
  55139. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55140. var t0;
  55141. var embeddedInPlane = false;
  55142. //defensive programming, actually not needed.
  55143. if (!trianglePlaneArray) {
  55144. trianglePlaneArray = [];
  55145. }
  55146. if (!trianglePlaneArray[faceIndex]) {
  55147. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55148. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55149. }
  55150. var trianglePlane = trianglePlaneArray[faceIndex];
  55151. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55152. return;
  55153. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55154. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55155. if (normalDotVelocity == 0) {
  55156. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55157. return;
  55158. embeddedInPlane = true;
  55159. t0 = 0;
  55160. }
  55161. else {
  55162. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55163. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55164. if (t0 > t1) {
  55165. var temp = t1;
  55166. t1 = t0;
  55167. t0 = temp;
  55168. }
  55169. if (t0 > 1.0 || t1 < 0.0)
  55170. return;
  55171. if (t0 < 0)
  55172. t0 = 0;
  55173. if (t0 > 1.0)
  55174. t0 = 1.0;
  55175. }
  55176. this._collisionPoint.copyFromFloats(0, 0, 0);
  55177. var found = false;
  55178. var t = 1.0;
  55179. if (!embeddedInPlane) {
  55180. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55181. this._velocity.scaleToRef(t0, this._tempVector);
  55182. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55183. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55184. found = true;
  55185. t = t0;
  55186. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55187. }
  55188. }
  55189. if (!found) {
  55190. var velocitySquaredLength = this._velocity.lengthSquared();
  55191. var a = velocitySquaredLength;
  55192. this._basePoint.subtractToRef(p1, this._tempVector);
  55193. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55194. var c = this._tempVector.lengthSquared() - 1.0;
  55195. var lowestRoot = getLowestRoot(a, b, c, t);
  55196. if (lowestRoot.found) {
  55197. t = lowestRoot.root;
  55198. found = true;
  55199. this._collisionPoint.copyFrom(p1);
  55200. }
  55201. this._basePoint.subtractToRef(p2, this._tempVector);
  55202. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55203. c = this._tempVector.lengthSquared() - 1.0;
  55204. lowestRoot = getLowestRoot(a, b, c, t);
  55205. if (lowestRoot.found) {
  55206. t = lowestRoot.root;
  55207. found = true;
  55208. this._collisionPoint.copyFrom(p2);
  55209. }
  55210. this._basePoint.subtractToRef(p3, this._tempVector);
  55211. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55212. c = this._tempVector.lengthSquared() - 1.0;
  55213. lowestRoot = getLowestRoot(a, b, c, t);
  55214. if (lowestRoot.found) {
  55215. t = lowestRoot.root;
  55216. found = true;
  55217. this._collisionPoint.copyFrom(p3);
  55218. }
  55219. p2.subtractToRef(p1, this._edge);
  55220. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55221. var edgeSquaredLength = this._edge.lengthSquared();
  55222. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55223. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55224. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55225. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55226. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55227. lowestRoot = getLowestRoot(a, b, c, t);
  55228. if (lowestRoot.found) {
  55229. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55230. if (f >= 0.0 && f <= 1.0) {
  55231. t = lowestRoot.root;
  55232. found = true;
  55233. this._edge.scaleInPlace(f);
  55234. p1.addToRef(this._edge, this._collisionPoint);
  55235. }
  55236. }
  55237. p3.subtractToRef(p2, this._edge);
  55238. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55239. edgeSquaredLength = this._edge.lengthSquared();
  55240. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55241. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55242. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55243. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55244. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55245. lowestRoot = getLowestRoot(a, b, c, t);
  55246. if (lowestRoot.found) {
  55247. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55248. if (f >= 0.0 && f <= 1.0) {
  55249. t = lowestRoot.root;
  55250. found = true;
  55251. this._edge.scaleInPlace(f);
  55252. p2.addToRef(this._edge, this._collisionPoint);
  55253. }
  55254. }
  55255. p1.subtractToRef(p3, this._edge);
  55256. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55257. edgeSquaredLength = this._edge.lengthSquared();
  55258. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55259. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55260. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55261. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55262. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55263. lowestRoot = getLowestRoot(a, b, c, t);
  55264. if (lowestRoot.found) {
  55265. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55266. if (f >= 0.0 && f <= 1.0) {
  55267. t = lowestRoot.root;
  55268. found = true;
  55269. this._edge.scaleInPlace(f);
  55270. p3.addToRef(this._edge, this._collisionPoint);
  55271. }
  55272. }
  55273. }
  55274. if (found) {
  55275. var distToCollision = t * this._velocity.length();
  55276. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55277. if (!this.intersectionPoint) {
  55278. this.intersectionPoint = this._collisionPoint.clone();
  55279. }
  55280. else {
  55281. this.intersectionPoint.copyFrom(this._collisionPoint);
  55282. }
  55283. this._nearestDistance = distToCollision;
  55284. this.collisionFound = true;
  55285. }
  55286. }
  55287. };
  55288. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55289. for (var i = indexStart; i < indexEnd; i += 3) {
  55290. var p1 = pts[indices[i] - decal];
  55291. var p2 = pts[indices[i + 1] - decal];
  55292. var p3 = pts[indices[i + 2] - decal];
  55293. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55294. }
  55295. };
  55296. Collider.prototype._getResponse = function (pos, vel) {
  55297. pos.addToRef(vel, this._destinationPoint);
  55298. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55299. this._basePoint.addToRef(vel, pos);
  55300. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55301. this._slidePlaneNormal.normalize();
  55302. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55303. pos.addInPlace(this._displacementVector);
  55304. this.intersectionPoint.addInPlace(this._displacementVector);
  55305. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55306. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55307. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55308. };
  55309. return Collider;
  55310. }());
  55311. BABYLON.Collider = Collider;
  55312. })(BABYLON || (BABYLON = {}));
  55313. //# sourceMappingURL=babylon.collider.js.map
  55314. var BABYLON;
  55315. (function (BABYLON) {
  55316. //WebWorker code will be inserted to this variable.
  55317. BABYLON.CollisionWorker = "";
  55318. /** Defines supported task for worker process */
  55319. var WorkerTaskType;
  55320. (function (WorkerTaskType) {
  55321. /** Initialization */
  55322. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55323. /** Update of geometry */
  55324. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55325. /** Evaluate collision */
  55326. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55327. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55328. /** Defines kind of replies returned by worker */
  55329. var WorkerReplyType;
  55330. (function (WorkerReplyType) {
  55331. /** Success */
  55332. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55333. /** Unkown error */
  55334. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55335. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55336. var CollisionCoordinatorWorker = /** @class */ (function () {
  55337. function CollisionCoordinatorWorker() {
  55338. var _this = this;
  55339. this._scaledPosition = BABYLON.Vector3.Zero();
  55340. this._scaledVelocity = BABYLON.Vector3.Zero();
  55341. this.onMeshUpdated = function (transformNode) {
  55342. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55343. };
  55344. this.onGeometryUpdated = function (geometry) {
  55345. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55346. };
  55347. this._afterRender = function () {
  55348. if (!_this._init)
  55349. return;
  55350. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55351. return;
  55352. }
  55353. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55354. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55355. if (_this._runningUpdated > 4) {
  55356. return;
  55357. }
  55358. ++_this._runningUpdated;
  55359. var payload = {
  55360. updatedMeshes: _this._addUpdateMeshesList,
  55361. updatedGeometries: _this._addUpdateGeometriesList,
  55362. removedGeometries: _this._toRemoveGeometryArray,
  55363. removedMeshes: _this._toRemoveMeshesArray
  55364. };
  55365. var message = {
  55366. payload: payload,
  55367. taskType: WorkerTaskType.UPDATE
  55368. };
  55369. var serializable = [];
  55370. for (var id in payload.updatedGeometries) {
  55371. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55372. //prepare transferables
  55373. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55374. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55375. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55376. }
  55377. }
  55378. _this._worker.postMessage(message, serializable);
  55379. _this._addUpdateMeshesList = {};
  55380. _this._addUpdateGeometriesList = {};
  55381. _this._toRemoveGeometryArray = [];
  55382. _this._toRemoveMeshesArray = [];
  55383. };
  55384. this._onMessageFromWorker = function (e) {
  55385. var returnData = e.data;
  55386. if (returnData.error != WorkerReplyType.SUCCESS) {
  55387. //TODO what errors can be returned from the worker?
  55388. BABYLON.Tools.Warn("error returned from worker!");
  55389. return;
  55390. }
  55391. switch (returnData.taskType) {
  55392. case WorkerTaskType.INIT:
  55393. _this._init = true;
  55394. //Update the worked with ALL of the scene's current state
  55395. _this._scene.meshes.forEach(function (mesh) {
  55396. _this.onMeshAdded(mesh);
  55397. });
  55398. _this._scene.getGeometries().forEach(function (geometry) {
  55399. _this.onGeometryAdded(geometry);
  55400. });
  55401. break;
  55402. case WorkerTaskType.UPDATE:
  55403. _this._runningUpdated--;
  55404. break;
  55405. case WorkerTaskType.COLLIDE:
  55406. var returnPayload = returnData.payload;
  55407. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55408. return;
  55409. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55410. if (callback) {
  55411. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55412. if (mesh) {
  55413. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55414. }
  55415. }
  55416. //cleanup
  55417. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55418. break;
  55419. }
  55420. };
  55421. this._collisionsCallbackArray = [];
  55422. this._init = false;
  55423. this._runningUpdated = 0;
  55424. this._addUpdateMeshesList = {};
  55425. this._addUpdateGeometriesList = {};
  55426. this._toRemoveGeometryArray = [];
  55427. this._toRemoveMeshesArray = [];
  55428. }
  55429. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55430. if (!this._init)
  55431. return;
  55432. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55433. return;
  55434. position.divideToRef(collider._radius, this._scaledPosition);
  55435. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55436. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55437. var payload = {
  55438. collider: {
  55439. position: this._scaledPosition.asArray(),
  55440. velocity: this._scaledVelocity.asArray(),
  55441. radius: collider._radius.asArray()
  55442. },
  55443. collisionId: collisionIndex,
  55444. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55445. maximumRetry: maximumRetry
  55446. };
  55447. var message = {
  55448. payload: payload,
  55449. taskType: WorkerTaskType.COLLIDE
  55450. };
  55451. this._worker.postMessage(message);
  55452. };
  55453. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55454. this._scene = scene;
  55455. this._scene.registerAfterRender(this._afterRender);
  55456. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55457. this._worker = new Worker(workerUrl);
  55458. this._worker.onmessage = this._onMessageFromWorker;
  55459. var message = {
  55460. payload: {},
  55461. taskType: WorkerTaskType.INIT
  55462. };
  55463. this._worker.postMessage(message);
  55464. };
  55465. CollisionCoordinatorWorker.prototype.destroy = function () {
  55466. this._scene.unregisterAfterRender(this._afterRender);
  55467. this._worker.terminate();
  55468. };
  55469. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55470. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55471. this.onMeshUpdated(mesh);
  55472. };
  55473. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55474. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55475. };
  55476. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55477. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55478. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55479. this.onGeometryUpdated(geometry);
  55480. };
  55481. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55482. this._toRemoveGeometryArray.push(geometry.id);
  55483. };
  55484. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55485. var submeshes = [];
  55486. if (mesh.subMeshes) {
  55487. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55488. var boundingInfo = sm.getBoundingInfo();
  55489. return {
  55490. position: idx,
  55491. verticesStart: sm.verticesStart,
  55492. verticesCount: sm.verticesCount,
  55493. indexStart: sm.indexStart,
  55494. indexCount: sm.indexCount,
  55495. hasMaterial: !!sm.getMaterial(),
  55496. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55497. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55498. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55499. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55500. };
  55501. });
  55502. }
  55503. var geometryId = null;
  55504. if (mesh instanceof BABYLON.Mesh) {
  55505. var geometry = mesh.geometry;
  55506. geometryId = geometry ? geometry.id : null;
  55507. }
  55508. else if (mesh instanceof BABYLON.InstancedMesh) {
  55509. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55510. geometryId = geometry ? geometry.id : null;
  55511. }
  55512. var boundingInfo = mesh.getBoundingInfo();
  55513. return {
  55514. uniqueId: mesh.uniqueId,
  55515. id: mesh.id,
  55516. name: mesh.name,
  55517. geometryId: geometryId,
  55518. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55519. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55520. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55521. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55522. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55523. subMeshes: submeshes,
  55524. checkCollisions: mesh.checkCollisions
  55525. };
  55526. };
  55527. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55528. return {
  55529. id: geometry.id,
  55530. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55531. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55532. indices: new Uint32Array(geometry.getIndices() || []),
  55533. };
  55534. };
  55535. return CollisionCoordinatorWorker;
  55536. }());
  55537. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55538. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55539. function CollisionCoordinatorLegacy() {
  55540. this._scaledPosition = BABYLON.Vector3.Zero();
  55541. this._scaledVelocity = BABYLON.Vector3.Zero();
  55542. this._finalPosition = BABYLON.Vector3.Zero();
  55543. }
  55544. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55545. position.divideToRef(collider._radius, this._scaledPosition);
  55546. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55547. collider.collidedMesh = null;
  55548. collider._retry = 0;
  55549. collider._initialVelocity = this._scaledVelocity;
  55550. collider._initialPosition = this._scaledPosition;
  55551. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55552. this._finalPosition.multiplyInPlace(collider._radius);
  55553. //run the callback
  55554. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55555. };
  55556. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55557. this._scene = scene;
  55558. };
  55559. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55560. //Legacy need no destruction method.
  55561. };
  55562. //No update in legacy mode
  55563. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55564. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55565. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55566. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55567. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55568. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55569. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55570. if (excludedMesh === void 0) { excludedMesh = null; }
  55571. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55572. if (collider._retry >= maximumRetry) {
  55573. finalPosition.copyFrom(position);
  55574. return;
  55575. }
  55576. // Check if this is a mesh else camera or -1
  55577. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55578. collider._initialize(position, velocity, closeDistance);
  55579. // Check all meshes
  55580. for (var index = 0; index < this._scene.meshes.length; index++) {
  55581. var mesh = this._scene.meshes[index];
  55582. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55583. mesh._checkCollision(collider);
  55584. }
  55585. }
  55586. if (!collider.collisionFound) {
  55587. position.addToRef(velocity, finalPosition);
  55588. return;
  55589. }
  55590. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55591. collider._getResponse(position, velocity);
  55592. }
  55593. if (velocity.length() <= closeDistance) {
  55594. finalPosition.copyFrom(position);
  55595. return;
  55596. }
  55597. collider._retry++;
  55598. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55599. };
  55600. return CollisionCoordinatorLegacy;
  55601. }());
  55602. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55603. })(BABYLON || (BABYLON = {}));
  55604. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55605. var BABYLON;
  55606. (function (BABYLON) {
  55607. /**
  55608. * A particle represents one of the element emitted by a particle system.
  55609. * This is mainly define by its coordinates, direction, velocity and age.
  55610. */
  55611. var Particle = /** @class */ (function () {
  55612. /**
  55613. * Creates a new instance Particle
  55614. * @param particleSystem the particle system the particle belongs to
  55615. */
  55616. function Particle(
  55617. /**
  55618. * particleSystem the particle system the particle belongs to.
  55619. */
  55620. particleSystem) {
  55621. this.particleSystem = particleSystem;
  55622. /**
  55623. * The world position of the particle in the scene.
  55624. */
  55625. this.position = BABYLON.Vector3.Zero();
  55626. /**
  55627. * The world direction of the particle in the scene.
  55628. */
  55629. this.direction = BABYLON.Vector3.Zero();
  55630. /**
  55631. * The color of the particle.
  55632. */
  55633. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55634. /**
  55635. * The color change of the particle per step.
  55636. */
  55637. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55638. /**
  55639. * Defines how long will the life of the particle be.
  55640. */
  55641. this.lifeTime = 1.0;
  55642. /**
  55643. * The current age of the particle.
  55644. */
  55645. this.age = 0;
  55646. /**
  55647. * The current size of the particle.
  55648. */
  55649. this.size = 0;
  55650. /**
  55651. * The current angle of the particle.
  55652. */
  55653. this.angle = 0;
  55654. /**
  55655. * Defines how fast is the angle changing.
  55656. */
  55657. this.angularSpeed = 0;
  55658. /**
  55659. * Defines the cell index used by the particle to be rendered from a sprite.
  55660. */
  55661. this.cellIndex = 0;
  55662. this._currentFrameCounter = 0;
  55663. if (!this.particleSystem.isAnimationSheetEnabled) {
  55664. return;
  55665. }
  55666. this.updateCellInfoFromSystem();
  55667. }
  55668. Particle.prototype.updateCellInfoFromSystem = function () {
  55669. this.cellIndex = this.particleSystem.startSpriteCellID;
  55670. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55671. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55672. }
  55673. else {
  55674. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55675. }
  55676. };
  55677. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55678. // (ageOffset / scaledUpdateSpeed) / available cells
  55679. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55680. this._currentFrameCounter += scaledUpdateSpeed;
  55681. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55682. this._currentFrameCounter = 0;
  55683. this.cellIndex++;
  55684. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55685. this.cellIndex = this.particleSystem.endSpriteCellID;
  55686. }
  55687. }
  55688. };
  55689. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55690. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55691. this.cellIndex++;
  55692. this._currentFrameCounter = 0;
  55693. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55694. if (this.particleSystem.spriteCellLoop) {
  55695. this.cellIndex = this.particleSystem.startSpriteCellID;
  55696. }
  55697. else {
  55698. this.cellIndex = this.particleSystem.endSpriteCellID;
  55699. }
  55700. }
  55701. }
  55702. else {
  55703. this._currentFrameCounter++;
  55704. }
  55705. };
  55706. /**
  55707. * Copy the properties of particle to another one.
  55708. * @param other the particle to copy the information to.
  55709. */
  55710. Particle.prototype.copyTo = function (other) {
  55711. other.position.copyFrom(this.position);
  55712. other.direction.copyFrom(this.direction);
  55713. other.color.copyFrom(this.color);
  55714. other.colorStep.copyFrom(this.colorStep);
  55715. other.lifeTime = this.lifeTime;
  55716. other.age = this.age;
  55717. other.size = this.size;
  55718. other.angle = this.angle;
  55719. other.angularSpeed = this.angularSpeed;
  55720. other.particleSystem = this.particleSystem;
  55721. other.cellIndex = this.cellIndex;
  55722. };
  55723. return Particle;
  55724. }());
  55725. BABYLON.Particle = Particle;
  55726. })(BABYLON || (BABYLON = {}));
  55727. //# sourceMappingURL=babylon.particle.js.map
  55728. var BABYLON;
  55729. (function (BABYLON) {
  55730. /**
  55731. * This represents a particle system in Babylon.
  55732. * 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.
  55733. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55734. * @example https://doc.babylonjs.com/babylon101/particles
  55735. */
  55736. var ParticleSystem = /** @class */ (function () {
  55737. /**
  55738. * Instantiates a particle system.
  55739. * 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.
  55740. * @param name The name of the particle system
  55741. * @param capacity The max number of particles alive at the same time
  55742. * @param scene The scene the particle system belongs to
  55743. * @param customEffect a custom effect used to change the way particles are rendered by default
  55744. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55745. * @param epsilon Offset used to render the particles
  55746. */
  55747. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55748. if (customEffect === void 0) { customEffect = null; }
  55749. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55750. if (epsilon === void 0) { epsilon = 0.01; }
  55751. var _this = this;
  55752. /**
  55753. * List of animations used by the particle system.
  55754. */
  55755. this.animations = [];
  55756. /**
  55757. * The rendering group used by the Particle system to chose when to render.
  55758. */
  55759. this.renderingGroupId = 0;
  55760. /**
  55761. * The emitter represents the Mesh or position we are attaching the particle system to.
  55762. */
  55763. this.emitter = null;
  55764. /**
  55765. * The maximum number of particles to emit per frame
  55766. */
  55767. this.emitRate = 10;
  55768. /**
  55769. * If you want to launch only a few particles at once, that can be done, as well.
  55770. */
  55771. this.manualEmitCount = -1;
  55772. /**
  55773. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55774. */
  55775. this.updateSpeed = 0.01;
  55776. /**
  55777. * The amount of time the particle system is running (depends of the overall update speed).
  55778. */
  55779. this.targetStopDuration = 0;
  55780. /**
  55781. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55782. */
  55783. this.disposeOnStop = false;
  55784. /**
  55785. * Minimum power of emitting particles.
  55786. */
  55787. this.minEmitPower = 1;
  55788. /**
  55789. * Maximum power of emitting particles.
  55790. */
  55791. this.maxEmitPower = 1;
  55792. /**
  55793. * Minimum life time of emitting particles.
  55794. */
  55795. this.minLifeTime = 1;
  55796. /**
  55797. * Maximum life time of emitting particles.
  55798. */
  55799. this.maxLifeTime = 1;
  55800. /**
  55801. * Minimum Size of emitting particles.
  55802. */
  55803. this.minSize = 1;
  55804. /**
  55805. * Maximum Size of emitting particles.
  55806. */
  55807. this.maxSize = 1;
  55808. /**
  55809. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55810. */
  55811. this.minAngularSpeed = 0;
  55812. /**
  55813. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55814. */
  55815. this.maxAngularSpeed = 0;
  55816. /**
  55817. * The layer mask we are rendering the particles through.
  55818. */
  55819. this.layerMask = 0x0FFFFFFF;
  55820. /**
  55821. * This can help using your own shader to render the particle system.
  55822. * The according effect will be created
  55823. */
  55824. this.customShader = null;
  55825. /**
  55826. * By default particle system starts as soon as they are created. This prevents the
  55827. * automatic start to happen and let you decide when to start emitting particles.
  55828. */
  55829. this.preventAutoStart = false;
  55830. /**
  55831. * Callback triggered when the particle animation is ending.
  55832. */
  55833. this.onAnimationEnd = null;
  55834. /**
  55835. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55836. */
  55837. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55838. /**
  55839. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55840. * to override the particles.
  55841. */
  55842. this.forceDepthWrite = false;
  55843. /**
  55844. * You can use gravity if you want to give an orientation to your particles.
  55845. */
  55846. this.gravity = BABYLON.Vector3.Zero();
  55847. /**
  55848. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55849. */
  55850. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55851. /**
  55852. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55853. */
  55854. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55855. /**
  55856. * Color the particle will have at the end of its lifetime.
  55857. */
  55858. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55859. /**
  55860. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55861. */
  55862. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55863. /**
  55864. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55865. */
  55866. this.spriteCellLoop = true;
  55867. /**
  55868. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55869. */
  55870. this.spriteCellChangeSpeed = 0;
  55871. /**
  55872. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55873. */
  55874. this.startSpriteCellID = 0;
  55875. /**
  55876. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55877. */
  55878. this.endSpriteCellID = 0;
  55879. /**
  55880. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55881. */
  55882. this.spriteCellWidth = 0;
  55883. /**
  55884. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55885. */
  55886. this.spriteCellHeight = 0;
  55887. /**
  55888. * An event triggered when the system is disposed.
  55889. */
  55890. this.onDisposeObservable = new BABYLON.Observable();
  55891. this._particles = new Array();
  55892. this._stockParticles = new Array();
  55893. this._newPartsExcess = 0;
  55894. this._vertexBuffers = {};
  55895. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55896. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55897. this._scaledDirection = BABYLON.Vector3.Zero();
  55898. this._scaledGravity = BABYLON.Vector3.Zero();
  55899. this._currentRenderId = -1;
  55900. this._started = false;
  55901. this._stopped = false;
  55902. this._actualFrame = 0;
  55903. this._vertexBufferSize = 11;
  55904. // start of sub system methods
  55905. /**
  55906. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55907. * Its lifetime will start back at 0.
  55908. */
  55909. this.recycleParticle = function (particle) {
  55910. var lastParticle = _this._particles.pop();
  55911. if (lastParticle !== particle) {
  55912. lastParticle.copyTo(particle);
  55913. }
  55914. _this._stockParticles.push(lastParticle);
  55915. };
  55916. this._createParticle = function () {
  55917. var particle;
  55918. if (_this._stockParticles.length !== 0) {
  55919. particle = _this._stockParticles.pop();
  55920. particle.age = 0;
  55921. particle.cellIndex = _this.startSpriteCellID;
  55922. }
  55923. else {
  55924. particle = new BABYLON.Particle(_this);
  55925. }
  55926. return particle;
  55927. };
  55928. this._emitFromParticle = function (particle) {
  55929. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55930. return;
  55931. }
  55932. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55933. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55934. subSystem._rootParticleSystem = _this;
  55935. _this.activeSubSystems.push(subSystem);
  55936. subSystem.start();
  55937. };
  55938. this._appendParticleVertexes = null;
  55939. this.id = name;
  55940. this.name = name;
  55941. this._capacity = capacity;
  55942. this._epsilon = epsilon;
  55943. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55944. if (isAnimationSheetEnabled) {
  55945. this._vertexBufferSize = 12;
  55946. }
  55947. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55948. this._customEffect = customEffect;
  55949. scene.particleSystems.push(this);
  55950. this._createIndexBuffer();
  55951. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55952. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55953. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55954. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55955. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55956. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55957. if (this._isAnimationSheetEnabled) {
  55958. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55959. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55960. }
  55961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55962. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55963. this._vertexBuffers["options"] = options;
  55964. // Default emitter type
  55965. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55966. this.updateFunction = function (particles) {
  55967. for (var index = 0; index < particles.length; index++) {
  55968. var particle = particles[index];
  55969. particle.age += _this._scaledUpdateSpeed;
  55970. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55971. _this._emitFromParticle(particle);
  55972. _this.recycleParticle(particle);
  55973. index--;
  55974. continue;
  55975. }
  55976. else {
  55977. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55978. particle.color.addInPlace(_this._scaledColorStep);
  55979. if (particle.color.a < 0)
  55980. particle.color.a = 0;
  55981. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55982. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55983. particle.position.addInPlace(_this._scaledDirection);
  55984. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55985. particle.direction.addInPlace(_this._scaledGravity);
  55986. if (_this._isAnimationSheetEnabled) {
  55987. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55988. }
  55989. }
  55990. }
  55991. };
  55992. }
  55993. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55994. /**
  55995. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55996. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55997. */
  55998. get: function () {
  55999. if (this.particleEmitterType.direction1) {
  56000. return this.particleEmitterType.direction1;
  56001. }
  56002. return BABYLON.Vector3.Zero();
  56003. },
  56004. set: function (value) {
  56005. if (this.particleEmitterType.direction1) {
  56006. this.particleEmitterType.direction1 = value;
  56007. }
  56008. },
  56009. enumerable: true,
  56010. configurable: true
  56011. });
  56012. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56013. /**
  56014. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56015. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56016. */
  56017. get: function () {
  56018. if (this.particleEmitterType.direction2) {
  56019. return this.particleEmitterType.direction2;
  56020. }
  56021. return BABYLON.Vector3.Zero();
  56022. },
  56023. set: function (value) {
  56024. if (this.particleEmitterType.direction2) {
  56025. this.particleEmitterType.direction2 = value;
  56026. }
  56027. },
  56028. enumerable: true,
  56029. configurable: true
  56030. });
  56031. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56032. /**
  56033. * 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.
  56034. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56035. */
  56036. get: function () {
  56037. if (this.particleEmitterType.minEmitBox) {
  56038. return this.particleEmitterType.minEmitBox;
  56039. }
  56040. return BABYLON.Vector3.Zero();
  56041. },
  56042. set: function (value) {
  56043. if (this.particleEmitterType.minEmitBox) {
  56044. this.particleEmitterType.minEmitBox = value;
  56045. }
  56046. },
  56047. enumerable: true,
  56048. configurable: true
  56049. });
  56050. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56051. /**
  56052. * 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.
  56053. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56054. */
  56055. get: function () {
  56056. if (this.particleEmitterType.maxEmitBox) {
  56057. return this.particleEmitterType.maxEmitBox;
  56058. }
  56059. return BABYLON.Vector3.Zero();
  56060. },
  56061. set: function (value) {
  56062. if (this.particleEmitterType.maxEmitBox) {
  56063. this.particleEmitterType.maxEmitBox = value;
  56064. }
  56065. },
  56066. enumerable: true,
  56067. configurable: true
  56068. });
  56069. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56070. /**
  56071. * Sets a callback that will be triggered when the system is disposed.
  56072. */
  56073. set: function (callback) {
  56074. if (this._onDisposeObserver) {
  56075. this.onDisposeObservable.remove(this._onDisposeObserver);
  56076. }
  56077. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56078. },
  56079. enumerable: true,
  56080. configurable: true
  56081. });
  56082. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56083. /**
  56084. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56085. */
  56086. get: function () {
  56087. return this._isAnimationSheetEnabled;
  56088. },
  56089. enumerable: true,
  56090. configurable: true
  56091. });
  56092. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56093. //end of Sub-emitter
  56094. /**
  56095. * Gets the current list of active particles
  56096. */
  56097. get: function () {
  56098. return this._particles;
  56099. },
  56100. enumerable: true,
  56101. configurable: true
  56102. });
  56103. /**
  56104. * Returns the string "ParticleSystem"
  56105. * @returns a string containing the class name
  56106. */
  56107. ParticleSystem.prototype.getClassName = function () {
  56108. return "ParticleSystem";
  56109. };
  56110. ParticleSystem.prototype._createIndexBuffer = function () {
  56111. var indices = [];
  56112. var index = 0;
  56113. for (var count = 0; count < this._capacity; count++) {
  56114. indices.push(index);
  56115. indices.push(index + 1);
  56116. indices.push(index + 2);
  56117. indices.push(index);
  56118. indices.push(index + 2);
  56119. indices.push(index + 3);
  56120. index += 4;
  56121. }
  56122. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56123. };
  56124. /**
  56125. * Gets the maximum number of particles active at the same time.
  56126. * @returns The max number of active particles.
  56127. */
  56128. ParticleSystem.prototype.getCapacity = function () {
  56129. return this._capacity;
  56130. };
  56131. /**
  56132. * Gets Wether there are still active particles in the system.
  56133. * @returns True if it is alive, otherwise false.
  56134. */
  56135. ParticleSystem.prototype.isAlive = function () {
  56136. return this._alive;
  56137. };
  56138. /**
  56139. * Gets Wether the system has been started.
  56140. * @returns True if it has been started, otherwise false.
  56141. */
  56142. ParticleSystem.prototype.isStarted = function () {
  56143. return this._started;
  56144. };
  56145. /**
  56146. * Starts the particle system and begins to emit.
  56147. */
  56148. ParticleSystem.prototype.start = function () {
  56149. this._started = true;
  56150. this._stopped = false;
  56151. this._actualFrame = 0;
  56152. if (this.subEmitters && this.subEmitters.length != 0) {
  56153. this.activeSubSystems = new Array();
  56154. }
  56155. };
  56156. /**
  56157. * Stops the particle system.
  56158. * @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.
  56159. */
  56160. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56161. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56162. this._stopped = true;
  56163. if (stopSubEmitters) {
  56164. this._stopSubEmitters();
  56165. }
  56166. };
  56167. // animation sheet
  56168. /**
  56169. * Remove all active particles
  56170. */
  56171. ParticleSystem.prototype.reset = function () {
  56172. this._stockParticles = [];
  56173. this._particles = [];
  56174. };
  56175. /**
  56176. * @hidden (for internal use only)
  56177. */
  56178. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56179. var offset = index * this._vertexBufferSize;
  56180. this._vertexData[offset] = particle.position.x;
  56181. this._vertexData[offset + 1] = particle.position.y;
  56182. this._vertexData[offset + 2] = particle.position.z;
  56183. this._vertexData[offset + 3] = particle.color.r;
  56184. this._vertexData[offset + 4] = particle.color.g;
  56185. this._vertexData[offset + 5] = particle.color.b;
  56186. this._vertexData[offset + 6] = particle.color.a;
  56187. this._vertexData[offset + 7] = particle.angle;
  56188. this._vertexData[offset + 8] = particle.size;
  56189. this._vertexData[offset + 9] = offsetX;
  56190. this._vertexData[offset + 10] = offsetY;
  56191. };
  56192. /**
  56193. * @hidden (for internal use only)
  56194. */
  56195. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56196. if (offsetX === 0)
  56197. offsetX = this._epsilon;
  56198. else if (offsetX === 1)
  56199. offsetX = 1 - this._epsilon;
  56200. if (offsetY === 0)
  56201. offsetY = this._epsilon;
  56202. else if (offsetY === 1)
  56203. offsetY = 1 - this._epsilon;
  56204. var offset = index * this._vertexBufferSize;
  56205. this._vertexData[offset] = particle.position.x;
  56206. this._vertexData[offset + 1] = particle.position.y;
  56207. this._vertexData[offset + 2] = particle.position.z;
  56208. this._vertexData[offset + 3] = particle.color.r;
  56209. this._vertexData[offset + 4] = particle.color.g;
  56210. this._vertexData[offset + 5] = particle.color.b;
  56211. this._vertexData[offset + 6] = particle.color.a;
  56212. this._vertexData[offset + 7] = particle.angle;
  56213. this._vertexData[offset + 8] = particle.size;
  56214. this._vertexData[offset + 9] = offsetX;
  56215. this._vertexData[offset + 10] = offsetY;
  56216. this._vertexData[offset + 11] = particle.cellIndex;
  56217. };
  56218. ParticleSystem.prototype._stopSubEmitters = function () {
  56219. if (!this.activeSubSystems) {
  56220. return;
  56221. }
  56222. this.activeSubSystems.forEach(function (subSystem) {
  56223. subSystem.stop(true);
  56224. });
  56225. this.activeSubSystems = new Array();
  56226. };
  56227. ParticleSystem.prototype._removeFromRoot = function () {
  56228. if (!this._rootParticleSystem) {
  56229. return;
  56230. }
  56231. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56232. if (index !== -1) {
  56233. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56234. }
  56235. };
  56236. // end of sub system methods
  56237. ParticleSystem.prototype._update = function (newParticles) {
  56238. // Update current
  56239. this._alive = this._particles.length > 0;
  56240. this.updateFunction(this._particles);
  56241. // Add new ones
  56242. var worldMatrix;
  56243. if (this.emitter.position) {
  56244. var emitterMesh = this.emitter;
  56245. worldMatrix = emitterMesh.getWorldMatrix();
  56246. }
  56247. else {
  56248. var emitterPosition = this.emitter;
  56249. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56250. }
  56251. var particle;
  56252. for (var index = 0; index < newParticles; index++) {
  56253. if (this._particles.length === this._capacity) {
  56254. break;
  56255. }
  56256. particle = this._createParticle();
  56257. this._particles.push(particle);
  56258. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56259. if (this.startPositionFunction) {
  56260. this.startPositionFunction(worldMatrix, particle.position, particle);
  56261. }
  56262. else {
  56263. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56264. }
  56265. if (this.startDirectionFunction) {
  56266. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56267. }
  56268. else {
  56269. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56270. }
  56271. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56272. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56273. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56274. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56275. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56276. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56277. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56278. }
  56279. };
  56280. ParticleSystem.prototype._getEffect = function () {
  56281. if (this._customEffect) {
  56282. return this._customEffect;
  56283. }
  56284. ;
  56285. var defines = [];
  56286. if (this._scene.clipPlane) {
  56287. defines.push("#define CLIPPLANE");
  56288. }
  56289. if (this._isAnimationSheetEnabled) {
  56290. defines.push("#define ANIMATESHEET");
  56291. }
  56292. // Effect
  56293. var join = defines.join("\n");
  56294. if (this._cachedDefines !== join) {
  56295. this._cachedDefines = join;
  56296. var attributesNamesOrOptions;
  56297. var effectCreationOption;
  56298. if (this._isAnimationSheetEnabled) {
  56299. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56300. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56301. }
  56302. else {
  56303. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56304. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56305. }
  56306. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56307. }
  56308. return this._effect;
  56309. };
  56310. /**
  56311. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56312. */
  56313. ParticleSystem.prototype.animate = function () {
  56314. if (!this._started)
  56315. return;
  56316. var effect = this._getEffect();
  56317. // Check
  56318. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56319. return;
  56320. if (this._currentRenderId === this._scene.getRenderId()) {
  56321. return;
  56322. }
  56323. this._currentRenderId = this._scene.getRenderId();
  56324. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56325. // determine the number of particles we need to create
  56326. var newParticles;
  56327. if (this.manualEmitCount > -1) {
  56328. newParticles = this.manualEmitCount;
  56329. this._newPartsExcess = 0;
  56330. this.manualEmitCount = 0;
  56331. }
  56332. else {
  56333. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56334. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56335. }
  56336. if (this._newPartsExcess > 1.0) {
  56337. newParticles += this._newPartsExcess >> 0;
  56338. this._newPartsExcess -= this._newPartsExcess >> 0;
  56339. }
  56340. this._alive = false;
  56341. if (!this._stopped) {
  56342. this._actualFrame += this._scaledUpdateSpeed;
  56343. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56344. this.stop();
  56345. }
  56346. else {
  56347. newParticles = 0;
  56348. }
  56349. this._update(newParticles);
  56350. // Stopped?
  56351. if (this._stopped) {
  56352. if (!this._alive) {
  56353. this._started = false;
  56354. if (this.onAnimationEnd) {
  56355. this.onAnimationEnd();
  56356. }
  56357. if (this.disposeOnStop) {
  56358. this._scene._toBeDisposed.push(this);
  56359. }
  56360. }
  56361. }
  56362. // Animation sheet
  56363. if (this._isAnimationSheetEnabled) {
  56364. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56365. }
  56366. else {
  56367. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56368. }
  56369. // Update VBO
  56370. var offset = 0;
  56371. for (var index = 0; index < this._particles.length; index++) {
  56372. var particle = this._particles[index];
  56373. this._appendParticleVertexes(offset, particle);
  56374. offset += 4;
  56375. }
  56376. if (this._vertexBuffer) {
  56377. this._vertexBuffer.update(this._vertexData);
  56378. }
  56379. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56380. this.stop();
  56381. }
  56382. };
  56383. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56384. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56385. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56386. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56387. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56388. };
  56389. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56390. this._appendParticleVertex(offset++, particle, 0, 0);
  56391. this._appendParticleVertex(offset++, particle, 1, 0);
  56392. this._appendParticleVertex(offset++, particle, 1, 1);
  56393. this._appendParticleVertex(offset++, particle, 0, 1);
  56394. };
  56395. /**
  56396. * Rebuilds the particle system.
  56397. */
  56398. ParticleSystem.prototype.rebuild = function () {
  56399. this._createIndexBuffer();
  56400. if (this._vertexBuffer) {
  56401. this._vertexBuffer._rebuild();
  56402. }
  56403. };
  56404. /**
  56405. * Is this system ready to be used/rendered
  56406. * @return true if the system is ready
  56407. */
  56408. ParticleSystem.prototype.isReady = function () {
  56409. var effect = this._getEffect();
  56410. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56411. return false;
  56412. }
  56413. return true;
  56414. };
  56415. /**
  56416. * Renders the particle system in its current state.
  56417. * @returns the current number of particles
  56418. */
  56419. ParticleSystem.prototype.render = function () {
  56420. var effect = this._getEffect();
  56421. // Check
  56422. if (!this.isReady() || !this._particles.length) {
  56423. return 0;
  56424. }
  56425. var engine = this._scene.getEngine();
  56426. // Render
  56427. engine.enableEffect(effect);
  56428. engine.setState(false);
  56429. var viewMatrix = this._scene.getViewMatrix();
  56430. effect.setTexture("diffuseSampler", this.particleTexture);
  56431. effect.setMatrix("view", viewMatrix);
  56432. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56433. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56434. var baseSize = this.particleTexture.getBaseSize();
  56435. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56436. }
  56437. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56438. if (this._scene.clipPlane) {
  56439. var clipPlane = this._scene.clipPlane;
  56440. var invView = viewMatrix.clone();
  56441. invView.invert();
  56442. effect.setMatrix("invView", invView);
  56443. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56444. }
  56445. // VBOs
  56446. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56447. // Draw order
  56448. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56449. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56450. }
  56451. else {
  56452. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56453. }
  56454. if (this.forceDepthWrite) {
  56455. engine.setDepthWrite(true);
  56456. }
  56457. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56458. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56459. return this._particles.length;
  56460. };
  56461. /**
  56462. * Disposes the particle system and free the associated resources
  56463. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56464. */
  56465. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56466. if (disposeTexture === void 0) { disposeTexture = true; }
  56467. if (this._vertexBuffer) {
  56468. this._vertexBuffer.dispose();
  56469. this._vertexBuffer = null;
  56470. }
  56471. if (this._indexBuffer) {
  56472. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56473. this._indexBuffer = null;
  56474. }
  56475. if (disposeTexture && this.particleTexture) {
  56476. this.particleTexture.dispose();
  56477. this.particleTexture = null;
  56478. }
  56479. this._removeFromRoot();
  56480. // Remove from scene
  56481. var index = this._scene.particleSystems.indexOf(this);
  56482. if (index > -1) {
  56483. this._scene.particleSystems.splice(index, 1);
  56484. }
  56485. // Callback
  56486. this.onDisposeObservable.notifyObservers(this);
  56487. this.onDisposeObservable.clear();
  56488. };
  56489. /**
  56490. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56491. * @param radius The radius of the sphere to emit from
  56492. * @returns the emitter
  56493. */
  56494. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56495. if (radius === void 0) { radius = 1; }
  56496. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56497. this.particleEmitterType = particleEmitter;
  56498. return particleEmitter;
  56499. };
  56500. /**
  56501. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56502. * @param radius The radius of the sphere to emit from
  56503. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56504. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56505. * @returns the emitter
  56506. */
  56507. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56508. if (radius === void 0) { radius = 1; }
  56509. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56510. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56511. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56512. this.particleEmitterType = particleEmitter;
  56513. return particleEmitter;
  56514. };
  56515. /**
  56516. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56517. * @param radius The radius of the cone to emit from
  56518. * @param angle The base angle of the cone
  56519. * @returns the emitter
  56520. */
  56521. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56522. if (radius === void 0) { radius = 1; }
  56523. if (angle === void 0) { angle = Math.PI / 4; }
  56524. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56525. this.particleEmitterType = particleEmitter;
  56526. return particleEmitter;
  56527. };
  56528. // 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.
  56529. /**
  56530. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56531. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56532. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56533. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56534. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56535. * @returns the emitter
  56536. */
  56537. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56538. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56539. this.particleEmitterType = particleEmitter;
  56540. this.direction1 = direction1;
  56541. this.direction2 = direction2;
  56542. this.minEmitBox = minEmitBox;
  56543. this.maxEmitBox = maxEmitBox;
  56544. return particleEmitter;
  56545. };
  56546. // Clone
  56547. /**
  56548. * Clones the particle system.
  56549. * @param name The name of the cloned object
  56550. * @param newEmitter The new emitter to use
  56551. * @returns the cloned particle system
  56552. */
  56553. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56554. var custom = null;
  56555. var program = null;
  56556. if (this.customShader != null) {
  56557. program = this.customShader;
  56558. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56559. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56560. }
  56561. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56562. result.customShader = program;
  56563. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56564. if (newEmitter === undefined) {
  56565. newEmitter = this.emitter;
  56566. }
  56567. result.emitter = newEmitter;
  56568. if (this.particleTexture) {
  56569. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56570. }
  56571. if (!this.preventAutoStart) {
  56572. result.start();
  56573. }
  56574. return result;
  56575. };
  56576. /**
  56577. * Serializes the particle system to a JSON object.
  56578. * @returns the JSON object
  56579. */
  56580. ParticleSystem.prototype.serialize = function () {
  56581. var serializationObject = {};
  56582. serializationObject.name = this.name;
  56583. serializationObject.id = this.id;
  56584. // Emitter
  56585. if (this.emitter.position) {
  56586. var emitterMesh = this.emitter;
  56587. serializationObject.emitterId = emitterMesh.id;
  56588. }
  56589. else {
  56590. var emitterPosition = this.emitter;
  56591. serializationObject.emitter = emitterPosition.asArray();
  56592. }
  56593. serializationObject.capacity = this.getCapacity();
  56594. if (this.particleTexture) {
  56595. serializationObject.textureName = this.particleTexture.name;
  56596. }
  56597. // Animations
  56598. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56599. // Particle system
  56600. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56601. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56602. serializationObject.minSize = this.minSize;
  56603. serializationObject.maxSize = this.maxSize;
  56604. serializationObject.minEmitPower = this.minEmitPower;
  56605. serializationObject.maxEmitPower = this.maxEmitPower;
  56606. serializationObject.minLifeTime = this.minLifeTime;
  56607. serializationObject.maxLifeTime = this.maxLifeTime;
  56608. serializationObject.emitRate = this.emitRate;
  56609. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56610. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56611. serializationObject.gravity = this.gravity.asArray();
  56612. serializationObject.direction1 = this.direction1.asArray();
  56613. serializationObject.direction2 = this.direction2.asArray();
  56614. serializationObject.color1 = this.color1.asArray();
  56615. serializationObject.color2 = this.color2.asArray();
  56616. serializationObject.colorDead = this.colorDead.asArray();
  56617. serializationObject.updateSpeed = this.updateSpeed;
  56618. serializationObject.targetStopDuration = this.targetStopDuration;
  56619. serializationObject.textureMask = this.textureMask.asArray();
  56620. serializationObject.blendMode = this.blendMode;
  56621. serializationObject.customShader = this.customShader;
  56622. serializationObject.preventAutoStart = this.preventAutoStart;
  56623. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56624. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56625. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56626. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56627. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56628. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56629. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56630. // Emitter
  56631. if (this.particleEmitterType) {
  56632. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56633. }
  56634. return serializationObject;
  56635. };
  56636. /**
  56637. * Parses a JSON object to create a particle system.
  56638. * @param parsedParticleSystem The JSON object to parse
  56639. * @param scene The scene to create the particle system in
  56640. * @param rootUrl The root url to use to load external dependencies like texture
  56641. * @returns the Parsed particle system
  56642. */
  56643. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56644. var name = parsedParticleSystem.name;
  56645. var custom = null;
  56646. var program = null;
  56647. if (parsedParticleSystem.customShader) {
  56648. program = parsedParticleSystem.customShader;
  56649. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56650. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56651. }
  56652. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56653. particleSystem.customShader = program;
  56654. if (parsedParticleSystem.id) {
  56655. particleSystem.id = parsedParticleSystem.id;
  56656. }
  56657. // Auto start
  56658. if (parsedParticleSystem.preventAutoStart) {
  56659. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56660. }
  56661. // Texture
  56662. if (parsedParticleSystem.textureName) {
  56663. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56664. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56665. }
  56666. // Emitter
  56667. if (parsedParticleSystem.emitterId) {
  56668. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56669. }
  56670. else {
  56671. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56672. }
  56673. // Animations
  56674. if (parsedParticleSystem.animations) {
  56675. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56676. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56677. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56678. }
  56679. }
  56680. if (parsedParticleSystem.autoAnimate) {
  56681. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56682. }
  56683. // Particle system
  56684. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56685. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56686. particleSystem.minSize = parsedParticleSystem.minSize;
  56687. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56688. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56689. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56690. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56691. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56692. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56693. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56694. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56695. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56696. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56697. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56698. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56699. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56700. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56701. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56702. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56703. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56704. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56705. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56706. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56707. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56708. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56709. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56710. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56711. if (!particleSystem.preventAutoStart) {
  56712. particleSystem.start();
  56713. }
  56714. return particleSystem;
  56715. };
  56716. /**
  56717. * Source color is added to the destination color without alpha affecting the result.
  56718. */
  56719. ParticleSystem.BLENDMODE_ONEONE = 0;
  56720. /**
  56721. * Blend current color and particle color using particle’s alpha.
  56722. */
  56723. ParticleSystem.BLENDMODE_STANDARD = 1;
  56724. return ParticleSystem;
  56725. }());
  56726. BABYLON.ParticleSystem = ParticleSystem;
  56727. })(BABYLON || (BABYLON = {}));
  56728. //# sourceMappingURL=babylon.particleSystem.js.map
  56729. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56730. var BABYLON;
  56731. (function (BABYLON) {
  56732. /**
  56733. * Particle emitter emitting particles from the inside of a box.
  56734. * It emits the particles randomly between 2 given directions.
  56735. */
  56736. var BoxParticleEmitter = /** @class */ (function () {
  56737. /**
  56738. * Creates a new instance BoxParticleEmitter
  56739. */
  56740. function BoxParticleEmitter() {
  56741. /**
  56742. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56743. */
  56744. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56745. /**
  56746. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56747. */
  56748. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56749. /**
  56750. * 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.
  56751. */
  56752. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56753. /**
  56754. * 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.
  56755. */
  56756. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56757. }
  56758. /**
  56759. * Called by the particle System when the direction is computed for the created particle.
  56760. * @param emitPower is the power of the particle (speed)
  56761. * @param worldMatrix is the world matrix of the particle system
  56762. * @param directionToUpdate is the direction vector to update with the result
  56763. * @param particle is the particle we are computed the direction for
  56764. */
  56765. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56766. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56767. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56768. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56769. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56770. };
  56771. /**
  56772. * Called by the particle System when the position is computed for the created particle.
  56773. * @param worldMatrix is the world matrix of the particle system
  56774. * @param positionToUpdate is the position vector to update with the result
  56775. * @param particle is the particle we are computed the position for
  56776. */
  56777. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56778. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56779. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56780. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56782. };
  56783. /**
  56784. * Clones the current emitter and returns a copy of it
  56785. * @returns the new emitter
  56786. */
  56787. BoxParticleEmitter.prototype.clone = function () {
  56788. var newOne = new BoxParticleEmitter();
  56789. BABYLON.Tools.DeepCopy(this, newOne);
  56790. return newOne;
  56791. };
  56792. /**
  56793. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56794. * @param effect defines the update shader
  56795. */
  56796. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56797. effect.setVector3("direction1", this.direction1);
  56798. effect.setVector3("direction2", this.direction2);
  56799. effect.setVector3("minEmitBox", this.minEmitBox);
  56800. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56801. };
  56802. /**
  56803. * Returns a string to use to update the GPU particles update shader
  56804. * @returns a string containng the defines string
  56805. */
  56806. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56807. return "#define BOXEMITTER";
  56808. };
  56809. /**
  56810. * Returns the string "BoxEmitter"
  56811. * @returns a string containing the class name
  56812. */
  56813. BoxParticleEmitter.prototype.getClassName = function () {
  56814. return "BoxEmitter";
  56815. };
  56816. /**
  56817. * Serializes the particle system to a JSON object.
  56818. * @returns the JSON object
  56819. */
  56820. BoxParticleEmitter.prototype.serialize = function () {
  56821. var serializationObject = {};
  56822. serializationObject.type = this.getClassName();
  56823. serializationObject.direction1 = this.direction1.asArray();
  56824. serializationObject.direction2 = this.direction2.asArray();
  56825. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56826. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56827. return serializationObject;
  56828. };
  56829. /**
  56830. * Parse properties from a JSON object
  56831. * @param serializationObject defines the JSON object
  56832. */
  56833. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56834. this.direction1.copyFrom(serializationObject.direction1);
  56835. this.direction2.copyFrom(serializationObject.direction2);
  56836. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56837. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56838. };
  56839. return BoxParticleEmitter;
  56840. }());
  56841. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56842. })(BABYLON || (BABYLON = {}));
  56843. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56844. var BABYLON;
  56845. (function (BABYLON) {
  56846. /**
  56847. * Particle emitter emitting particles from the inside of a cone.
  56848. * It emits the particles alongside the cone volume from the base to the particle.
  56849. * The emission direction might be randomized.
  56850. */
  56851. var ConeParticleEmitter = /** @class */ (function () {
  56852. /**
  56853. * Creates a new instance ConeParticleEmitter
  56854. * @param radius the radius of the emission cone (1 by default)
  56855. * @param angles the cone base angle (PI by default)
  56856. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56857. */
  56858. function ConeParticleEmitter(radius,
  56859. /**
  56860. * The radius of the emission cone.
  56861. */
  56862. angle,
  56863. /**
  56864. * The cone base angle.
  56865. */
  56866. directionRandomizer) {
  56867. if (radius === void 0) { radius = 1; }
  56868. if (angle === void 0) { angle = Math.PI; }
  56869. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56870. this.angle = angle;
  56871. this.directionRandomizer = directionRandomizer;
  56872. this.radius = radius;
  56873. }
  56874. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56875. /**
  56876. * Gets the radius of the emission cone.
  56877. */
  56878. get: function () {
  56879. return this._radius;
  56880. },
  56881. /**
  56882. * Sets the radius of the emission cone.
  56883. */
  56884. set: function (value) {
  56885. this._radius = value;
  56886. if (this.angle !== 0) {
  56887. this._height = value / Math.tan(this.angle / 2);
  56888. }
  56889. else {
  56890. this._height = 1;
  56891. }
  56892. },
  56893. enumerable: true,
  56894. configurable: true
  56895. });
  56896. /**
  56897. * Called by the particle System when the direction is computed for the created particle.
  56898. * @param emitPower is the power of the particle (speed)
  56899. * @param worldMatrix is the world matrix of the particle system
  56900. * @param directionToUpdate is the direction vector to update with the result
  56901. * @param particle is the particle we are computed the direction for
  56902. */
  56903. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56904. if (this.angle === 0) {
  56905. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56906. }
  56907. else {
  56908. // measure the direction Vector from the emitter to the particle.
  56909. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56910. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56911. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56912. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56913. direction.x += randX;
  56914. direction.y += randY;
  56915. direction.z += randZ;
  56916. direction.normalize();
  56917. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56918. }
  56919. };
  56920. /**
  56921. * Called by the particle System when the position is computed for the created particle.
  56922. * @param worldMatrix is the world matrix of the particle system
  56923. * @param positionToUpdate is the position vector to update with the result
  56924. * @param particle is the particle we are computed the position for
  56925. */
  56926. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56927. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56928. var h = BABYLON.Scalar.RandomRange(0, 1);
  56929. // Better distribution in a cone at normal angles.
  56930. h = 1 - h * h;
  56931. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56932. radius = radius * h;
  56933. var randX = radius * Math.sin(s);
  56934. var randZ = radius * Math.cos(s);
  56935. var randY = h * this._height;
  56936. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56937. };
  56938. /**
  56939. * Clones the current emitter and returns a copy of it
  56940. * @returns the new emitter
  56941. */
  56942. ConeParticleEmitter.prototype.clone = function () {
  56943. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56944. BABYLON.Tools.DeepCopy(this, newOne);
  56945. return newOne;
  56946. };
  56947. /**
  56948. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56949. * @param effect defines the update shader
  56950. */
  56951. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56952. effect.setFloat("radius", this.radius);
  56953. effect.setFloat("angle", this.angle);
  56954. effect.setFloat("height", this._height);
  56955. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56956. };
  56957. /**
  56958. * Returns a string to use to update the GPU particles update shader
  56959. * @returns a string containng the defines string
  56960. */
  56961. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56962. return "#define CONEEMITTER";
  56963. };
  56964. /**
  56965. * Returns the string "BoxEmitter"
  56966. * @returns a string containing the class name
  56967. */
  56968. ConeParticleEmitter.prototype.getClassName = function () {
  56969. return "ConeEmitter";
  56970. };
  56971. /**
  56972. * Serializes the particle system to a JSON object.
  56973. * @returns the JSON object
  56974. */
  56975. ConeParticleEmitter.prototype.serialize = function () {
  56976. var serializationObject = {};
  56977. serializationObject.type = this.getClassName();
  56978. serializationObject.radius = this.radius;
  56979. serializationObject.angle = this.angle;
  56980. serializationObject.directionRandomizer = this.directionRandomizer;
  56981. return serializationObject;
  56982. };
  56983. /**
  56984. * Parse properties from a JSON object
  56985. * @param serializationObject defines the JSON object
  56986. */
  56987. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56988. this.radius = serializationObject.radius;
  56989. this.angle = serializationObject.angle;
  56990. this.directionRandomizer = serializationObject.directionRandomizer;
  56991. };
  56992. return ConeParticleEmitter;
  56993. }());
  56994. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56995. })(BABYLON || (BABYLON = {}));
  56996. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56997. var BABYLON;
  56998. (function (BABYLON) {
  56999. /**
  57000. * Particle emitter emitting particles from the inside of a sphere.
  57001. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57002. */
  57003. var SphereParticleEmitter = /** @class */ (function () {
  57004. /**
  57005. * Creates a new instance SphereParticleEmitter
  57006. * @param radius the radius of the emission sphere (1 by default)
  57007. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57008. */
  57009. function SphereParticleEmitter(
  57010. /**
  57011. * The radius of the emission sphere.
  57012. */
  57013. radius,
  57014. /**
  57015. * How much to randomize the particle direction [0-1].
  57016. */
  57017. directionRandomizer) {
  57018. if (radius === void 0) { radius = 1; }
  57019. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57020. this.radius = radius;
  57021. this.directionRandomizer = directionRandomizer;
  57022. }
  57023. /**
  57024. * Called by the particle System when the direction is computed for the created particle.
  57025. * @param emitPower is the power of the particle (speed)
  57026. * @param worldMatrix is the world matrix of the particle system
  57027. * @param directionToUpdate is the direction vector to update with the result
  57028. * @param particle is the particle we are computed the direction for
  57029. */
  57030. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57031. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57032. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57033. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57034. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57035. direction.x += randX;
  57036. direction.y += randY;
  57037. direction.z += randZ;
  57038. direction.normalize();
  57039. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57040. };
  57041. /**
  57042. * Called by the particle System when the position is computed for the created particle.
  57043. * @param worldMatrix is the world matrix of the particle system
  57044. * @param positionToUpdate is the position vector to update with the result
  57045. * @param particle is the particle we are computed the position for
  57046. */
  57047. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57048. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57049. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57050. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57051. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57052. var randY = randRadius * Math.cos(theta);
  57053. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57055. };
  57056. /**
  57057. * Clones the current emitter and returns a copy of it
  57058. * @returns the new emitter
  57059. */
  57060. SphereParticleEmitter.prototype.clone = function () {
  57061. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57062. BABYLON.Tools.DeepCopy(this, newOne);
  57063. return newOne;
  57064. };
  57065. /**
  57066. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57067. * @param effect defines the update shader
  57068. */
  57069. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57070. effect.setFloat("radius", this.radius);
  57071. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57072. };
  57073. /**
  57074. * Returns a string to use to update the GPU particles update shader
  57075. * @returns a string containng the defines string
  57076. */
  57077. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57078. return "#define SPHEREEMITTER";
  57079. };
  57080. /**
  57081. * Returns the string "SphereParticleEmitter"
  57082. * @returns a string containing the class name
  57083. */
  57084. SphereParticleEmitter.prototype.getClassName = function () {
  57085. return "SphereParticleEmitter";
  57086. };
  57087. /**
  57088. * Serializes the particle system to a JSON object.
  57089. * @returns the JSON object
  57090. */
  57091. SphereParticleEmitter.prototype.serialize = function () {
  57092. var serializationObject = {};
  57093. serializationObject.type = this.getClassName();
  57094. serializationObject.radius = this.radius;
  57095. serializationObject.directionRandomizer = this.directionRandomizer;
  57096. return serializationObject;
  57097. };
  57098. /**
  57099. * Parse properties from a JSON object
  57100. * @param serializationObject defines the JSON object
  57101. */
  57102. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57103. this.radius = serializationObject.radius;
  57104. this.directionRandomizer = serializationObject.directionRandomizer;
  57105. };
  57106. return SphereParticleEmitter;
  57107. }());
  57108. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57109. /**
  57110. * Particle emitter emitting particles from the inside of a sphere.
  57111. * It emits the particles randomly between two vectors.
  57112. */
  57113. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57114. __extends(SphereDirectedParticleEmitter, _super);
  57115. /**
  57116. * Creates a new instance SphereDirectedParticleEmitter
  57117. * @param radius the radius of the emission sphere (1 by default)
  57118. * @param direction1 the min limit of the emission direction (up vector by default)
  57119. * @param direction2 the max limit of the emission direction (up vector by default)
  57120. */
  57121. function SphereDirectedParticleEmitter(radius,
  57122. /**
  57123. * The min limit of the emission direction.
  57124. */
  57125. direction1,
  57126. /**
  57127. * The max limit of the emission direction.
  57128. */
  57129. direction2) {
  57130. if (radius === void 0) { radius = 1; }
  57131. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57132. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57133. var _this = _super.call(this, radius) || this;
  57134. _this.direction1 = direction1;
  57135. _this.direction2 = direction2;
  57136. return _this;
  57137. }
  57138. /**
  57139. * Called by the particle System when the direction is computed for the created particle.
  57140. * @param emitPower is the power of the particle (speed)
  57141. * @param worldMatrix is the world matrix of the particle system
  57142. * @param directionToUpdate is the direction vector to update with the result
  57143. * @param particle is the particle we are computed the direction for
  57144. */
  57145. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57146. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57147. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57148. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57149. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57150. };
  57151. /**
  57152. * Clones the current emitter and returns a copy of it
  57153. * @returns the new emitter
  57154. */
  57155. SphereDirectedParticleEmitter.prototype.clone = function () {
  57156. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57157. BABYLON.Tools.DeepCopy(this, newOne);
  57158. return newOne;
  57159. };
  57160. /**
  57161. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57162. * @param effect defines the update shader
  57163. */
  57164. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57165. effect.setFloat("radius", this.radius);
  57166. effect.setVector3("direction1", this.direction1);
  57167. effect.setVector3("direction2", this.direction2);
  57168. };
  57169. /**
  57170. * Returns a string to use to update the GPU particles update shader
  57171. * @returns a string containng the defines string
  57172. */
  57173. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57174. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57175. };
  57176. /**
  57177. * Returns the string "SphereDirectedParticleEmitter"
  57178. * @returns a string containing the class name
  57179. */
  57180. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57181. return "SphereDirectedParticleEmitter";
  57182. };
  57183. /**
  57184. * Serializes the particle system to a JSON object.
  57185. * @returns the JSON object
  57186. */
  57187. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57188. var serializationObject = _super.prototype.serialize.call(this);
  57189. serializationObject.direction1 = this.direction1.asArray();
  57190. serializationObject.direction2 = this.direction2.asArray();
  57191. return serializationObject;
  57192. };
  57193. /**
  57194. * Parse properties from a JSON object
  57195. * @param serializationObject defines the JSON object
  57196. */
  57197. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57198. _super.prototype.parse.call(this, serializationObject);
  57199. this.direction1.copyFrom(serializationObject.direction1);
  57200. this.direction2.copyFrom(serializationObject.direction2);
  57201. };
  57202. return SphereDirectedParticleEmitter;
  57203. }(SphereParticleEmitter));
  57204. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57205. })(BABYLON || (BABYLON = {}));
  57206. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57207. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57208. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57209. s = arguments[i];
  57210. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57211. t[p] = s[p];
  57212. }
  57213. return t;
  57214. };
  57215. var BABYLON;
  57216. (function (BABYLON) {
  57217. /**
  57218. * This represents a GPU particle system in Babylon
  57219. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57220. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57221. */
  57222. var GPUParticleSystem = /** @class */ (function () {
  57223. /**
  57224. * Instantiates a GPU particle system.
  57225. * 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.
  57226. * @param name The name of the particle system
  57227. * @param capacity The max number of particles alive at the same time
  57228. * @param scene The scene the particle system belongs to
  57229. */
  57230. function GPUParticleSystem(name, options, scene) {
  57231. /**
  57232. * The emitter represents the Mesh or position we are attaching the particle system to.
  57233. */
  57234. this.emitter = null;
  57235. /**
  57236. * The rendering group used by the Particle system to chose when to render.
  57237. */
  57238. this.renderingGroupId = 0;
  57239. /**
  57240. * The layer mask we are rendering the particles through.
  57241. */
  57242. this.layerMask = 0x0FFFFFFF;
  57243. this._targetIndex = 0;
  57244. this._currentRenderId = -1;
  57245. this._started = false;
  57246. this._stopped = false;
  57247. this._timeDelta = 0;
  57248. this._attributesStrideSize = 14;
  57249. this._actualFrame = 0;
  57250. /**
  57251. * List of animations used by the particle system.
  57252. */
  57253. this.animations = [];
  57254. /**
  57255. * An event triggered when the system is disposed.
  57256. */
  57257. this.onDisposeObservable = new BABYLON.Observable();
  57258. /**
  57259. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57260. */
  57261. this.updateSpeed = 0.01;
  57262. /**
  57263. * The amount of time the particle system is running (depends of the overall update speed).
  57264. */
  57265. this.targetStopDuration = 0;
  57266. /**
  57267. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57268. */
  57269. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57270. /**
  57271. * Minimum life time of emitting particles.
  57272. */
  57273. this.minLifeTime = 1;
  57274. /**
  57275. * Maximum life time of emitting particles.
  57276. */
  57277. this.maxLifeTime = 1;
  57278. /**
  57279. * Minimum Size of emitting particles.
  57280. */
  57281. this.minSize = 1;
  57282. /**
  57283. * Maximum Size of emitting particles.
  57284. */
  57285. this.maxSize = 1;
  57286. /**
  57287. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57288. */
  57289. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57290. /**
  57291. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57292. */
  57293. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57294. /**
  57295. * Color the particle will have at the end of its lifetime.
  57296. */
  57297. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57298. /**
  57299. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57300. */
  57301. this.emitRate = 100;
  57302. /**
  57303. * You can use gravity if you want to give an orientation to your particles.
  57304. */
  57305. this.gravity = BABYLON.Vector3.Zero();
  57306. /**
  57307. * Minimum power of emitting particles.
  57308. */
  57309. this.minEmitPower = 1;
  57310. /**
  57311. * Maximum power of emitting particles.
  57312. */
  57313. this.maxEmitPower = 1;
  57314. /**
  57315. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57316. * to override the particles.
  57317. */
  57318. this.forceDepthWrite = false;
  57319. this.id = name;
  57320. this.name = name;
  57321. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57322. this._engine = this._scene.getEngine();
  57323. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57324. this._capacity = fullOptions.capacity;
  57325. this._activeCount = fullOptions.capacity;
  57326. this._currentActiveCount = 0;
  57327. this._scene.particleSystems.push(this);
  57328. this._updateEffectOptions = {
  57329. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57330. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57331. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57332. uniformBuffersNames: [],
  57333. samplers: ["randomSampler"],
  57334. defines: "",
  57335. fallbacks: null,
  57336. onCompiled: null,
  57337. onError: null,
  57338. indexParameters: null,
  57339. maxSimultaneousLights: 0,
  57340. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57341. };
  57342. // Random data
  57343. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57344. var d = [];
  57345. for (var i = 0; i < maxTextureSize; ++i) {
  57346. d.push(Math.random());
  57347. d.push(Math.random());
  57348. d.push(Math.random());
  57349. d.push(Math.random());
  57350. }
  57351. 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);
  57352. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57353. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57354. this._randomTextureSize = maxTextureSize;
  57355. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57356. }
  57357. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57358. /**
  57359. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57360. */
  57361. get: function () {
  57362. if (!BABYLON.Engine.LastCreatedEngine) {
  57363. return false;
  57364. }
  57365. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57366. },
  57367. enumerable: true,
  57368. configurable: true
  57369. });
  57370. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57371. /**
  57372. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57373. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57374. */
  57375. get: function () {
  57376. if (this.particleEmitterType.direction1) {
  57377. return this.particleEmitterType.direction1;
  57378. }
  57379. return BABYLON.Vector3.Zero();
  57380. },
  57381. set: function (value) {
  57382. if (this.particleEmitterType.direction1) {
  57383. this.particleEmitterType.direction1 = value;
  57384. }
  57385. },
  57386. enumerable: true,
  57387. configurable: true
  57388. });
  57389. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57390. /**
  57391. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57392. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57393. */
  57394. get: function () {
  57395. if (this.particleEmitterType.direction2) {
  57396. return this.particleEmitterType.direction2;
  57397. }
  57398. return BABYLON.Vector3.Zero();
  57399. },
  57400. set: function (value) {
  57401. if (this.particleEmitterType.direction2) {
  57402. this.particleEmitterType.direction2 = value;
  57403. }
  57404. },
  57405. enumerable: true,
  57406. configurable: true
  57407. });
  57408. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57409. /**
  57410. * 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.
  57411. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57412. */
  57413. get: function () {
  57414. if (this.particleEmitterType.minEmitBox) {
  57415. return this.particleEmitterType.minEmitBox;
  57416. }
  57417. return BABYLON.Vector3.Zero();
  57418. },
  57419. set: function (value) {
  57420. if (this.particleEmitterType.minEmitBox) {
  57421. this.particleEmitterType.minEmitBox = value;
  57422. }
  57423. },
  57424. enumerable: true,
  57425. configurable: true
  57426. });
  57427. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57428. /**
  57429. * 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.
  57430. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57431. */
  57432. get: function () {
  57433. if (this.particleEmitterType.maxEmitBox) {
  57434. return this.particleEmitterType.maxEmitBox;
  57435. }
  57436. return BABYLON.Vector3.Zero();
  57437. },
  57438. set: function (value) {
  57439. if (this.particleEmitterType.maxEmitBox) {
  57440. this.particleEmitterType.maxEmitBox = value;
  57441. }
  57442. },
  57443. enumerable: true,
  57444. configurable: true
  57445. });
  57446. /**
  57447. * Gets the maximum number of particles active at the same time.
  57448. * @returns The max number of active particles.
  57449. */
  57450. GPUParticleSystem.prototype.getCapacity = function () {
  57451. return this._capacity;
  57452. };
  57453. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57454. /**
  57455. * Gets or set the number of active particles
  57456. */
  57457. get: function () {
  57458. return this._activeCount;
  57459. },
  57460. set: function (value) {
  57461. this._activeCount = Math.min(value, this._capacity);
  57462. },
  57463. enumerable: true,
  57464. configurable: true
  57465. });
  57466. /**
  57467. * Is this system ready to be used/rendered
  57468. * @return true if the system is ready
  57469. */
  57470. GPUParticleSystem.prototype.isReady = function () {
  57471. if (!this._updateEffect) {
  57472. this._recreateUpdateEffect();
  57473. this._recreateRenderEffect();
  57474. return false;
  57475. }
  57476. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57477. return false;
  57478. }
  57479. return true;
  57480. };
  57481. /**
  57482. * Gets Wether the system has been started.
  57483. * @returns True if it has been started, otherwise false.
  57484. */
  57485. GPUParticleSystem.prototype.isStarted = function () {
  57486. return this._started;
  57487. };
  57488. /**
  57489. * Starts the particle system and begins to emit.
  57490. */
  57491. GPUParticleSystem.prototype.start = function () {
  57492. this._started = true;
  57493. this._stopped = false;
  57494. };
  57495. /**
  57496. * Stops the particle system.
  57497. */
  57498. GPUParticleSystem.prototype.stop = function () {
  57499. this._stopped = true;
  57500. };
  57501. /**
  57502. * Remove all active particles
  57503. */
  57504. GPUParticleSystem.prototype.reset = function () {
  57505. this._releaseBuffers();
  57506. this._releaseVAOs();
  57507. this._currentActiveCount = 0;
  57508. this._targetIndex = 0;
  57509. };
  57510. /**
  57511. * Returns the string "GPUParticleSystem"
  57512. * @returns a string containing the class name
  57513. */
  57514. GPUParticleSystem.prototype.getClassName = function () {
  57515. return "GPUParticleSystem";
  57516. };
  57517. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57518. var updateVertexBuffers = {};
  57519. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57520. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57521. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57522. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57523. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57524. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57525. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57526. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57527. this._engine.bindArrayBuffer(null);
  57528. return vao;
  57529. };
  57530. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57531. var renderVertexBuffers = {};
  57532. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57533. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57534. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57535. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57536. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57537. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57538. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57539. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57540. this._engine.bindArrayBuffer(null);
  57541. return vao;
  57542. };
  57543. GPUParticleSystem.prototype._initialize = function (force) {
  57544. if (force === void 0) { force = false; }
  57545. if (this._buffer0 && !force) {
  57546. return;
  57547. }
  57548. var engine = this._scene.getEngine();
  57549. var data = new Array();
  57550. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57551. // position
  57552. data.push(0.0);
  57553. data.push(0.0);
  57554. data.push(0.0);
  57555. // Age and life
  57556. data.push(0.0); // create the particle as a dead one to create a new one at start
  57557. data.push(0.0);
  57558. // Seed
  57559. data.push(Math.random());
  57560. // Size
  57561. data.push(0.0);
  57562. // color
  57563. data.push(0.0);
  57564. data.push(0.0);
  57565. data.push(0.0);
  57566. data.push(0.0);
  57567. // direction
  57568. data.push(0.0);
  57569. data.push(0.0);
  57570. data.push(0.0);
  57571. }
  57572. // Sprite data
  57573. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57574. -0.5, 0.5, 0, 1,
  57575. -0.5, -0.5, 0, 0,
  57576. 0.5, -0.5, 1, 0]);
  57577. // Buffers
  57578. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57579. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57580. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57581. // Update VAO
  57582. this._updateVAO = [];
  57583. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57584. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57585. // Render VAO
  57586. this._renderVAO = [];
  57587. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57588. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57589. // Links
  57590. this._sourceBuffer = this._buffer0;
  57591. this._targetBuffer = this._buffer1;
  57592. };
  57593. /** @hidden */
  57594. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57595. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57596. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57597. return;
  57598. }
  57599. this._updateEffectOptions.defines = defines;
  57600. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57601. };
  57602. /** @hidden */
  57603. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57604. var defines = "";
  57605. if (this._scene.clipPlane) {
  57606. defines = "\n#define CLIPPLANE";
  57607. }
  57608. if (this._renderEffect && this._renderEffect.defines === defines) {
  57609. return;
  57610. }
  57611. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57612. };
  57613. /**
  57614. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57615. */
  57616. GPUParticleSystem.prototype.animate = function () {
  57617. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57618. this._actualFrame += this._timeDelta;
  57619. if (!this._stopped) {
  57620. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57621. this.stop();
  57622. }
  57623. }
  57624. };
  57625. /**
  57626. * Renders the particle system in its current state.
  57627. * @returns the current number of particles
  57628. */
  57629. GPUParticleSystem.prototype.render = function () {
  57630. if (!this._started) {
  57631. return 0;
  57632. }
  57633. this._recreateUpdateEffect();
  57634. this._recreateRenderEffect();
  57635. if (!this.isReady()) {
  57636. return 0;
  57637. }
  57638. if (this._currentRenderId === this._scene.getRenderId()) {
  57639. return 0;
  57640. }
  57641. this._currentRenderId = this._scene.getRenderId();
  57642. // Get everything ready to render
  57643. this._initialize();
  57644. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57645. // Enable update effect
  57646. this._engine.enableEffect(this._updateEffect);
  57647. this._engine.setState(false);
  57648. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57649. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57650. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57651. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57652. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57653. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57654. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57655. this._updateEffect.setDirectColor4("color1", this.color1);
  57656. this._updateEffect.setDirectColor4("color2", this.color2);
  57657. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57658. this._updateEffect.setVector3("gravity", this.gravity);
  57659. if (this.particleEmitterType) {
  57660. this.particleEmitterType.applyToShader(this._updateEffect);
  57661. }
  57662. var emitterWM;
  57663. if (this.emitter.position) {
  57664. var emitterMesh = this.emitter;
  57665. emitterWM = emitterMesh.getWorldMatrix();
  57666. }
  57667. else {
  57668. var emitterPosition = this.emitter;
  57669. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57670. }
  57671. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57672. // Bind source VAO
  57673. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57674. // Update
  57675. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57676. this._engine.setRasterizerState(false);
  57677. this._engine.beginTransformFeedback();
  57678. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57679. this._engine.endTransformFeedback();
  57680. this._engine.setRasterizerState(true);
  57681. this._engine.bindTransformFeedbackBuffer(null);
  57682. // Enable render effect
  57683. this._engine.enableEffect(this._renderEffect);
  57684. var viewMatrix = this._scene.getViewMatrix();
  57685. this._renderEffect.setMatrix("view", viewMatrix);
  57686. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57687. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57688. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57689. if (this._scene.clipPlane) {
  57690. var clipPlane = this._scene.clipPlane;
  57691. var invView = viewMatrix.clone();
  57692. invView.invert();
  57693. this._renderEffect.setMatrix("invView", invView);
  57694. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57695. }
  57696. // Draw order
  57697. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57698. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57699. }
  57700. else {
  57701. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57702. }
  57703. if (this.forceDepthWrite) {
  57704. this._engine.setDepthWrite(true);
  57705. }
  57706. // Bind source VAO
  57707. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57708. // Render
  57709. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57710. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57711. // Switch VAOs
  57712. this._targetIndex++;
  57713. if (this._targetIndex === 2) {
  57714. this._targetIndex = 0;
  57715. }
  57716. // Switch buffers
  57717. var tmpBuffer = this._sourceBuffer;
  57718. this._sourceBuffer = this._targetBuffer;
  57719. this._targetBuffer = tmpBuffer;
  57720. return this._currentActiveCount;
  57721. };
  57722. /**
  57723. * Rebuilds the particle system
  57724. */
  57725. GPUParticleSystem.prototype.rebuild = function () {
  57726. this._initialize(true);
  57727. };
  57728. GPUParticleSystem.prototype._releaseBuffers = function () {
  57729. if (this._buffer0) {
  57730. this._buffer0.dispose();
  57731. this._buffer0 = null;
  57732. }
  57733. if (this._buffer1) {
  57734. this._buffer1.dispose();
  57735. this._buffer1 = null;
  57736. }
  57737. if (this._spriteBuffer) {
  57738. this._spriteBuffer.dispose();
  57739. this._spriteBuffer = null;
  57740. }
  57741. };
  57742. GPUParticleSystem.prototype._releaseVAOs = function () {
  57743. if (!this._updateVAO) {
  57744. return;
  57745. }
  57746. for (var index = 0; index < this._updateVAO.length; index++) {
  57747. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57748. }
  57749. this._updateVAO = [];
  57750. for (var index = 0; index < this._renderVAO.length; index++) {
  57751. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57752. }
  57753. this._renderVAO = [];
  57754. };
  57755. /**
  57756. * Disposes the particle system and free the associated resources
  57757. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57758. */
  57759. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57760. if (disposeTexture === void 0) { disposeTexture = true; }
  57761. var index = this._scene.particleSystems.indexOf(this);
  57762. if (index > -1) {
  57763. this._scene.particleSystems.splice(index, 1);
  57764. }
  57765. this._releaseBuffers();
  57766. this._releaseVAOs();
  57767. if (this._randomTexture) {
  57768. this._randomTexture.dispose();
  57769. this._randomTexture = null;
  57770. }
  57771. if (disposeTexture && this.particleTexture) {
  57772. this.particleTexture.dispose();
  57773. this.particleTexture = null;
  57774. }
  57775. // Callback
  57776. this.onDisposeObservable.notifyObservers(this);
  57777. this.onDisposeObservable.clear();
  57778. };
  57779. /**
  57780. * Clones the particle system.
  57781. * @param name The name of the cloned object
  57782. * @param newEmitter The new emitter to use
  57783. * @returns the cloned particle system
  57784. */
  57785. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57786. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57787. BABYLON.Tools.DeepCopy(this, result);
  57788. if (newEmitter === undefined) {
  57789. newEmitter = this.emitter;
  57790. }
  57791. result.emitter = newEmitter;
  57792. if (this.particleTexture) {
  57793. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57794. }
  57795. return result;
  57796. };
  57797. /**
  57798. * Serializes the particle system to a JSON object.
  57799. * @returns the JSON object
  57800. */
  57801. GPUParticleSystem.prototype.serialize = function () {
  57802. var serializationObject = {};
  57803. serializationObject.name = this.name;
  57804. serializationObject.id = this.id;
  57805. // Emitter
  57806. if (this.emitter.position) {
  57807. var emitterMesh = this.emitter;
  57808. serializationObject.emitterId = emitterMesh.id;
  57809. }
  57810. else {
  57811. var emitterPosition = this.emitter;
  57812. serializationObject.emitter = emitterPosition.asArray();
  57813. }
  57814. serializationObject.capacity = this.getCapacity();
  57815. if (this.particleTexture) {
  57816. serializationObject.textureName = this.particleTexture.name;
  57817. }
  57818. // Animations
  57819. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57820. // Particle system
  57821. serializationObject.activeParticleCount = this.activeParticleCount;
  57822. serializationObject.randomTextureSize = this._randomTextureSize;
  57823. serializationObject.minSize = this.minSize;
  57824. serializationObject.maxSize = this.maxSize;
  57825. serializationObject.minEmitPower = this.minEmitPower;
  57826. serializationObject.maxEmitPower = this.maxEmitPower;
  57827. serializationObject.minLifeTime = this.minLifeTime;
  57828. serializationObject.maxLifeTime = this.maxLifeTime;
  57829. serializationObject.emitRate = this.emitRate;
  57830. serializationObject.gravity = this.gravity.asArray();
  57831. serializationObject.color1 = this.color1.asArray();
  57832. serializationObject.color2 = this.color2.asArray();
  57833. serializationObject.colorDead = this.colorDead.asArray();
  57834. serializationObject.updateSpeed = this.updateSpeed;
  57835. serializationObject.targetStopDuration = this.targetStopDuration;
  57836. serializationObject.blendMode = this.blendMode;
  57837. // Emitter
  57838. if (this.particleEmitterType) {
  57839. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57840. }
  57841. return serializationObject;
  57842. };
  57843. /**
  57844. * Parses a JSON object to create a GPU particle system.
  57845. * @param parsedParticleSystem The JSON object to parse
  57846. * @param scene The scene to create the particle system in
  57847. * @param rootUrl The root url to use to load external dependencies like texture
  57848. * @returns the parsed GPU particle system
  57849. */
  57850. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57851. var name = parsedParticleSystem.name;
  57852. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57853. if (parsedParticleSystem.id) {
  57854. particleSystem.id = parsedParticleSystem.id;
  57855. }
  57856. // Texture
  57857. if (parsedParticleSystem.textureName) {
  57858. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57859. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57860. }
  57861. // Emitter
  57862. if (parsedParticleSystem.emitterId) {
  57863. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57864. }
  57865. else {
  57866. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57867. }
  57868. // Animations
  57869. if (parsedParticleSystem.animations) {
  57870. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57871. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57872. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57873. }
  57874. }
  57875. // Particle system
  57876. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57877. particleSystem.minSize = parsedParticleSystem.minSize;
  57878. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57879. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57880. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57881. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57882. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57883. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57884. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57885. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57886. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57887. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57888. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57889. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57890. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57891. // Emitter
  57892. if (parsedParticleSystem.particleEmitterType) {
  57893. var emitterType = void 0;
  57894. switch (parsedParticleSystem.particleEmitterType.type) {
  57895. case "SphereEmitter":
  57896. emitterType = new BABYLON.SphereParticleEmitter();
  57897. break;
  57898. case "SphereDirectedParticleEmitter":
  57899. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57900. break;
  57901. case "ConeEmitter":
  57902. emitterType = new BABYLON.ConeParticleEmitter();
  57903. break;
  57904. case "BoxEmitter":
  57905. default:
  57906. emitterType = new BABYLON.BoxParticleEmitter();
  57907. break;
  57908. }
  57909. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57910. particleSystem.particleEmitterType = emitterType;
  57911. }
  57912. return particleSystem;
  57913. };
  57914. return GPUParticleSystem;
  57915. }());
  57916. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57917. })(BABYLON || (BABYLON = {}));
  57918. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57919. var BABYLON;
  57920. (function (BABYLON) {
  57921. /**
  57922. * Represents one particle of a solid particle system.
  57923. */
  57924. var SolidParticle = /** @class */ (function () {
  57925. /**
  57926. * Creates a Solid Particle object.
  57927. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57928. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57929. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57930. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57931. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57932. * @param shapeId (integer) is the model shape identifier in the SPS.
  57933. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57934. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57935. */
  57936. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57937. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57938. /**
  57939. * particle global index
  57940. */
  57941. this.idx = 0;
  57942. /**
  57943. * The color of the particle
  57944. */
  57945. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57946. /**
  57947. * The world space position of the particle.
  57948. */
  57949. this.position = BABYLON.Vector3.Zero();
  57950. /**
  57951. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57952. */
  57953. this.rotation = BABYLON.Vector3.Zero();
  57954. /**
  57955. * The scaling of the particle.
  57956. */
  57957. this.scaling = BABYLON.Vector3.One();
  57958. /**
  57959. * The uvs of the particle.
  57960. */
  57961. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57962. /**
  57963. * The current speed of the particle.
  57964. */
  57965. this.velocity = BABYLON.Vector3.Zero();
  57966. /**
  57967. * The pivot point in the particle local space.
  57968. */
  57969. this.pivot = BABYLON.Vector3.Zero();
  57970. /**
  57971. * Must the particle be translated from its pivot point in its local space ?
  57972. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57973. * Default : false
  57974. */
  57975. this.translateFromPivot = false;
  57976. /**
  57977. * Is the particle active or not ?
  57978. */
  57979. this.alive = true;
  57980. /**
  57981. * Is the particle visible or not ?
  57982. */
  57983. this.isVisible = true;
  57984. /**
  57985. * Index of this particle in the global "positions" array (Internal use)
  57986. */
  57987. this._pos = 0;
  57988. /**
  57989. * Index of this particle in the global "indices" array (Internal use)
  57990. */
  57991. this._ind = 0;
  57992. /**
  57993. * ModelShape id of this particle
  57994. */
  57995. this.shapeId = 0;
  57996. /**
  57997. * Index of the particle in its shape id (Internal use)
  57998. */
  57999. this.idxInShape = 0;
  58000. /**
  58001. * Still set as invisible in order to skip useless computations (Internal use)
  58002. */
  58003. this._stillInvisible = false;
  58004. /**
  58005. * Last computed particle rotation matrix
  58006. */
  58007. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58008. /**
  58009. * Parent particle Id, if any.
  58010. * Default null.
  58011. */
  58012. this.parentId = null;
  58013. /**
  58014. * Internal global position in the SPS.
  58015. */
  58016. this._globalPosition = BABYLON.Vector3.Zero();
  58017. this.idx = particleIndex;
  58018. this._pos = positionIndex;
  58019. this._ind = indiceIndex;
  58020. this._model = model;
  58021. this.shapeId = shapeId;
  58022. this.idxInShape = idxInShape;
  58023. this._sps = sps;
  58024. if (modelBoundingInfo) {
  58025. this._modelBoundingInfo = modelBoundingInfo;
  58026. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58027. }
  58028. }
  58029. Object.defineProperty(SolidParticle.prototype, "scale", {
  58030. /**
  58031. * Legacy support, changed scale to scaling
  58032. */
  58033. get: function () {
  58034. return this.scaling;
  58035. },
  58036. /**
  58037. * Legacy support, changed scale to scaling
  58038. */
  58039. set: function (scale) {
  58040. this.scaling = scale;
  58041. },
  58042. enumerable: true,
  58043. configurable: true
  58044. });
  58045. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58046. /**
  58047. * Legacy support, changed quaternion to rotationQuaternion
  58048. */
  58049. get: function () {
  58050. return this.rotationQuaternion;
  58051. },
  58052. /**
  58053. * Legacy support, changed quaternion to rotationQuaternion
  58054. */
  58055. set: function (q) {
  58056. this.rotationQuaternion = q;
  58057. },
  58058. enumerable: true,
  58059. configurable: true
  58060. });
  58061. /**
  58062. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58063. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58064. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58065. * @returns true if it intersects
  58066. */
  58067. SolidParticle.prototype.intersectsMesh = function (target) {
  58068. if (!this._boundingInfo || !target._boundingInfo) {
  58069. return false;
  58070. }
  58071. if (this._sps._bSphereOnly) {
  58072. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58073. }
  58074. return this._boundingInfo.intersects(target._boundingInfo, false);
  58075. };
  58076. return SolidParticle;
  58077. }());
  58078. BABYLON.SolidParticle = SolidParticle;
  58079. /**
  58080. * Represents the shape of the model used by one particle of a solid particle system.
  58081. * SPS internal tool, don't use it manually.
  58082. */
  58083. var ModelShape = /** @class */ (function () {
  58084. /**
  58085. * 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.
  58086. * SPS internal tool, don't use it manually.
  58087. * @hidden
  58088. */
  58089. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58090. /**
  58091. * length of the shape in the model indices array (internal use)
  58092. */
  58093. this._indicesLength = 0;
  58094. this.shapeID = id;
  58095. this._shape = shape;
  58096. this._indicesLength = indicesLength;
  58097. this._shapeUV = shapeUV;
  58098. this._positionFunction = posFunction;
  58099. this._vertexFunction = vtxFunction;
  58100. }
  58101. return ModelShape;
  58102. }());
  58103. BABYLON.ModelShape = ModelShape;
  58104. /**
  58105. * Represents a Depth Sorted Particle in the solid particle system.
  58106. */
  58107. var DepthSortedParticle = /** @class */ (function () {
  58108. function DepthSortedParticle() {
  58109. /**
  58110. * Index of the particle in the "indices" array
  58111. */
  58112. this.ind = 0;
  58113. /**
  58114. * Length of the particle shape in the "indices" array
  58115. */
  58116. this.indicesLength = 0;
  58117. /**
  58118. * Squared distance from the particle to the camera
  58119. */
  58120. this.sqDistance = 0.0;
  58121. }
  58122. return DepthSortedParticle;
  58123. }());
  58124. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58125. })(BABYLON || (BABYLON = {}));
  58126. //# sourceMappingURL=babylon.solidParticle.js.map
  58127. var BABYLON;
  58128. (function (BABYLON) {
  58129. /**
  58130. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58131. *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.
  58132. * The SPS is also a particle system. It provides some methods to manage the particles.
  58133. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58134. *
  58135. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58136. */
  58137. var SolidParticleSystem = /** @class */ (function () {
  58138. /**
  58139. * Creates a SPS (Solid Particle System) object.
  58140. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58141. * @param scene (Scene) is the scene in which the SPS is added.
  58142. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58143. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58144. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58145. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58146. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58147. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58148. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58149. */
  58150. function SolidParticleSystem(name, scene, options) {
  58151. /**
  58152. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58153. * Example : var p = SPS.particles[i];
  58154. */
  58155. this.particles = new Array();
  58156. /**
  58157. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58158. */
  58159. this.nbParticles = 0;
  58160. /**
  58161. * If the particles must ever face the camera (default false). Useful for planar particles.
  58162. */
  58163. this.billboard = false;
  58164. /**
  58165. * Recompute normals when adding a shape
  58166. */
  58167. this.recomputeNormals = true;
  58168. /**
  58169. * This a counter ofr your own usage. It's not set by any SPS functions.
  58170. */
  58171. this.counter = 0;
  58172. /**
  58173. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58174. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58175. */
  58176. this.vars = {};
  58177. /**
  58178. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58179. */
  58180. this._bSphereOnly = false;
  58181. /**
  58182. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58183. */
  58184. this._bSphereRadiusFactor = 1.0;
  58185. this._positions = new Array();
  58186. this._indices = new Array();
  58187. this._normals = new Array();
  58188. this._colors = new Array();
  58189. this._uvs = new Array();
  58190. this._index = 0; // indices index
  58191. this._updatable = true;
  58192. this._pickable = false;
  58193. this._isVisibilityBoxLocked = false;
  58194. this._alwaysVisible = false;
  58195. this._depthSort = false;
  58196. this._shapeCounter = 0;
  58197. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58198. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58199. this._computeParticleColor = true;
  58200. this._computeParticleTexture = true;
  58201. this._computeParticleRotation = true;
  58202. this._computeParticleVertex = false;
  58203. this._computeBoundingBox = false;
  58204. this._depthSortParticles = true;
  58205. this._cam_axisZ = BABYLON.Vector3.Zero();
  58206. this._cam_axisY = BABYLON.Vector3.Zero();
  58207. this._cam_axisX = BABYLON.Vector3.Zero();
  58208. this._axisZ = BABYLON.Axis.Z;
  58209. this._camDir = BABYLON.Vector3.Zero();
  58210. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58211. this._rotMatrix = new BABYLON.Matrix();
  58212. this._invertMatrix = new BABYLON.Matrix();
  58213. this._rotated = BABYLON.Vector3.Zero();
  58214. this._quaternion = new BABYLON.Quaternion();
  58215. this._vertex = BABYLON.Vector3.Zero();
  58216. this._normal = BABYLON.Vector3.Zero();
  58217. this._yaw = 0.0;
  58218. this._pitch = 0.0;
  58219. this._roll = 0.0;
  58220. this._halfroll = 0.0;
  58221. this._halfpitch = 0.0;
  58222. this._halfyaw = 0.0;
  58223. this._sinRoll = 0.0;
  58224. this._cosRoll = 0.0;
  58225. this._sinPitch = 0.0;
  58226. this._cosPitch = 0.0;
  58227. this._sinYaw = 0.0;
  58228. this._cosYaw = 0.0;
  58229. this._mustUnrotateFixedNormals = false;
  58230. this._minimum = BABYLON.Vector3.Zero();
  58231. this._maximum = BABYLON.Vector3.Zero();
  58232. this._minBbox = BABYLON.Vector3.Zero();
  58233. this._maxBbox = BABYLON.Vector3.Zero();
  58234. this._particlesIntersect = false;
  58235. this._depthSortFunction = function (p1, p2) {
  58236. return (p2.sqDistance - p1.sqDistance);
  58237. };
  58238. this._needs32Bits = false;
  58239. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58240. this._scaledPivot = BABYLON.Vector3.Zero();
  58241. this._particleHasParent = false;
  58242. this.name = name;
  58243. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58244. this._camera = scene.activeCamera;
  58245. this._pickable = options ? options.isPickable : false;
  58246. this._depthSort = options ? options.enableDepthSort : false;
  58247. this._particlesIntersect = options ? options.particleIntersection : false;
  58248. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58249. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58250. if (options && options.updatable) {
  58251. this._updatable = options.updatable;
  58252. }
  58253. else {
  58254. this._updatable = true;
  58255. }
  58256. if (this._pickable) {
  58257. this.pickedParticles = [];
  58258. }
  58259. if (this._depthSort) {
  58260. this.depthSortedParticles = [];
  58261. }
  58262. }
  58263. /**
  58264. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58265. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58266. * @returns the created mesh
  58267. */
  58268. SolidParticleSystem.prototype.buildMesh = function () {
  58269. if (this.nbParticles === 0) {
  58270. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58271. this.addShape(triangle, 1);
  58272. triangle.dispose();
  58273. }
  58274. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58275. this._positions32 = new Float32Array(this._positions);
  58276. this._uvs32 = new Float32Array(this._uvs);
  58277. this._colors32 = new Float32Array(this._colors);
  58278. if (this.recomputeNormals) {
  58279. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58280. }
  58281. this._normals32 = new Float32Array(this._normals);
  58282. this._fixedNormal32 = new Float32Array(this._normals);
  58283. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58284. this._unrotateFixedNormals();
  58285. }
  58286. var vertexData = new BABYLON.VertexData();
  58287. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58288. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58289. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58290. if (this._uvs32.length > 0) {
  58291. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58292. }
  58293. if (this._colors32.length > 0) {
  58294. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58295. }
  58296. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58297. vertexData.applyToMesh(mesh, this._updatable);
  58298. this.mesh = mesh;
  58299. this.mesh.isPickable = this._pickable;
  58300. // free memory
  58301. if (!this._depthSort) {
  58302. this._indices = null;
  58303. }
  58304. this._positions = null;
  58305. this._normals = null;
  58306. this._uvs = null;
  58307. this._colors = null;
  58308. if (!this._updatable) {
  58309. this.particles.length = 0;
  58310. }
  58311. return mesh;
  58312. };
  58313. /**
  58314. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58315. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58316. * Thus the particles generated from `digest()` have their property `position` set yet.
  58317. * @param mesh ( Mesh ) is the mesh to be digested
  58318. * @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
  58319. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58320. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58321. * @returns the current SPS
  58322. */
  58323. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58324. var size = (options && options.facetNb) || 1;
  58325. var number = (options && options.number) || 0;
  58326. var delta = (options && options.delta) || 0;
  58327. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58328. var meshInd = mesh.getIndices();
  58329. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58330. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58331. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58332. var f = 0; // facet counter
  58333. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58334. // compute size from number
  58335. if (number) {
  58336. number = (number > totalFacets) ? totalFacets : number;
  58337. size = Math.round(totalFacets / number);
  58338. delta = 0;
  58339. }
  58340. else {
  58341. size = (size > totalFacets) ? totalFacets : size;
  58342. }
  58343. var facetPos = []; // submesh positions
  58344. var facetInd = []; // submesh indices
  58345. var facetUV = []; // submesh UV
  58346. var facetCol = []; // submesh colors
  58347. var barycenter = BABYLON.Vector3.Zero();
  58348. var sizeO = size;
  58349. while (f < totalFacets) {
  58350. size = sizeO + Math.floor((1 + delta) * Math.random());
  58351. if (f > totalFacets - size) {
  58352. size = totalFacets - f;
  58353. }
  58354. // reset temp arrays
  58355. facetPos.length = 0;
  58356. facetInd.length = 0;
  58357. facetUV.length = 0;
  58358. facetCol.length = 0;
  58359. // iterate over "size" facets
  58360. var fi = 0;
  58361. for (var j = f * 3; j < (f + size) * 3; j++) {
  58362. facetInd.push(fi);
  58363. var i = meshInd[j];
  58364. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58365. if (meshUV) {
  58366. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58367. }
  58368. if (meshCol) {
  58369. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58370. }
  58371. fi++;
  58372. }
  58373. // create a model shape for each single particle
  58374. var idx = this.nbParticles;
  58375. var shape = this._posToShape(facetPos);
  58376. var shapeUV = this._uvsToShapeUV(facetUV);
  58377. // compute the barycenter of the shape
  58378. var v;
  58379. for (v = 0; v < shape.length; v++) {
  58380. barycenter.addInPlace(shape[v]);
  58381. }
  58382. barycenter.scaleInPlace(1 / shape.length);
  58383. // shift the shape from its barycenter to the origin
  58384. for (v = 0; v < shape.length; v++) {
  58385. shape[v].subtractInPlace(barycenter);
  58386. }
  58387. var bInfo;
  58388. if (this._particlesIntersect) {
  58389. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58390. }
  58391. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58392. // add the particle in the SPS
  58393. var currentPos = this._positions.length;
  58394. var currentInd = this._indices.length;
  58395. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58396. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58397. // initialize the particle position
  58398. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58399. this._index += shape.length;
  58400. idx++;
  58401. this.nbParticles++;
  58402. this._shapeCounter++;
  58403. f += size;
  58404. }
  58405. return this;
  58406. };
  58407. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58408. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58409. var index = 0;
  58410. var idx = 0;
  58411. for (var p = 0; p < this.particles.length; p++) {
  58412. this._particle = this.particles[p];
  58413. this._shape = this._particle._model._shape;
  58414. if (this._particle.rotationQuaternion) {
  58415. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58416. }
  58417. else {
  58418. this._yaw = this._particle.rotation.y;
  58419. this._pitch = this._particle.rotation.x;
  58420. this._roll = this._particle.rotation.z;
  58421. this._quaternionRotationYPR();
  58422. }
  58423. this._quaternionToRotationMatrix();
  58424. this._rotMatrix.invertToRef(this._invertMatrix);
  58425. for (var pt = 0; pt < this._shape.length; pt++) {
  58426. idx = index + pt * 3;
  58427. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58428. this._fixedNormal32[idx] = this._normal.x;
  58429. this._fixedNormal32[idx + 1] = this._normal.y;
  58430. this._fixedNormal32[idx + 2] = this._normal.z;
  58431. }
  58432. index = idx + 3;
  58433. }
  58434. };
  58435. //reset copy
  58436. SolidParticleSystem.prototype._resetCopy = function () {
  58437. this._copy.position.x = 0;
  58438. this._copy.position.y = 0;
  58439. this._copy.position.z = 0;
  58440. this._copy.rotation.x = 0;
  58441. this._copy.rotation.y = 0;
  58442. this._copy.rotation.z = 0;
  58443. this._copy.rotationQuaternion = null;
  58444. this._copy.scaling.x = 1.0;
  58445. this._copy.scaling.y = 1.0;
  58446. this._copy.scaling.z = 1.0;
  58447. this._copy.uvs.x = 0;
  58448. this._copy.uvs.y = 0;
  58449. this._copy.uvs.z = 1.0;
  58450. this._copy.uvs.w = 1.0;
  58451. this._copy.color = null;
  58452. this._copy.translateFromPivot = false;
  58453. };
  58454. // _meshBuilder : inserts the shape model in the global SPS mesh
  58455. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58456. var i;
  58457. var u = 0;
  58458. var c = 0;
  58459. var n = 0;
  58460. this._resetCopy();
  58461. if (options && options.positionFunction) { // call to custom positionFunction
  58462. options.positionFunction(this._copy, idx, idxInShape);
  58463. this._mustUnrotateFixedNormals = true;
  58464. }
  58465. if (this._copy.rotationQuaternion) {
  58466. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58467. }
  58468. else {
  58469. this._yaw = this._copy.rotation.y;
  58470. this._pitch = this._copy.rotation.x;
  58471. this._roll = this._copy.rotation.z;
  58472. this._quaternionRotationYPR();
  58473. }
  58474. this._quaternionToRotationMatrix();
  58475. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58476. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58477. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58478. if (this._copy.translateFromPivot) {
  58479. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58480. }
  58481. else {
  58482. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58483. }
  58484. for (i = 0; i < shape.length; i++) {
  58485. this._vertex.x = shape[i].x;
  58486. this._vertex.y = shape[i].y;
  58487. this._vertex.z = shape[i].z;
  58488. if (options && options.vertexFunction) {
  58489. options.vertexFunction(this._copy, this._vertex, i);
  58490. }
  58491. this._vertex.x *= this._copy.scaling.x;
  58492. this._vertex.y *= this._copy.scaling.y;
  58493. this._vertex.z *= this._copy.scaling.z;
  58494. this._vertex.x -= this._scaledPivot.x;
  58495. this._vertex.y -= this._scaledPivot.y;
  58496. this._vertex.z -= this._scaledPivot.z;
  58497. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58498. this._rotated.addInPlace(this._pivotBackTranslation);
  58499. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58500. if (meshUV) {
  58501. 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);
  58502. u += 2;
  58503. }
  58504. if (this._copy.color) {
  58505. this._color = this._copy.color;
  58506. }
  58507. else if (meshCol && meshCol[c] !== undefined) {
  58508. this._color.r = meshCol[c];
  58509. this._color.g = meshCol[c + 1];
  58510. this._color.b = meshCol[c + 2];
  58511. this._color.a = meshCol[c + 3];
  58512. }
  58513. else {
  58514. this._color.r = 1.0;
  58515. this._color.g = 1.0;
  58516. this._color.b = 1.0;
  58517. this._color.a = 1.0;
  58518. }
  58519. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58520. c += 4;
  58521. if (!this.recomputeNormals && meshNor) {
  58522. this._normal.x = meshNor[n];
  58523. this._normal.y = meshNor[n + 1];
  58524. this._normal.z = meshNor[n + 2];
  58525. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58526. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58527. n += 3;
  58528. }
  58529. }
  58530. for (i = 0; i < meshInd.length; i++) {
  58531. var current_ind = p + meshInd[i];
  58532. indices.push(current_ind);
  58533. if (current_ind > 65535) {
  58534. this._needs32Bits = true;
  58535. }
  58536. }
  58537. if (this._pickable) {
  58538. var nbfaces = meshInd.length / 3;
  58539. for (i = 0; i < nbfaces; i++) {
  58540. this.pickedParticles.push({ idx: idx, faceId: i });
  58541. }
  58542. }
  58543. if (this._depthSort) {
  58544. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58545. }
  58546. return this._copy;
  58547. };
  58548. // returns a shape array from positions array
  58549. SolidParticleSystem.prototype._posToShape = function (positions) {
  58550. var shape = [];
  58551. for (var i = 0; i < positions.length; i += 3) {
  58552. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58553. }
  58554. return shape;
  58555. };
  58556. // returns a shapeUV array from a Vector4 uvs
  58557. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58558. var shapeUV = [];
  58559. if (uvs) {
  58560. for (var i = 0; i < uvs.length; i++)
  58561. shapeUV.push(uvs[i]);
  58562. }
  58563. return shapeUV;
  58564. };
  58565. // adds a new particle object in the particles array
  58566. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58567. if (bInfo === void 0) { bInfo = null; }
  58568. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58569. this.particles.push(sp);
  58570. return sp;
  58571. };
  58572. /**
  58573. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58574. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58575. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58576. * @param nb (positive integer) the number of particles to be created from this model
  58577. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58578. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58579. * @returns the number of shapes in the system
  58580. */
  58581. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58582. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58583. var meshInd = mesh.getIndices();
  58584. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58585. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58586. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58587. var bbInfo;
  58588. if (this._particlesIntersect) {
  58589. bbInfo = mesh.getBoundingInfo();
  58590. }
  58591. var shape = this._posToShape(meshPos);
  58592. var shapeUV = this._uvsToShapeUV(meshUV);
  58593. var posfunc = options ? options.positionFunction : null;
  58594. var vtxfunc = options ? options.vertexFunction : null;
  58595. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58596. // particles
  58597. var sp;
  58598. var currentCopy;
  58599. var idx = this.nbParticles;
  58600. for (var i = 0; i < nb; i++) {
  58601. var currentPos = this._positions.length;
  58602. var currentInd = this._indices.length;
  58603. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58604. if (this._updatable) {
  58605. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58606. sp.position.copyFrom(currentCopy.position);
  58607. sp.rotation.copyFrom(currentCopy.rotation);
  58608. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58609. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58610. }
  58611. if (currentCopy.color && sp.color) {
  58612. sp.color.copyFrom(currentCopy.color);
  58613. }
  58614. sp.scaling.copyFrom(currentCopy.scaling);
  58615. sp.uvs.copyFrom(currentCopy.uvs);
  58616. }
  58617. this._index += shape.length;
  58618. idx++;
  58619. }
  58620. this.nbParticles += nb;
  58621. this._shapeCounter++;
  58622. return this._shapeCounter - 1;
  58623. };
  58624. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58625. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58626. this._resetCopy();
  58627. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58628. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58629. }
  58630. if (this._copy.rotationQuaternion) {
  58631. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58632. }
  58633. else {
  58634. this._yaw = this._copy.rotation.y;
  58635. this._pitch = this._copy.rotation.x;
  58636. this._roll = this._copy.rotation.z;
  58637. this._quaternionRotationYPR();
  58638. }
  58639. this._quaternionToRotationMatrix();
  58640. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58641. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58642. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58643. if (this._copy.translateFromPivot) {
  58644. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58645. }
  58646. else {
  58647. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58648. }
  58649. this._shape = particle._model._shape;
  58650. for (var pt = 0; pt < this._shape.length; pt++) {
  58651. this._vertex.x = this._shape[pt].x;
  58652. this._vertex.y = this._shape[pt].y;
  58653. this._vertex.z = this._shape[pt].z;
  58654. if (particle._model._vertexFunction) {
  58655. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58656. }
  58657. this._vertex.x *= this._copy.scaling.x;
  58658. this._vertex.y *= this._copy.scaling.y;
  58659. this._vertex.z *= this._copy.scaling.z;
  58660. this._vertex.x -= this._scaledPivot.x;
  58661. this._vertex.y -= this._scaledPivot.y;
  58662. this._vertex.z -= this._scaledPivot.z;
  58663. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58664. this._rotated.addInPlace(this._pivotBackTranslation);
  58665. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58666. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58667. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58668. }
  58669. particle.position.x = 0.0;
  58670. particle.position.y = 0.0;
  58671. particle.position.z = 0.0;
  58672. particle.rotation.x = 0.0;
  58673. particle.rotation.y = 0.0;
  58674. particle.rotation.z = 0.0;
  58675. particle.rotationQuaternion = null;
  58676. particle.scaling.x = 1.0;
  58677. particle.scaling.y = 1.0;
  58678. particle.scaling.z = 1.0;
  58679. particle.uvs.x = 0.0;
  58680. particle.uvs.y = 0.0;
  58681. particle.uvs.z = 1.0;
  58682. particle.uvs.w = 1.0;
  58683. particle.pivot.x = 0.0;
  58684. particle.pivot.y = 0.0;
  58685. particle.pivot.z = 0.0;
  58686. particle.translateFromPivot = false;
  58687. particle.parentId = null;
  58688. };
  58689. /**
  58690. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58691. * @returns the SPS.
  58692. */
  58693. SolidParticleSystem.prototype.rebuildMesh = function () {
  58694. for (var p = 0; p < this.particles.length; p++) {
  58695. this._rebuildParticle(this.particles[p]);
  58696. }
  58697. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58698. return this;
  58699. };
  58700. /**
  58701. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58702. * This method calls `updateParticle()` for each particle of the SPS.
  58703. * For an animated SPS, it is usually called within the render loop.
  58704. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58705. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58706. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58707. * @returns the SPS.
  58708. */
  58709. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58710. if (start === void 0) { start = 0; }
  58711. if (end === void 0) { end = this.nbParticles - 1; }
  58712. if (update === void 0) { update = true; }
  58713. if (!this._updatable) {
  58714. return this;
  58715. }
  58716. // custom beforeUpdate
  58717. this.beforeUpdateParticles(start, end, update);
  58718. this._cam_axisX.x = 1.0;
  58719. this._cam_axisX.y = 0.0;
  58720. this._cam_axisX.z = 0.0;
  58721. this._cam_axisY.x = 0.0;
  58722. this._cam_axisY.y = 1.0;
  58723. this._cam_axisY.z = 0.0;
  58724. this._cam_axisZ.x = 0.0;
  58725. this._cam_axisZ.y = 0.0;
  58726. this._cam_axisZ.z = 1.0;
  58727. // cases when the World Matrix is to be computed first
  58728. if (this.billboard || this._depthSort) {
  58729. this.mesh.computeWorldMatrix(true);
  58730. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58731. }
  58732. // if the particles will always face the camera
  58733. if (this.billboard) {
  58734. // compute the camera position and un-rotate it by the current mesh rotation
  58735. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58736. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58737. this._cam_axisZ.normalize();
  58738. // same for camera up vector extracted from the cam view matrix
  58739. var view = this._camera.getViewMatrix(true);
  58740. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58741. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58742. this._cam_axisY.normalize();
  58743. this._cam_axisX.normalize();
  58744. }
  58745. // if depthSort, compute the camera global position in the mesh local system
  58746. if (this._depthSort) {
  58747. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58748. }
  58749. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58750. var idx = 0; // current position index in the global array positions32
  58751. var index = 0; // position start index in the global array positions32 of the current particle
  58752. var colidx = 0; // current color index in the global array colors32
  58753. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58754. var uvidx = 0; // current uv index in the global array uvs32
  58755. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58756. var pt = 0; // current index in the particle model shape
  58757. if (this.mesh.isFacetDataEnabled) {
  58758. this._computeBoundingBox = true;
  58759. }
  58760. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58761. if (this._computeBoundingBox) {
  58762. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58763. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58764. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58765. }
  58766. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58767. if (this.mesh._boundingInfo) {
  58768. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58769. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58770. }
  58771. }
  58772. }
  58773. // particle loop
  58774. index = this.particles[start]._pos;
  58775. var vpos = (index / 3) | 0;
  58776. colorIndex = vpos * 4;
  58777. uvIndex = vpos * 2;
  58778. for (var p = start; p <= end; p++) {
  58779. this._particle = this.particles[p];
  58780. this._shape = this._particle._model._shape;
  58781. this._shapeUV = this._particle._model._shapeUV;
  58782. // call to custom user function to update the particle properties
  58783. this.updateParticle(this._particle);
  58784. // camera-particle distance for depth sorting
  58785. if (this._depthSort && this._depthSortParticles) {
  58786. var dsp = this.depthSortedParticles[p];
  58787. dsp.ind = this._particle._ind;
  58788. dsp.indicesLength = this._particle._model._indicesLength;
  58789. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58790. }
  58791. // skip the computations for inactive or already invisible particles
  58792. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58793. // increment indexes for the next particle
  58794. pt = this._shape.length;
  58795. index += pt * 3;
  58796. colorIndex += pt * 4;
  58797. uvIndex += pt * 2;
  58798. continue;
  58799. }
  58800. if (this._particle.isVisible) {
  58801. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58802. this._particleHasParent = (this._particle.parentId !== null);
  58803. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58804. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58805. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58806. // particle rotation matrix
  58807. if (this.billboard) {
  58808. this._particle.rotation.x = 0.0;
  58809. this._particle.rotation.y = 0.0;
  58810. }
  58811. if (this._computeParticleRotation || this.billboard) {
  58812. if (this._particle.rotationQuaternion) {
  58813. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58814. }
  58815. else {
  58816. this._yaw = this._particle.rotation.y;
  58817. this._pitch = this._particle.rotation.x;
  58818. this._roll = this._particle.rotation.z;
  58819. this._quaternionRotationYPR();
  58820. }
  58821. this._quaternionToRotationMatrix();
  58822. }
  58823. if (this._particleHasParent) {
  58824. this._parent = this.particles[this._particle.parentId];
  58825. 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];
  58826. 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];
  58827. 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];
  58828. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58829. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58830. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58831. if (this._computeParticleRotation || this.billboard) {
  58832. 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];
  58833. 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];
  58834. 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];
  58835. 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];
  58836. 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];
  58837. 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];
  58838. 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];
  58839. 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];
  58840. 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];
  58841. }
  58842. }
  58843. else {
  58844. this._particle._globalPosition.x = this._particle.position.x;
  58845. this._particle._globalPosition.y = this._particle.position.y;
  58846. this._particle._globalPosition.z = this._particle.position.z;
  58847. if (this._computeParticleRotation || this.billboard) {
  58848. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58849. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58850. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58851. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58852. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58853. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58854. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58855. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58856. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58857. }
  58858. }
  58859. if (this._particle.translateFromPivot) {
  58860. this._pivotBackTranslation.x = 0.0;
  58861. this._pivotBackTranslation.y = 0.0;
  58862. this._pivotBackTranslation.z = 0.0;
  58863. }
  58864. else {
  58865. this._pivotBackTranslation.x = this._scaledPivot.x;
  58866. this._pivotBackTranslation.y = this._scaledPivot.y;
  58867. this._pivotBackTranslation.z = this._scaledPivot.z;
  58868. }
  58869. // particle vertex loop
  58870. for (pt = 0; pt < this._shape.length; pt++) {
  58871. idx = index + pt * 3;
  58872. colidx = colorIndex + pt * 4;
  58873. uvidx = uvIndex + pt * 2;
  58874. this._vertex.x = this._shape[pt].x;
  58875. this._vertex.y = this._shape[pt].y;
  58876. this._vertex.z = this._shape[pt].z;
  58877. if (this._computeParticleVertex) {
  58878. this.updateParticleVertex(this._particle, this._vertex, pt);
  58879. }
  58880. // positions
  58881. this._vertex.x *= this._particle.scaling.x;
  58882. this._vertex.y *= this._particle.scaling.y;
  58883. this._vertex.z *= this._particle.scaling.z;
  58884. this._vertex.x -= this._scaledPivot.x;
  58885. this._vertex.y -= this._scaledPivot.y;
  58886. this._vertex.z -= this._scaledPivot.z;
  58887. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58888. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58889. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58890. this._rotated.x += this._pivotBackTranslation.x;
  58891. this._rotated.y += this._pivotBackTranslation.y;
  58892. this._rotated.z += this._pivotBackTranslation.z;
  58893. 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;
  58894. 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;
  58895. 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;
  58896. if (this._computeBoundingBox) {
  58897. if (this._positions32[idx] < this._minimum.x) {
  58898. this._minimum.x = this._positions32[idx];
  58899. }
  58900. if (this._positions32[idx] > this._maximum.x) {
  58901. this._maximum.x = this._positions32[idx];
  58902. }
  58903. if (this._positions32[idx + 1] < this._minimum.y) {
  58904. this._minimum.y = this._positions32[idx + 1];
  58905. }
  58906. if (this._positions32[idx + 1] > this._maximum.y) {
  58907. this._maximum.y = this._positions32[idx + 1];
  58908. }
  58909. if (this._positions32[idx + 2] < this._minimum.z) {
  58910. this._minimum.z = this._positions32[idx + 2];
  58911. }
  58912. if (this._positions32[idx + 2] > this._maximum.z) {
  58913. this._maximum.z = this._positions32[idx + 2];
  58914. }
  58915. }
  58916. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58917. if (!this._computeParticleVertex) {
  58918. this._normal.x = this._fixedNormal32[idx];
  58919. this._normal.y = this._fixedNormal32[idx + 1];
  58920. this._normal.z = this._fixedNormal32[idx + 2];
  58921. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58922. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58923. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58924. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58925. 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;
  58926. 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;
  58927. }
  58928. if (this._computeParticleColor && this._particle.color) {
  58929. this._colors32[colidx] = this._particle.color.r;
  58930. this._colors32[colidx + 1] = this._particle.color.g;
  58931. this._colors32[colidx + 2] = this._particle.color.b;
  58932. this._colors32[colidx + 3] = this._particle.color.a;
  58933. }
  58934. if (this._computeParticleTexture) {
  58935. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58936. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58937. }
  58938. }
  58939. }
  58940. // particle just set invisible : scaled to zero and positioned at the origin
  58941. else {
  58942. this._particle._stillInvisible = true; // mark the particle as invisible
  58943. for (pt = 0; pt < this._shape.length; pt++) {
  58944. idx = index + pt * 3;
  58945. colidx = colorIndex + pt * 4;
  58946. uvidx = uvIndex + pt * 2;
  58947. this._positions32[idx] = 0.0;
  58948. this._positions32[idx + 1] = 0.0;
  58949. this._positions32[idx + 2] = 0.0;
  58950. this._normals32[idx] = 0.0;
  58951. this._normals32[idx + 1] = 0.0;
  58952. this._normals32[idx + 2] = 0.0;
  58953. if (this._computeParticleColor && this._particle.color) {
  58954. this._colors32[colidx] = this._particle.color.r;
  58955. this._colors32[colidx + 1] = this._particle.color.g;
  58956. this._colors32[colidx + 2] = this._particle.color.b;
  58957. this._colors32[colidx + 3] = this._particle.color.a;
  58958. }
  58959. if (this._computeParticleTexture) {
  58960. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58961. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58962. }
  58963. }
  58964. }
  58965. // if the particle intersections must be computed : update the bbInfo
  58966. if (this._particlesIntersect) {
  58967. var bInfo = this._particle._boundingInfo;
  58968. var bBox = bInfo.boundingBox;
  58969. var bSphere = bInfo.boundingSphere;
  58970. if (!this._bSphereOnly) {
  58971. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58972. for (var b = 0; b < bBox.vectors.length; b++) {
  58973. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58974. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58975. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58976. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58977. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58978. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58979. 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;
  58980. 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;
  58981. 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;
  58982. }
  58983. bBox._update(this.mesh._worldMatrix);
  58984. }
  58985. // place and scale the particle bouding sphere in the SPS local system, then update it
  58986. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58987. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58988. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58989. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58990. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58991. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58992. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58993. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58994. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58995. 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));
  58996. bSphere._update(this.mesh._worldMatrix);
  58997. }
  58998. // increment indexes for the next particle
  58999. index = idx + 3;
  59000. colorIndex = colidx + 4;
  59001. uvIndex = uvidx + 2;
  59002. }
  59003. // if the VBO must be updated
  59004. if (update) {
  59005. if (this._computeParticleColor) {
  59006. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59007. }
  59008. if (this._computeParticleTexture) {
  59009. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59010. }
  59011. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59012. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59013. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59014. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59015. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59016. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59017. for (var i = 0; i < this._normals32.length; i++) {
  59018. this._fixedNormal32[i] = this._normals32[i];
  59019. }
  59020. }
  59021. if (!this.mesh.areNormalsFrozen) {
  59022. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59023. }
  59024. }
  59025. if (this._depthSort && this._depthSortParticles) {
  59026. this.depthSortedParticles.sort(this._depthSortFunction);
  59027. var dspl = this.depthSortedParticles.length;
  59028. var sorted = 0;
  59029. var lind = 0;
  59030. var sind = 0;
  59031. var sid = 0;
  59032. for (sorted = 0; sorted < dspl; sorted++) {
  59033. lind = this.depthSortedParticles[sorted].indicesLength;
  59034. sind = this.depthSortedParticles[sorted].ind;
  59035. for (var i = 0; i < lind; i++) {
  59036. this._indices32[sid] = this._indices[sind + i];
  59037. sid++;
  59038. }
  59039. }
  59040. this.mesh.updateIndices(this._indices32);
  59041. }
  59042. }
  59043. if (this._computeBoundingBox) {
  59044. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59045. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59046. }
  59047. this.afterUpdateParticles(start, end, update);
  59048. return this;
  59049. };
  59050. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59051. this._halfroll = this._roll * 0.5;
  59052. this._halfpitch = this._pitch * 0.5;
  59053. this._halfyaw = this._yaw * 0.5;
  59054. this._sinRoll = Math.sin(this._halfroll);
  59055. this._cosRoll = Math.cos(this._halfroll);
  59056. this._sinPitch = Math.sin(this._halfpitch);
  59057. this._cosPitch = Math.cos(this._halfpitch);
  59058. this._sinYaw = Math.sin(this._halfyaw);
  59059. this._cosYaw = Math.cos(this._halfyaw);
  59060. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59061. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59062. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59063. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59064. };
  59065. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59066. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59067. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59068. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59069. this._rotMatrix.m[3] = 0;
  59070. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59071. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59072. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59073. this._rotMatrix.m[7] = 0;
  59074. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59075. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59076. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59077. this._rotMatrix.m[11] = 0;
  59078. this._rotMatrix.m[12] = 0;
  59079. this._rotMatrix.m[13] = 0;
  59080. this._rotMatrix.m[14] = 0;
  59081. this._rotMatrix.m[15] = 1.0;
  59082. };
  59083. /**
  59084. * Disposes the SPS.
  59085. */
  59086. SolidParticleSystem.prototype.dispose = function () {
  59087. this.mesh.dispose();
  59088. this.vars = null;
  59089. // drop references to internal big arrays for the GC
  59090. this._positions = null;
  59091. this._indices = null;
  59092. this._normals = null;
  59093. this._uvs = null;
  59094. this._colors = null;
  59095. this._indices32 = null;
  59096. this._positions32 = null;
  59097. this._normals32 = null;
  59098. this._fixedNormal32 = null;
  59099. this._uvs32 = null;
  59100. this._colors32 = null;
  59101. this.pickedParticles = null;
  59102. };
  59103. /**
  59104. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59105. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59106. * @returns the SPS.
  59107. */
  59108. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59109. if (!this._isVisibilityBoxLocked) {
  59110. this.mesh.refreshBoundingInfo();
  59111. }
  59112. return this;
  59113. };
  59114. /**
  59115. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59116. * @param size the size (float) of the visibility box
  59117. * note : this doesn't lock the SPS mesh bounding box.
  59118. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59119. */
  59120. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59121. var vis = size / 2;
  59122. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59123. };
  59124. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59125. /**
  59126. * Gets whether the SPS as always visible or not
  59127. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59128. */
  59129. get: function () {
  59130. return this._alwaysVisible;
  59131. },
  59132. /**
  59133. * Sets the SPS as always visible or not
  59134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59135. */
  59136. set: function (val) {
  59137. this._alwaysVisible = val;
  59138. this.mesh.alwaysSelectAsActiveMesh = val;
  59139. },
  59140. enumerable: true,
  59141. configurable: true
  59142. });
  59143. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59144. /**
  59145. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59146. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59147. */
  59148. get: function () {
  59149. return this._isVisibilityBoxLocked;
  59150. },
  59151. /**
  59152. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59153. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59154. */
  59155. set: function (val) {
  59156. this._isVisibilityBoxLocked = val;
  59157. var boundingInfo = this.mesh.getBoundingInfo();
  59158. boundingInfo.isLocked = val;
  59159. },
  59160. enumerable: true,
  59161. configurable: true
  59162. });
  59163. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59164. /**
  59165. * Gets if `setParticles()` computes the particle rotations or not.
  59166. * Default value : true. The SPS is faster when it's set to false.
  59167. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59168. */
  59169. get: function () {
  59170. return this._computeParticleRotation;
  59171. },
  59172. /**
  59173. * Tells to `setParticles()` to compute the particle rotations or not.
  59174. * Default value : true. The SPS is faster when it's set to false.
  59175. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59176. */
  59177. set: function (val) {
  59178. this._computeParticleRotation = val;
  59179. },
  59180. enumerable: true,
  59181. configurable: true
  59182. });
  59183. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59184. /**
  59185. * Gets if `setParticles()` computes the particle colors or not.
  59186. * Default value : true. The SPS is faster when it's set to false.
  59187. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59188. */
  59189. get: function () {
  59190. return this._computeParticleColor;
  59191. },
  59192. /**
  59193. * Tells to `setParticles()` to compute the particle colors or not.
  59194. * Default value : true. The SPS is faster when it's set to false.
  59195. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59196. */
  59197. set: function (val) {
  59198. this._computeParticleColor = val;
  59199. },
  59200. enumerable: true,
  59201. configurable: true
  59202. });
  59203. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59204. /**
  59205. * Gets if `setParticles()` computes the particle textures or not.
  59206. * Default value : true. The SPS is faster when it's set to false.
  59207. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59208. */
  59209. get: function () {
  59210. return this._computeParticleTexture;
  59211. },
  59212. set: function (val) {
  59213. this._computeParticleTexture = val;
  59214. },
  59215. enumerable: true,
  59216. configurable: true
  59217. });
  59218. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59219. /**
  59220. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59221. * Default value : false. The SPS is faster when it's set to false.
  59222. * Note : the particle custom vertex positions aren't stored values.
  59223. */
  59224. get: function () {
  59225. return this._computeParticleVertex;
  59226. },
  59227. /**
  59228. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59229. * Default value : false. The SPS is faster when it's set to false.
  59230. * Note : the particle custom vertex positions aren't stored values.
  59231. */
  59232. set: function (val) {
  59233. this._computeParticleVertex = val;
  59234. },
  59235. enumerable: true,
  59236. configurable: true
  59237. });
  59238. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59239. /**
  59240. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59241. */
  59242. get: function () {
  59243. return this._computeBoundingBox;
  59244. },
  59245. /**
  59246. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59247. */
  59248. set: function (val) {
  59249. this._computeBoundingBox = val;
  59250. },
  59251. enumerable: true,
  59252. configurable: true
  59253. });
  59254. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59255. /**
  59256. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59257. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59258. * Default : `true`
  59259. */
  59260. get: function () {
  59261. return this._depthSortParticles;
  59262. },
  59263. /**
  59264. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59265. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59266. * Default : `true`
  59267. */
  59268. set: function (val) {
  59269. this._depthSortParticles = val;
  59270. },
  59271. enumerable: true,
  59272. configurable: true
  59273. });
  59274. // =======================================================================
  59275. // Particle behavior logic
  59276. // these following methods may be overwritten by the user to fit his needs
  59277. /**
  59278. * This function does nothing. It may be overwritten to set all the particle first values.
  59279. * The SPS doesn't call this function, you may have to call it by your own.
  59280. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59281. */
  59282. SolidParticleSystem.prototype.initParticles = function () {
  59283. };
  59284. /**
  59285. * This function does nothing. It may be overwritten to recycle a particle.
  59286. * The SPS doesn't call this function, you may have to call it by your own.
  59287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59288. * @param particle The particle to recycle
  59289. * @returns the recycled particle
  59290. */
  59291. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59292. return particle;
  59293. };
  59294. /**
  59295. * Updates a particle : this function should be overwritten by the user.
  59296. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59297. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59298. * @example : just set a particle position or velocity and recycle conditions
  59299. * @param particle The particle to update
  59300. * @returns the updated particle
  59301. */
  59302. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59303. return particle;
  59304. };
  59305. /**
  59306. * Updates a vertex of a particle : it can be overwritten by the user.
  59307. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59308. * @param particle the current particle
  59309. * @param vertex the current index of the current particle
  59310. * @param pt the index of the current vertex in the particle shape
  59311. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59312. * @example : just set a vertex particle position
  59313. * @returns the updated vertex
  59314. */
  59315. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59316. return vertex;
  59317. };
  59318. /**
  59319. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59320. * This does nothing and may be overwritten by the user.
  59321. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59322. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59323. * @param update the boolean update value actually passed to setParticles()
  59324. */
  59325. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59326. };
  59327. /**
  59328. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59329. * This will be passed three parameters.
  59330. * This does nothing and may be overwritten by the user.
  59331. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59332. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59333. * @param update the boolean update value actually passed to setParticles()
  59334. */
  59335. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59336. };
  59337. return SolidParticleSystem;
  59338. }());
  59339. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59340. })(BABYLON || (BABYLON = {}));
  59341. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59342. var BABYLON;
  59343. (function (BABYLON) {
  59344. var ShaderMaterial = /** @class */ (function (_super) {
  59345. __extends(ShaderMaterial, _super);
  59346. function ShaderMaterial(name, scene, shaderPath, options) {
  59347. var _this = _super.call(this, name, scene) || this;
  59348. _this._textures = {};
  59349. _this._textureArrays = {};
  59350. _this._floats = {};
  59351. _this._ints = {};
  59352. _this._floatsArrays = {};
  59353. _this._colors3 = {};
  59354. _this._colors3Arrays = {};
  59355. _this._colors4 = {};
  59356. _this._vectors2 = {};
  59357. _this._vectors3 = {};
  59358. _this._vectors4 = {};
  59359. _this._matrices = {};
  59360. _this._matrices3x3 = {};
  59361. _this._matrices2x2 = {};
  59362. _this._vectors2Arrays = {};
  59363. _this._vectors3Arrays = {};
  59364. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59365. _this._shaderPath = shaderPath;
  59366. options.needAlphaBlending = options.needAlphaBlending || false;
  59367. options.needAlphaTesting = options.needAlphaTesting || false;
  59368. options.attributes = options.attributes || ["position", "normal", "uv"];
  59369. options.uniforms = options.uniforms || ["worldViewProjection"];
  59370. options.uniformBuffers = options.uniformBuffers || [];
  59371. options.samplers = options.samplers || [];
  59372. options.defines = options.defines || [];
  59373. _this._options = options;
  59374. return _this;
  59375. }
  59376. ShaderMaterial.prototype.getClassName = function () {
  59377. return "ShaderMaterial";
  59378. };
  59379. ShaderMaterial.prototype.needAlphaBlending = function () {
  59380. return this._options.needAlphaBlending;
  59381. };
  59382. ShaderMaterial.prototype.needAlphaTesting = function () {
  59383. return this._options.needAlphaTesting;
  59384. };
  59385. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59386. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59387. this._options.uniforms.push(uniformName);
  59388. }
  59389. };
  59390. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59391. if (this._options.samplers.indexOf(name) === -1) {
  59392. this._options.samplers.push(name);
  59393. }
  59394. this._textures[name] = texture;
  59395. return this;
  59396. };
  59397. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59398. if (this._options.samplers.indexOf(name) === -1) {
  59399. this._options.samplers.push(name);
  59400. }
  59401. this._checkUniform(name);
  59402. this._textureArrays[name] = textures;
  59403. return this;
  59404. };
  59405. ShaderMaterial.prototype.setFloat = function (name, value) {
  59406. this._checkUniform(name);
  59407. this._floats[name] = value;
  59408. return this;
  59409. };
  59410. ShaderMaterial.prototype.setInt = function (name, value) {
  59411. this._checkUniform(name);
  59412. this._ints[name] = value;
  59413. return this;
  59414. };
  59415. ShaderMaterial.prototype.setFloats = function (name, value) {
  59416. this._checkUniform(name);
  59417. this._floatsArrays[name] = value;
  59418. return this;
  59419. };
  59420. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59421. this._checkUniform(name);
  59422. this._colors3[name] = value;
  59423. return this;
  59424. };
  59425. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59426. this._checkUniform(name);
  59427. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59428. color.toArray(arr, arr.length);
  59429. return arr;
  59430. }, []);
  59431. return this;
  59432. };
  59433. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59434. this._checkUniform(name);
  59435. this._colors4[name] = value;
  59436. return this;
  59437. };
  59438. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59439. this._checkUniform(name);
  59440. this._vectors2[name] = value;
  59441. return this;
  59442. };
  59443. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59444. this._checkUniform(name);
  59445. this._vectors3[name] = value;
  59446. return this;
  59447. };
  59448. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59449. this._checkUniform(name);
  59450. this._vectors4[name] = value;
  59451. return this;
  59452. };
  59453. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59454. this._checkUniform(name);
  59455. this._matrices[name] = value;
  59456. return this;
  59457. };
  59458. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59459. this._checkUniform(name);
  59460. this._matrices3x3[name] = value;
  59461. return this;
  59462. };
  59463. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59464. this._checkUniform(name);
  59465. this._matrices2x2[name] = value;
  59466. return this;
  59467. };
  59468. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59469. this._checkUniform(name);
  59470. this._vectors2Arrays[name] = value;
  59471. return this;
  59472. };
  59473. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59474. this._checkUniform(name);
  59475. this._vectors3Arrays[name] = value;
  59476. return this;
  59477. };
  59478. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59479. if (!mesh) {
  59480. return true;
  59481. }
  59482. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59483. return false;
  59484. }
  59485. return false;
  59486. };
  59487. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59488. var scene = this.getScene();
  59489. var engine = scene.getEngine();
  59490. if (!this.checkReadyOnEveryCall) {
  59491. if (this._renderId === scene.getRenderId()) {
  59492. if (this._checkCache(scene, mesh, useInstances)) {
  59493. return true;
  59494. }
  59495. }
  59496. }
  59497. // Instances
  59498. var defines = [];
  59499. var attribs = [];
  59500. var fallbacks = new BABYLON.EffectFallbacks();
  59501. if (useInstances) {
  59502. defines.push("#define INSTANCES");
  59503. }
  59504. for (var index = 0; index < this._options.defines.length; index++) {
  59505. defines.push(this._options.defines[index]);
  59506. }
  59507. for (var index = 0; index < this._options.attributes.length; index++) {
  59508. attribs.push(this._options.attributes[index]);
  59509. }
  59510. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59511. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59512. defines.push("#define VERTEXCOLOR");
  59513. }
  59514. // Bones
  59515. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59516. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59517. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59518. if (mesh.numBoneInfluencers > 4) {
  59519. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59520. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59521. }
  59522. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59523. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59524. fallbacks.addCPUSkinningFallback(0, mesh);
  59525. if (this._options.uniforms.indexOf("mBones") === -1) {
  59526. this._options.uniforms.push("mBones");
  59527. }
  59528. }
  59529. else {
  59530. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59531. }
  59532. // Textures
  59533. for (var name in this._textures) {
  59534. if (!this._textures[name].isReady()) {
  59535. return false;
  59536. }
  59537. }
  59538. // Alpha test
  59539. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59540. defines.push("#define ALPHATEST");
  59541. }
  59542. var previousEffect = this._effect;
  59543. var join = defines.join("\n");
  59544. this._effect = engine.createEffect(this._shaderPath, {
  59545. attributes: attribs,
  59546. uniformsNames: this._options.uniforms,
  59547. uniformBuffersNames: this._options.uniformBuffers,
  59548. samplers: this._options.samplers,
  59549. defines: join,
  59550. fallbacks: fallbacks,
  59551. onCompiled: this.onCompiled,
  59552. onError: this.onError
  59553. }, engine);
  59554. if (!this._effect.isReady()) {
  59555. return false;
  59556. }
  59557. if (previousEffect !== this._effect) {
  59558. scene.resetCachedMaterial();
  59559. }
  59560. this._renderId = scene.getRenderId();
  59561. return true;
  59562. };
  59563. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59564. var scene = this.getScene();
  59565. if (!this._effect) {
  59566. return;
  59567. }
  59568. if (this._options.uniforms.indexOf("world") !== -1) {
  59569. this._effect.setMatrix("world", world);
  59570. }
  59571. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59572. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59573. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59574. }
  59575. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59576. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59577. }
  59578. };
  59579. ShaderMaterial.prototype.bind = function (world, mesh) {
  59580. // Std values
  59581. this.bindOnlyWorldMatrix(world);
  59582. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59583. if (this._options.uniforms.indexOf("view") !== -1) {
  59584. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59585. }
  59586. if (this._options.uniforms.indexOf("projection") !== -1) {
  59587. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59588. }
  59589. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59590. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59591. }
  59592. // Bones
  59593. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59594. var name;
  59595. // Texture
  59596. for (name in this._textures) {
  59597. this._effect.setTexture(name, this._textures[name]);
  59598. }
  59599. // Texture arrays
  59600. for (name in this._textureArrays) {
  59601. this._effect.setTextureArray(name, this._textureArrays[name]);
  59602. }
  59603. // Int
  59604. for (name in this._ints) {
  59605. this._effect.setInt(name, this._ints[name]);
  59606. }
  59607. // Float
  59608. for (name in this._floats) {
  59609. this._effect.setFloat(name, this._floats[name]);
  59610. }
  59611. // Floats
  59612. for (name in this._floatsArrays) {
  59613. this._effect.setArray(name, this._floatsArrays[name]);
  59614. }
  59615. // Color3
  59616. for (name in this._colors3) {
  59617. this._effect.setColor3(name, this._colors3[name]);
  59618. }
  59619. for (name in this._colors3Arrays) {
  59620. this._effect.setArray3(name, this._colors3Arrays[name]);
  59621. }
  59622. // Color4
  59623. for (name in this._colors4) {
  59624. var color = this._colors4[name];
  59625. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59626. }
  59627. // Vector2
  59628. for (name in this._vectors2) {
  59629. this._effect.setVector2(name, this._vectors2[name]);
  59630. }
  59631. // Vector3
  59632. for (name in this._vectors3) {
  59633. this._effect.setVector3(name, this._vectors3[name]);
  59634. }
  59635. // Vector4
  59636. for (name in this._vectors4) {
  59637. this._effect.setVector4(name, this._vectors4[name]);
  59638. }
  59639. // Matrix
  59640. for (name in this._matrices) {
  59641. this._effect.setMatrix(name, this._matrices[name]);
  59642. }
  59643. // Matrix 3x3
  59644. for (name in this._matrices3x3) {
  59645. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59646. }
  59647. // Matrix 2x2
  59648. for (name in this._matrices2x2) {
  59649. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59650. }
  59651. // Vector2Array
  59652. for (name in this._vectors2Arrays) {
  59653. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59654. }
  59655. // Vector3Array
  59656. for (name in this._vectors3Arrays) {
  59657. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59658. }
  59659. }
  59660. this._afterBind(mesh);
  59661. };
  59662. ShaderMaterial.prototype.getActiveTextures = function () {
  59663. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59664. for (var name in this._textures) {
  59665. activeTextures.push(this._textures[name]);
  59666. }
  59667. for (var name in this._textureArrays) {
  59668. var array = this._textureArrays[name];
  59669. for (var index = 0; index < array.length; index++) {
  59670. activeTextures.push(array[index]);
  59671. }
  59672. }
  59673. return activeTextures;
  59674. };
  59675. ShaderMaterial.prototype.hasTexture = function (texture) {
  59676. if (_super.prototype.hasTexture.call(this, texture)) {
  59677. return true;
  59678. }
  59679. for (var name in this._textures) {
  59680. if (this._textures[name] === texture) {
  59681. return true;
  59682. }
  59683. }
  59684. for (var name in this._textureArrays) {
  59685. var array = this._textureArrays[name];
  59686. for (var index = 0; index < array.length; index++) {
  59687. if (array[index] === texture) {
  59688. return true;
  59689. }
  59690. }
  59691. }
  59692. return false;
  59693. };
  59694. ShaderMaterial.prototype.clone = function (name) {
  59695. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59696. return newShaderMaterial;
  59697. };
  59698. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59699. if (forceDisposeTextures) {
  59700. var name;
  59701. for (name in this._textures) {
  59702. this._textures[name].dispose();
  59703. }
  59704. for (name in this._textureArrays) {
  59705. var array = this._textureArrays[name];
  59706. for (var index = 0; index < array.length; index++) {
  59707. array[index].dispose();
  59708. }
  59709. }
  59710. }
  59711. this._textures = {};
  59712. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59713. };
  59714. ShaderMaterial.prototype.serialize = function () {
  59715. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59716. serializationObject.customType = "BABYLON.ShaderMaterial";
  59717. serializationObject.options = this._options;
  59718. serializationObject.shaderPath = this._shaderPath;
  59719. var name;
  59720. // Texture
  59721. serializationObject.textures = {};
  59722. for (name in this._textures) {
  59723. serializationObject.textures[name] = this._textures[name].serialize();
  59724. }
  59725. // Texture arrays
  59726. serializationObject.textureArrays = {};
  59727. for (name in this._textureArrays) {
  59728. serializationObject.textureArrays[name] = [];
  59729. var array = this._textureArrays[name];
  59730. for (var index = 0; index < array.length; index++) {
  59731. serializationObject.textureArrays[name].push(array[index].serialize());
  59732. }
  59733. }
  59734. // Float
  59735. serializationObject.floats = {};
  59736. for (name in this._floats) {
  59737. serializationObject.floats[name] = this._floats[name];
  59738. }
  59739. // Float s
  59740. serializationObject.FloatArrays = {};
  59741. for (name in this._floatsArrays) {
  59742. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59743. }
  59744. // Color3
  59745. serializationObject.colors3 = {};
  59746. for (name in this._colors3) {
  59747. serializationObject.colors3[name] = this._colors3[name].asArray();
  59748. }
  59749. // Color3 array
  59750. serializationObject.colors3Arrays = {};
  59751. for (name in this._colors3Arrays) {
  59752. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59753. }
  59754. // Color4
  59755. serializationObject.colors4 = {};
  59756. for (name in this._colors4) {
  59757. serializationObject.colors4[name] = this._colors4[name].asArray();
  59758. }
  59759. // Vector2
  59760. serializationObject.vectors2 = {};
  59761. for (name in this._vectors2) {
  59762. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59763. }
  59764. // Vector3
  59765. serializationObject.vectors3 = {};
  59766. for (name in this._vectors3) {
  59767. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59768. }
  59769. // Vector4
  59770. serializationObject.vectors4 = {};
  59771. for (name in this._vectors4) {
  59772. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59773. }
  59774. // Matrix
  59775. serializationObject.matrices = {};
  59776. for (name in this._matrices) {
  59777. serializationObject.matrices[name] = this._matrices[name].asArray();
  59778. }
  59779. // Matrix 3x3
  59780. serializationObject.matrices3x3 = {};
  59781. for (name in this._matrices3x3) {
  59782. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59783. }
  59784. // Matrix 2x2
  59785. serializationObject.matrices2x2 = {};
  59786. for (name in this._matrices2x2) {
  59787. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59788. }
  59789. // Vector2Array
  59790. serializationObject.vectors2Arrays = {};
  59791. for (name in this._vectors2Arrays) {
  59792. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59793. }
  59794. // Vector3Array
  59795. serializationObject.vectors3Arrays = {};
  59796. for (name in this._vectors3Arrays) {
  59797. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59798. }
  59799. return serializationObject;
  59800. };
  59801. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59802. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59803. var name;
  59804. // Texture
  59805. for (name in source.textures) {
  59806. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59807. }
  59808. // Texture arrays
  59809. for (name in source.textureArrays) {
  59810. var array = source.textureArrays[name];
  59811. var textureArray = new Array();
  59812. for (var index = 0; index < array.length; index++) {
  59813. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59814. }
  59815. material.setTextureArray(name, textureArray);
  59816. }
  59817. // Float
  59818. for (name in source.floats) {
  59819. material.setFloat(name, source.floats[name]);
  59820. }
  59821. // Float s
  59822. for (name in source.floatsArrays) {
  59823. material.setFloats(name, source.floatsArrays[name]);
  59824. }
  59825. // Color3
  59826. for (name in source.colors3) {
  59827. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59828. }
  59829. // Color3 arrays
  59830. for (name in source.colors3Arrays) {
  59831. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59832. if (i % 3 === 0) {
  59833. arr.push([num]);
  59834. }
  59835. else {
  59836. arr[arr.length - 1].push(num);
  59837. }
  59838. return arr;
  59839. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59840. material.setColor3Array(name, colors);
  59841. }
  59842. // Color4
  59843. for (name in source.colors4) {
  59844. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59845. }
  59846. // Vector2
  59847. for (name in source.vectors2) {
  59848. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59849. }
  59850. // Vector3
  59851. for (name in source.vectors3) {
  59852. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59853. }
  59854. // Vector4
  59855. for (name in source.vectors4) {
  59856. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59857. }
  59858. // Matrix
  59859. for (name in source.matrices) {
  59860. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59861. }
  59862. // Matrix 3x3
  59863. for (name in source.matrices3x3) {
  59864. material.setMatrix3x3(name, source.matrices3x3[name]);
  59865. }
  59866. // Matrix 2x2
  59867. for (name in source.matrices2x2) {
  59868. material.setMatrix2x2(name, source.matrices2x2[name]);
  59869. }
  59870. // Vector2Array
  59871. for (name in source.vectors2Arrays) {
  59872. material.setArray2(name, source.vectors2Arrays[name]);
  59873. }
  59874. // Vector3Array
  59875. for (name in source.vectors3Arrays) {
  59876. material.setArray3(name, source.vectors3Arrays[name]);
  59877. }
  59878. return material;
  59879. };
  59880. return ShaderMaterial;
  59881. }(BABYLON.Material));
  59882. BABYLON.ShaderMaterial = ShaderMaterial;
  59883. })(BABYLON || (BABYLON = {}));
  59884. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59885. var BABYLON;
  59886. (function (BABYLON) {
  59887. var GroundMesh = /** @class */ (function (_super) {
  59888. __extends(GroundMesh, _super);
  59889. function GroundMesh(name, scene) {
  59890. var _this = _super.call(this, name, scene) || this;
  59891. _this.generateOctree = false;
  59892. return _this;
  59893. }
  59894. GroundMesh.prototype.getClassName = function () {
  59895. return "GroundMesh";
  59896. };
  59897. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59898. get: function () {
  59899. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59900. },
  59901. enumerable: true,
  59902. configurable: true
  59903. });
  59904. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59905. get: function () {
  59906. return this._subdivisionsX;
  59907. },
  59908. enumerable: true,
  59909. configurable: true
  59910. });
  59911. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59912. get: function () {
  59913. return this._subdivisionsY;
  59914. },
  59915. enumerable: true,
  59916. configurable: true
  59917. });
  59918. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59919. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59920. this._subdivisionsX = chunksCount;
  59921. this._subdivisionsY = chunksCount;
  59922. this.subdivide(chunksCount);
  59923. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59924. };
  59925. /**
  59926. * Returns a height (y) value in the Worl system :
  59927. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59928. * Returns the ground y position if (x, z) are outside the ground surface.
  59929. */
  59930. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59931. var world = this.getWorldMatrix();
  59932. var invMat = BABYLON.Tmp.Matrix[5];
  59933. world.invertToRef(invMat);
  59934. var tmpVect = BABYLON.Tmp.Vector3[8];
  59935. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59936. x = tmpVect.x;
  59937. z = tmpVect.z;
  59938. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59939. return this.position.y;
  59940. }
  59941. if (!this._heightQuads || this._heightQuads.length == 0) {
  59942. this._initHeightQuads();
  59943. this._computeHeightQuads();
  59944. }
  59945. var facet = this._getFacetAt(x, z);
  59946. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59947. // return y in the World system
  59948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59949. return tmpVect.y;
  59950. };
  59951. /**
  59952. * Returns a normalized vector (Vector3) orthogonal to the ground
  59953. * at the ground coordinates (x, z) expressed in the World system.
  59954. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59955. */
  59956. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59957. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59958. this.getNormalAtCoordinatesToRef(x, z, normal);
  59959. return normal;
  59960. };
  59961. /**
  59962. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59963. * at the ground coordinates (x, z) expressed in the World system.
  59964. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59965. * Returns the GroundMesh.
  59966. */
  59967. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59968. var world = this.getWorldMatrix();
  59969. var tmpMat = BABYLON.Tmp.Matrix[5];
  59970. world.invertToRef(tmpMat);
  59971. var tmpVect = BABYLON.Tmp.Vector3[8];
  59972. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59973. x = tmpVect.x;
  59974. z = tmpVect.z;
  59975. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59976. return this;
  59977. }
  59978. if (!this._heightQuads || this._heightQuads.length == 0) {
  59979. this._initHeightQuads();
  59980. this._computeHeightQuads();
  59981. }
  59982. var facet = this._getFacetAt(x, z);
  59983. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59984. return this;
  59985. };
  59986. /**
  59987. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59988. * if the ground has been updated.
  59989. * This can be used in the render loop.
  59990. * Returns the GroundMesh.
  59991. */
  59992. GroundMesh.prototype.updateCoordinateHeights = function () {
  59993. if (!this._heightQuads || this._heightQuads.length == 0) {
  59994. this._initHeightQuads();
  59995. }
  59996. this._computeHeightQuads();
  59997. return this;
  59998. };
  59999. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60000. GroundMesh.prototype._getFacetAt = function (x, z) {
  60001. // retrieve col and row from x, z coordinates in the ground local system
  60002. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60003. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60004. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60005. var facet;
  60006. if (z < quad.slope.x * x + quad.slope.y) {
  60007. facet = quad.facet1;
  60008. }
  60009. else {
  60010. facet = quad.facet2;
  60011. }
  60012. return facet;
  60013. };
  60014. // Creates and populates the heightMap array with "facet" elements :
  60015. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60016. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60017. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60018. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60019. // Returns the GroundMesh.
  60020. GroundMesh.prototype._initHeightQuads = function () {
  60021. var subdivisionsX = this._subdivisionsX;
  60022. var subdivisionsY = this._subdivisionsY;
  60023. this._heightQuads = new Array();
  60024. for (var row = 0; row < subdivisionsY; row++) {
  60025. for (var col = 0; col < subdivisionsX; col++) {
  60026. 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) };
  60027. this._heightQuads[row * subdivisionsX + col] = quad;
  60028. }
  60029. }
  60030. return this;
  60031. };
  60032. // Compute each quad element values and update the the heightMap array :
  60033. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60034. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60035. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60036. // Returns the GroundMesh.
  60037. GroundMesh.prototype._computeHeightQuads = function () {
  60038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60039. if (!positions) {
  60040. return this;
  60041. }
  60042. var v1 = BABYLON.Tmp.Vector3[3];
  60043. var v2 = BABYLON.Tmp.Vector3[2];
  60044. var v3 = BABYLON.Tmp.Vector3[1];
  60045. var v4 = BABYLON.Tmp.Vector3[0];
  60046. var v1v2 = BABYLON.Tmp.Vector3[4];
  60047. var v1v3 = BABYLON.Tmp.Vector3[5];
  60048. var v1v4 = BABYLON.Tmp.Vector3[6];
  60049. var norm1 = BABYLON.Tmp.Vector3[7];
  60050. var norm2 = BABYLON.Tmp.Vector3[8];
  60051. var i = 0;
  60052. var j = 0;
  60053. var k = 0;
  60054. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60055. var h = 0;
  60056. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60057. var d2 = 0;
  60058. var subdivisionsX = this._subdivisionsX;
  60059. var subdivisionsY = this._subdivisionsY;
  60060. for (var row = 0; row < subdivisionsY; row++) {
  60061. for (var col = 0; col < subdivisionsX; col++) {
  60062. i = col * 3;
  60063. j = row * (subdivisionsX + 1) * 3;
  60064. k = (row + 1) * (subdivisionsX + 1) * 3;
  60065. v1.x = positions[j + i];
  60066. v1.y = positions[j + i + 1];
  60067. v1.z = positions[j + i + 2];
  60068. v2.x = positions[j + i + 3];
  60069. v2.y = positions[j + i + 4];
  60070. v2.z = positions[j + i + 5];
  60071. v3.x = positions[k + i];
  60072. v3.y = positions[k + i + 1];
  60073. v3.z = positions[k + i + 2];
  60074. v4.x = positions[k + i + 3];
  60075. v4.y = positions[k + i + 4];
  60076. v4.z = positions[k + i + 5];
  60077. // 2D slope V1V4
  60078. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60079. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60080. // facet equations :
  60081. // we compute each facet normal vector
  60082. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60083. // we compute the value d by applying the equation to v1 which belongs to the plane
  60084. // then we store the facet equation in a Vector4
  60085. v2.subtractToRef(v1, v1v2);
  60086. v3.subtractToRef(v1, v1v3);
  60087. v4.subtractToRef(v1, v1v4);
  60088. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60089. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60090. norm1.normalize();
  60091. norm2.normalize();
  60092. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60093. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60094. var quad = this._heightQuads[row * subdivisionsX + col];
  60095. quad.slope.copyFromFloats(cd, h);
  60096. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60097. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60098. }
  60099. }
  60100. return this;
  60101. };
  60102. GroundMesh.prototype.serialize = function (serializationObject) {
  60103. _super.prototype.serialize.call(this, serializationObject);
  60104. serializationObject.subdivisionsX = this._subdivisionsX;
  60105. serializationObject.subdivisionsY = this._subdivisionsY;
  60106. serializationObject.minX = this._minX;
  60107. serializationObject.maxX = this._maxX;
  60108. serializationObject.minZ = this._minZ;
  60109. serializationObject.maxZ = this._maxZ;
  60110. serializationObject.width = this._width;
  60111. serializationObject.height = this._height;
  60112. };
  60113. GroundMesh.Parse = function (parsedMesh, scene) {
  60114. var result = new GroundMesh(parsedMesh.name, scene);
  60115. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60116. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60117. result._minX = parsedMesh.minX;
  60118. result._maxX = parsedMesh.maxX;
  60119. result._minZ = parsedMesh.minZ;
  60120. result._maxZ = parsedMesh.maxZ;
  60121. result._width = parsedMesh.width;
  60122. result._height = parsedMesh.height;
  60123. return result;
  60124. };
  60125. return GroundMesh;
  60126. }(BABYLON.Mesh));
  60127. BABYLON.GroundMesh = GroundMesh;
  60128. })(BABYLON || (BABYLON = {}));
  60129. //# sourceMappingURL=babylon.groundMesh.js.map
  60130. var BABYLON;
  60131. (function (BABYLON) {
  60132. /**
  60133. * Creates an instance based on a source mesh.
  60134. */
  60135. var InstancedMesh = /** @class */ (function (_super) {
  60136. __extends(InstancedMesh, _super);
  60137. function InstancedMesh(name, source) {
  60138. var _this = _super.call(this, name, source.getScene()) || this;
  60139. source.instances.push(_this);
  60140. _this._sourceMesh = source;
  60141. _this.position.copyFrom(source.position);
  60142. _this.rotation.copyFrom(source.rotation);
  60143. _this.scaling.copyFrom(source.scaling);
  60144. if (source.rotationQuaternion) {
  60145. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60146. }
  60147. _this.infiniteDistance = source.infiniteDistance;
  60148. _this.setPivotMatrix(source.getPivotMatrix());
  60149. _this.refreshBoundingInfo();
  60150. _this._syncSubMeshes();
  60151. return _this;
  60152. }
  60153. /**
  60154. * Returns the string "InstancedMesh".
  60155. */
  60156. InstancedMesh.prototype.getClassName = function () {
  60157. return "InstancedMesh";
  60158. };
  60159. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60160. // Methods
  60161. get: function () {
  60162. return this._sourceMesh.receiveShadows;
  60163. },
  60164. enumerable: true,
  60165. configurable: true
  60166. });
  60167. Object.defineProperty(InstancedMesh.prototype, "material", {
  60168. get: function () {
  60169. return this._sourceMesh.material;
  60170. },
  60171. enumerable: true,
  60172. configurable: true
  60173. });
  60174. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60175. get: function () {
  60176. return this._sourceMesh.visibility;
  60177. },
  60178. enumerable: true,
  60179. configurable: true
  60180. });
  60181. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60182. get: function () {
  60183. return this._sourceMesh.skeleton;
  60184. },
  60185. enumerable: true,
  60186. configurable: true
  60187. });
  60188. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60189. get: function () {
  60190. return this._sourceMesh.renderingGroupId;
  60191. },
  60192. set: function (value) {
  60193. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60194. return;
  60195. }
  60196. //no-op with warning
  60197. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60198. },
  60199. enumerable: true,
  60200. configurable: true
  60201. });
  60202. /**
  60203. * Returns the total number of vertices (integer).
  60204. */
  60205. InstancedMesh.prototype.getTotalVertices = function () {
  60206. return this._sourceMesh.getTotalVertices();
  60207. };
  60208. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60209. get: function () {
  60210. return this._sourceMesh;
  60211. },
  60212. enumerable: true,
  60213. configurable: true
  60214. });
  60215. /**
  60216. * Is this node ready to be used/rendered
  60217. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60218. * @return {boolean} is it ready
  60219. */
  60220. InstancedMesh.prototype.isReady = function (completeCheck) {
  60221. if (completeCheck === void 0) { completeCheck = false; }
  60222. return this._sourceMesh.isReady(completeCheck, true);
  60223. };
  60224. /**
  60225. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60226. */
  60227. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60228. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60229. };
  60230. /**
  60231. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60232. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60233. * The `data` are either a numeric array either a Float32Array.
  60234. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60235. * 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).
  60236. * Note that a new underlying VertexBuffer object is created each call.
  60237. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60238. *
  60239. * Possible `kind` values :
  60240. * - BABYLON.VertexBuffer.PositionKind
  60241. * - BABYLON.VertexBuffer.UVKind
  60242. * - BABYLON.VertexBuffer.UV2Kind
  60243. * - BABYLON.VertexBuffer.UV3Kind
  60244. * - BABYLON.VertexBuffer.UV4Kind
  60245. * - BABYLON.VertexBuffer.UV5Kind
  60246. * - BABYLON.VertexBuffer.UV6Kind
  60247. * - BABYLON.VertexBuffer.ColorKind
  60248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60252. *
  60253. * Returns the Mesh.
  60254. */
  60255. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60256. if (this.sourceMesh) {
  60257. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60258. }
  60259. return this.sourceMesh;
  60260. };
  60261. /**
  60262. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60263. * If the mesh has no geometry, it is simply returned as it is.
  60264. * The `data` are either a numeric array either a Float32Array.
  60265. * No new underlying VertexBuffer object is created.
  60266. * 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.
  60267. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60268. *
  60269. * Possible `kind` values :
  60270. * - BABYLON.VertexBuffer.PositionKind
  60271. * - BABYLON.VertexBuffer.UVKind
  60272. * - BABYLON.VertexBuffer.UV2Kind
  60273. * - BABYLON.VertexBuffer.UV3Kind
  60274. * - BABYLON.VertexBuffer.UV4Kind
  60275. * - BABYLON.VertexBuffer.UV5Kind
  60276. * - BABYLON.VertexBuffer.UV6Kind
  60277. * - BABYLON.VertexBuffer.ColorKind
  60278. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60279. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60280. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60281. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60282. *
  60283. * Returns the Mesh.
  60284. */
  60285. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60286. if (this.sourceMesh) {
  60287. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60288. }
  60289. return this.sourceMesh;
  60290. };
  60291. /**
  60292. * Sets the mesh indices.
  60293. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60294. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60295. * This method creates a new index buffer each call.
  60296. * Returns the Mesh.
  60297. */
  60298. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60299. if (totalVertices === void 0) { totalVertices = null; }
  60300. if (this.sourceMesh) {
  60301. this.sourceMesh.setIndices(indices, totalVertices);
  60302. }
  60303. return this.sourceMesh;
  60304. };
  60305. /**
  60306. * Boolean : True if the mesh owns the requested kind of data.
  60307. */
  60308. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60309. return this._sourceMesh.isVerticesDataPresent(kind);
  60310. };
  60311. /**
  60312. * Returns an array of indices (IndicesArray).
  60313. */
  60314. InstancedMesh.prototype.getIndices = function () {
  60315. return this._sourceMesh.getIndices();
  60316. };
  60317. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60318. get: function () {
  60319. return this._sourceMesh._positions;
  60320. },
  60321. enumerable: true,
  60322. configurable: true
  60323. });
  60324. /**
  60325. * Sets a new updated BoundingInfo to the mesh.
  60326. * Returns the mesh.
  60327. */
  60328. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60329. var meshBB = this._sourceMesh.getBoundingInfo();
  60330. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60331. this._updateBoundingInfo();
  60332. return this;
  60333. };
  60334. InstancedMesh.prototype._preActivate = function () {
  60335. if (this._currentLOD) {
  60336. this._currentLOD._preActivate();
  60337. }
  60338. return this;
  60339. };
  60340. InstancedMesh.prototype._activate = function (renderId) {
  60341. if (this._currentLOD) {
  60342. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60343. }
  60344. return this;
  60345. };
  60346. /**
  60347. * Returns the current associated LOD AbstractMesh.
  60348. */
  60349. InstancedMesh.prototype.getLOD = function (camera) {
  60350. if (!camera) {
  60351. return this;
  60352. }
  60353. var boundingInfo = this.getBoundingInfo();
  60354. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60355. if (this._currentLOD === this.sourceMesh) {
  60356. return this;
  60357. }
  60358. return this._currentLOD;
  60359. };
  60360. InstancedMesh.prototype._syncSubMeshes = function () {
  60361. this.releaseSubMeshes();
  60362. if (this._sourceMesh.subMeshes) {
  60363. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60364. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60365. }
  60366. }
  60367. return this;
  60368. };
  60369. InstancedMesh.prototype._generatePointsArray = function () {
  60370. return this._sourceMesh._generatePointsArray();
  60371. };
  60372. /**
  60373. * Creates a new InstancedMesh from the current mesh.
  60374. * - name (string) : the cloned mesh name
  60375. * - newParent (optional Node) : the optional Node to parent the clone to.
  60376. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60377. *
  60378. * Returns the clone.
  60379. */
  60380. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60381. var result = this._sourceMesh.createInstance(name);
  60382. // Deep copy
  60383. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60384. // Bounding info
  60385. this.refreshBoundingInfo();
  60386. // Parent
  60387. if (newParent) {
  60388. result.parent = newParent;
  60389. }
  60390. if (!doNotCloneChildren) {
  60391. // Children
  60392. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60393. var mesh = this.getScene().meshes[index];
  60394. if (mesh.parent === this) {
  60395. mesh.clone(mesh.name, result);
  60396. }
  60397. }
  60398. }
  60399. result.computeWorldMatrix(true);
  60400. return result;
  60401. };
  60402. /**
  60403. * Disposes the InstancedMesh.
  60404. * Returns nothing.
  60405. */
  60406. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60407. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60408. // Remove from mesh
  60409. var index = this._sourceMesh.instances.indexOf(this);
  60410. this._sourceMesh.instances.splice(index, 1);
  60411. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60412. };
  60413. return InstancedMesh;
  60414. }(BABYLON.AbstractMesh));
  60415. BABYLON.InstancedMesh = InstancedMesh;
  60416. })(BABYLON || (BABYLON = {}));
  60417. //# sourceMappingURL=babylon.instancedMesh.js.map
  60418. var BABYLON;
  60419. (function (BABYLON) {
  60420. var LinesMesh = /** @class */ (function (_super) {
  60421. __extends(LinesMesh, _super);
  60422. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60423. if (scene === void 0) { scene = null; }
  60424. if (parent === void 0) { parent = null; }
  60425. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60426. _this.useVertexColor = useVertexColor;
  60427. _this.useVertexAlpha = useVertexAlpha;
  60428. _this.color = new BABYLON.Color3(1, 1, 1);
  60429. _this.alpha = 1;
  60430. if (source) {
  60431. _this.color = source.color.clone();
  60432. _this.alpha = source.alpha;
  60433. _this.useVertexColor = source.useVertexColor;
  60434. _this.useVertexAlpha = source.useVertexAlpha;
  60435. }
  60436. _this._intersectionThreshold = 0.1;
  60437. var defines = [];
  60438. var options = {
  60439. attributes: [BABYLON.VertexBuffer.PositionKind],
  60440. uniforms: ["world", "viewProjection"],
  60441. needAlphaBlending: true,
  60442. defines: defines
  60443. };
  60444. if (useVertexAlpha === false) {
  60445. options.needAlphaBlending = false;
  60446. }
  60447. if (!useVertexColor) {
  60448. options.uniforms.push("color");
  60449. }
  60450. else {
  60451. options.defines.push("#define VERTEXCOLOR");
  60452. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60453. }
  60454. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60455. return _this;
  60456. }
  60457. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60458. /**
  60459. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60460. * This margin is expressed in world space coordinates, so its value may vary.
  60461. * Default value is 0.1
  60462. * @returns the intersection Threshold value.
  60463. */
  60464. get: function () {
  60465. return this._intersectionThreshold;
  60466. },
  60467. /**
  60468. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60469. * This margin is expressed in world space coordinates, so its value may vary.
  60470. * @param value the new threshold to apply
  60471. */
  60472. set: function (value) {
  60473. if (this._intersectionThreshold === value) {
  60474. return;
  60475. }
  60476. this._intersectionThreshold = value;
  60477. if (this.geometry) {
  60478. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60479. }
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. /**
  60485. * Returns the string "LineMesh"
  60486. */
  60487. LinesMesh.prototype.getClassName = function () {
  60488. return "LinesMesh";
  60489. };
  60490. Object.defineProperty(LinesMesh.prototype, "material", {
  60491. get: function () {
  60492. return this._colorShader;
  60493. },
  60494. set: function (value) {
  60495. // Do nothing
  60496. },
  60497. enumerable: true,
  60498. configurable: true
  60499. });
  60500. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60501. get: function () {
  60502. return false;
  60503. },
  60504. enumerable: true,
  60505. configurable: true
  60506. });
  60507. LinesMesh.prototype.createInstance = function (name) {
  60508. throw new Error("LinesMeshes do not support createInstance.");
  60509. };
  60510. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60511. if (!this._geometry) {
  60512. return this;
  60513. }
  60514. // VBOs
  60515. this._geometry._bind(this._colorShader.getEffect());
  60516. // Color
  60517. if (!this.useVertexColor) {
  60518. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60519. }
  60520. return this;
  60521. };
  60522. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60523. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60524. return this;
  60525. }
  60526. var engine = this.getScene().getEngine();
  60527. // Draw order
  60528. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60529. return this;
  60530. };
  60531. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60532. this._colorShader.dispose();
  60533. _super.prototype.dispose.call(this, doNotRecurse);
  60534. };
  60535. /**
  60536. * Returns a new LineMesh object cloned from the current one.
  60537. */
  60538. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60539. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60540. };
  60541. return LinesMesh;
  60542. }(BABYLON.Mesh));
  60543. BABYLON.LinesMesh = LinesMesh;
  60544. })(BABYLON || (BABYLON = {}));
  60545. //# sourceMappingURL=babylon.linesMesh.js.map
  60546. var BABYLON;
  60547. (function (BABYLON) {
  60548. /**
  60549. * Class containing static functions to help procedurally build meshes
  60550. */
  60551. var MeshBuilder = /** @class */ (function () {
  60552. function MeshBuilder() {
  60553. }
  60554. MeshBuilder.updateSideOrientation = function (orientation) {
  60555. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60556. return BABYLON.Mesh.DOUBLESIDE;
  60557. }
  60558. if (orientation === undefined || orientation === null) {
  60559. return BABYLON.Mesh.FRONTSIDE;
  60560. }
  60561. return orientation;
  60562. };
  60563. /**
  60564. * Creates a box mesh
  60565. * * The parameter `size` sets the size (float) of each box side (default 1)
  60566. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60567. * * 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)
  60568. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60569. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60570. * * 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
  60571. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60572. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60573. * @param name defines the name of the mesh
  60574. * @param options defines the options used to create the mesh
  60575. * @param scene defines the hosting scene
  60576. * @returns the box mesh
  60577. */
  60578. MeshBuilder.CreateBox = function (name, options, scene) {
  60579. if (scene === void 0) { scene = null; }
  60580. var box = new BABYLON.Mesh(name, scene);
  60581. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60582. box._originalBuilderSideOrientation = options.sideOrientation;
  60583. var vertexData = BABYLON.VertexData.CreateBox(options);
  60584. vertexData.applyToMesh(box, options.updatable);
  60585. return box;
  60586. };
  60587. /**
  60588. * Creates a sphere mesh
  60589. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60590. * * 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`)
  60591. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60592. * * 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
  60593. * * 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)
  60594. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60595. * * 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
  60596. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60597. * @param name defines the name of the mesh
  60598. * @param options defines the options used to create the mesh
  60599. * @param scene defines the hosting scene
  60600. * @returns the sphere mesh
  60601. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60602. */
  60603. MeshBuilder.CreateSphere = function (name, options, scene) {
  60604. var sphere = new BABYLON.Mesh(name, scene);
  60605. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60606. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60607. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60608. vertexData.applyToMesh(sphere, options.updatable);
  60609. return sphere;
  60610. };
  60611. /**
  60612. * Creates a plane polygonal mesh. By default, this is a disc
  60613. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60614. * * 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
  60615. * * 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
  60616. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60617. * * 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
  60618. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60619. * @param name defines the name of the mesh
  60620. * @param options defines the options used to create the mesh
  60621. * @param scene defines the hosting scene
  60622. * @returns the plane polygonal mesh
  60623. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60624. */
  60625. MeshBuilder.CreateDisc = function (name, options, scene) {
  60626. if (scene === void 0) { scene = null; }
  60627. var disc = new BABYLON.Mesh(name, scene);
  60628. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60629. disc._originalBuilderSideOrientation = options.sideOrientation;
  60630. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60631. vertexData.applyToMesh(disc, options.updatable);
  60632. return disc;
  60633. };
  60634. /**
  60635. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60636. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60637. * * 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`)
  60638. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60639. * * 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
  60640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60641. * * 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
  60642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60643. * @param name defines the name of the mesh
  60644. * @param options defines the options used to create the mesh
  60645. * @param scene defines the hosting scene
  60646. * @returns the icosahedron mesh
  60647. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60648. */
  60649. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60650. var sphere = new BABYLON.Mesh(name, scene);
  60651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60652. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60653. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60654. vertexData.applyToMesh(sphere, options.updatable);
  60655. return sphere;
  60656. };
  60657. ;
  60658. /**
  60659. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60660. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60661. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60662. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60663. * * 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
  60664. * * 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
  60665. * * 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
  60666. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60667. * * 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
  60668. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60669. * * 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
  60670. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60671. * * 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
  60672. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60673. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60674. * @param name defines the name of the mesh
  60675. * @param options defines the options used to create the mesh
  60676. * @param scene defines the hosting scene
  60677. * @returns the ribbon mesh
  60678. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60679. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60680. */
  60681. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60682. if (scene === void 0) { scene = null; }
  60683. var pathArray = options.pathArray;
  60684. var closeArray = options.closeArray;
  60685. var closePath = options.closePath;
  60686. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60687. var instance = options.instance;
  60688. var updatable = options.updatable;
  60689. if (instance) { // existing ribbon instance update
  60690. // positionFunction : ribbon case
  60691. // only pathArray and sideOrientation parameters are taken into account for positions update
  60692. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60693. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60694. var positionFunction = function (positions) {
  60695. var minlg = pathArray[0].length;
  60696. var i = 0;
  60697. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60698. for (var si = 1; si <= ns; si++) {
  60699. for (var p = 0; p < pathArray.length; p++) {
  60700. var path = pathArray[p];
  60701. var l = path.length;
  60702. minlg = (minlg < l) ? minlg : l;
  60703. var j = 0;
  60704. while (j < minlg) {
  60705. positions[i] = path[j].x;
  60706. positions[i + 1] = path[j].y;
  60707. positions[i + 2] = path[j].z;
  60708. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60709. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60710. }
  60711. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60712. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60713. }
  60714. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60715. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60716. }
  60717. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60718. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60719. }
  60720. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60721. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60722. }
  60723. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60724. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60725. }
  60726. j++;
  60727. i += 3;
  60728. }
  60729. if (instance._closePath) {
  60730. positions[i] = path[0].x;
  60731. positions[i + 1] = path[0].y;
  60732. positions[i + 2] = path[0].z;
  60733. i += 3;
  60734. }
  60735. }
  60736. }
  60737. };
  60738. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60739. positionFunction(positions);
  60740. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60741. instance._boundingInfo.update(instance._worldMatrix);
  60742. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60743. if (options.colors) {
  60744. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60745. for (var c = 0; c < options.colors.length; c++) {
  60746. colors[c * 4] = options.colors[c].r;
  60747. colors[c * 4 + 1] = options.colors[c].g;
  60748. colors[c * 4 + 2] = options.colors[c].b;
  60749. colors[c * 4 + 3] = options.colors[c].a;
  60750. }
  60751. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60752. }
  60753. if (options.uvs) {
  60754. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60755. for (var i = 0; i < options.uvs.length; i++) {
  60756. uvs[i * 2] = options.uvs[i].x;
  60757. uvs[i * 2 + 1] = options.uvs[i].y;
  60758. }
  60759. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60760. }
  60761. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60762. var indices = instance.getIndices();
  60763. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60764. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60765. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60766. if (instance._closePath) {
  60767. var indexFirst = 0;
  60768. var indexLast = 0;
  60769. for (var p = 0; p < pathArray.length; p++) {
  60770. indexFirst = instance._idx[p] * 3;
  60771. if (p + 1 < pathArray.length) {
  60772. indexLast = (instance._idx[p + 1] - 1) * 3;
  60773. }
  60774. else {
  60775. indexLast = normals.length - 3;
  60776. }
  60777. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60778. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60779. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60780. normals[indexLast] = normals[indexFirst];
  60781. normals[indexLast + 1] = normals[indexFirst + 1];
  60782. normals[indexLast + 2] = normals[indexFirst + 2];
  60783. }
  60784. }
  60785. if (!(instance.areNormalsFrozen)) {
  60786. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60787. }
  60788. }
  60789. return instance;
  60790. }
  60791. else { // new ribbon creation
  60792. var ribbon = new BABYLON.Mesh(name, scene);
  60793. ribbon._originalBuilderSideOrientation = sideOrientation;
  60794. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60795. if (closePath) {
  60796. ribbon._idx = vertexData._idx;
  60797. }
  60798. ribbon._closePath = closePath;
  60799. ribbon._closeArray = closeArray;
  60800. vertexData.applyToMesh(ribbon, updatable);
  60801. return ribbon;
  60802. }
  60803. };
  60804. /**
  60805. * Creates a cylinder or a cone mesh
  60806. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60807. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60808. * * 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.
  60809. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60810. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60811. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60812. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60813. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60814. * * 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).
  60815. * * 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
  60816. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60817. * * 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
  60818. * * 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.
  60819. * * If `enclose` is false, a ring surface is one element.
  60820. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60821. * * 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
  60822. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60823. * * 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
  60824. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60825. * @param name defines the name of the mesh
  60826. * @param options defines the options used to create the mesh
  60827. * @param scene defines the hosting scene
  60828. * @returns the cylinder mesh
  60829. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60830. */
  60831. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60832. var cylinder = new BABYLON.Mesh(name, scene);
  60833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60834. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60835. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60836. vertexData.applyToMesh(cylinder, options.updatable);
  60837. return cylinder;
  60838. };
  60839. /**
  60840. * Creates a torus mesh
  60841. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60842. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60843. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60844. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60845. * * 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
  60846. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60847. * @param name defines the name of the mesh
  60848. * @param options defines the options used to create the mesh
  60849. * @param scene defines the hosting scene
  60850. * @returns the torus mesh
  60851. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60852. */
  60853. MeshBuilder.CreateTorus = function (name, options, scene) {
  60854. var torus = new BABYLON.Mesh(name, scene);
  60855. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60856. torus._originalBuilderSideOrientation = options.sideOrientation;
  60857. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60858. vertexData.applyToMesh(torus, options.updatable);
  60859. return torus;
  60860. };
  60861. /**
  60862. * Creates a torus knot mesh
  60863. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60864. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60865. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60866. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60867. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60868. * * 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
  60869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60870. * @param name defines the name of the mesh
  60871. * @param options defines the options used to create the mesh
  60872. * @param scene defines the hosting scene
  60873. * @returns the torus knot mesh
  60874. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60875. */
  60876. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60877. var torusKnot = new BABYLON.Mesh(name, scene);
  60878. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60879. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60880. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60881. vertexData.applyToMesh(torusKnot, options.updatable);
  60882. return torusKnot;
  60883. };
  60884. /**
  60885. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60886. * * 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
  60887. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60888. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60889. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60890. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60891. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60892. * * 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
  60893. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60895. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60896. * @param name defines the name of the new line system
  60897. * @param options defines the options used to create the line system
  60898. * @param scene defines the hosting scene
  60899. * @returns a new line system mesh
  60900. */
  60901. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60902. var instance = options.instance;
  60903. var lines = options.lines;
  60904. var colors = options.colors;
  60905. if (instance) { // lines update
  60906. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60907. var vertexColor;
  60908. var lineColors;
  60909. if (colors) {
  60910. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60911. }
  60912. var i = 0;
  60913. var c = 0;
  60914. for (var l = 0; l < lines.length; l++) {
  60915. var points = lines[l];
  60916. for (var p = 0; p < points.length; p++) {
  60917. positions[i] = points[p].x;
  60918. positions[i + 1] = points[p].y;
  60919. positions[i + 2] = points[p].z;
  60920. if (colors && vertexColor) {
  60921. lineColors = colors[l];
  60922. vertexColor[c] = lineColors[p].r;
  60923. vertexColor[c + 1] = lineColors[p].g;
  60924. vertexColor[c + 2] = lineColors[p].b;
  60925. vertexColor[c + 3] = lineColors[p].a;
  60926. c += 4;
  60927. }
  60928. i += 3;
  60929. }
  60930. }
  60931. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60932. if (colors && vertexColor) {
  60933. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60934. }
  60935. return instance;
  60936. }
  60937. // line system creation
  60938. var useVertexColor = (colors) ? true : false;
  60939. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60940. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60941. vertexData.applyToMesh(lineSystem, options.updatable);
  60942. return lineSystem;
  60943. };
  60944. /**
  60945. * Creates a line mesh
  60946. * 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
  60947. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60948. * * The parameter `points` is an array successive Vector3
  60949. * * 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
  60950. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60951. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60952. * * When updating an instance, remember that only point positions can change, not the number of points
  60953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60954. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60955. * @param name defines the name of the new line system
  60956. * @param options defines the options used to create the line system
  60957. * @param scene defines the hosting scene
  60958. * @returns a new line mesh
  60959. */
  60960. MeshBuilder.CreateLines = function (name, options, scene) {
  60961. if (scene === void 0) { scene = null; }
  60962. var colors = (options.colors) ? [options.colors] : null;
  60963. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60964. return lines;
  60965. };
  60966. /**
  60967. * Creates a dashed line mesh
  60968. * * 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
  60969. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60970. * * The parameter `points` is an array successive Vector3
  60971. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60972. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60973. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60974. * * 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
  60975. * * When updating an instance, remember that only point positions can change, not the number of points
  60976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60977. * @param name defines the name of the mesh
  60978. * @param options defines the options used to create the mesh
  60979. * @param scene defines the hosting scene
  60980. * @returns the dashed line mesh
  60981. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60982. */
  60983. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60984. if (scene === void 0) { scene = null; }
  60985. var points = options.points;
  60986. var instance = options.instance;
  60987. var gapSize = options.gapSize || 1;
  60988. var dashSize = options.dashSize || 3;
  60989. if (instance) { // dashed lines update
  60990. var positionFunction = function (positions) {
  60991. var curvect = BABYLON.Vector3.Zero();
  60992. var nbSeg = positions.length / 6;
  60993. var lg = 0;
  60994. var nb = 0;
  60995. var shft = 0;
  60996. var dashshft = 0;
  60997. var curshft = 0;
  60998. var p = 0;
  60999. var i = 0;
  61000. var j = 0;
  61001. for (i = 0; i < points.length - 1; i++) {
  61002. points[i + 1].subtractToRef(points[i], curvect);
  61003. lg += curvect.length();
  61004. }
  61005. shft = lg / nbSeg;
  61006. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61007. for (i = 0; i < points.length - 1; i++) {
  61008. points[i + 1].subtractToRef(points[i], curvect);
  61009. nb = Math.floor(curvect.length() / shft);
  61010. curvect.normalize();
  61011. j = 0;
  61012. while (j < nb && p < positions.length) {
  61013. curshft = shft * j;
  61014. positions[p] = points[i].x + curshft * curvect.x;
  61015. positions[p + 1] = points[i].y + curshft * curvect.y;
  61016. positions[p + 2] = points[i].z + curshft * curvect.z;
  61017. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61018. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61019. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61020. p += 6;
  61021. j++;
  61022. }
  61023. }
  61024. while (p < positions.length) {
  61025. positions[p] = points[i].x;
  61026. positions[p + 1] = points[i].y;
  61027. positions[p + 2] = points[i].z;
  61028. p += 3;
  61029. }
  61030. };
  61031. instance.updateMeshPositions(positionFunction, false);
  61032. return instance;
  61033. }
  61034. // dashed lines creation
  61035. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61036. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61037. vertexData.applyToMesh(dashedLines, options.updatable);
  61038. dashedLines.dashSize = dashSize;
  61039. dashedLines.gapSize = gapSize;
  61040. return dashedLines;
  61041. };
  61042. /**
  61043. * 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.
  61044. * * 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.
  61045. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61046. * * 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.
  61047. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61048. * * 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
  61049. * * 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
  61050. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61051. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61052. * * 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
  61053. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61055. * @param name defines the name of the mesh
  61056. * @param options defines the options used to create the mesh
  61057. * @param scene defines the hosting scene
  61058. * @returns the extruded shape mesh
  61059. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61060. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61061. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61062. */
  61063. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61064. if (scene === void 0) { scene = null; }
  61065. var path = options.path;
  61066. var shape = options.shape;
  61067. var scale = options.scale || 1;
  61068. var rotation = options.rotation || 0;
  61069. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61070. var updatable = options.updatable;
  61071. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61072. var instance = options.instance || null;
  61073. var invertUV = options.invertUV || false;
  61074. 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);
  61075. };
  61076. /**
  61077. * Creates an custom extruded shape mesh.
  61078. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61079. * * 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.
  61080. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61081. * * 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
  61082. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61083. * * 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
  61084. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61085. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61086. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61087. * * 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
  61088. * * 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
  61089. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61090. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61091. * * 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
  61092. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61093. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61094. * @param name defines the name of the mesh
  61095. * @param options defines the options used to create the mesh
  61096. * @param scene defines the hosting scene
  61097. * @returns the custom extruded shape mesh
  61098. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61099. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61100. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61101. */
  61102. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61103. var path = options.path;
  61104. var shape = options.shape;
  61105. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61106. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61107. var ribbonCloseArray = options.ribbonCloseArray || false;
  61108. var ribbonClosePath = options.ribbonClosePath || false;
  61109. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61110. var updatable = options.updatable;
  61111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61112. var instance = options.instance;
  61113. var invertUV = options.invertUV || false;
  61114. 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);
  61115. };
  61116. /**
  61117. * Creates lathe mesh.
  61118. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61119. * * 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
  61120. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61121. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61122. * * 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
  61123. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61124. * * 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
  61125. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61126. * * 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
  61127. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61128. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61129. * @param name defines the name of the mesh
  61130. * @param options defines the options used to create the mesh
  61131. * @param scene defines the hosting scene
  61132. * @returns the lathe mesh
  61133. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61134. */
  61135. MeshBuilder.CreateLathe = function (name, options, scene) {
  61136. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61137. var closed = (options.closed === undefined) ? true : options.closed;
  61138. var shape = options.shape;
  61139. var radius = options.radius || 1;
  61140. var tessellation = options.tessellation || 64;
  61141. var updatable = options.updatable;
  61142. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61143. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61144. var pi2 = Math.PI * 2;
  61145. var paths = new Array();
  61146. var invertUV = options.invertUV || false;
  61147. var i = 0;
  61148. var p = 0;
  61149. var step = pi2 / tessellation * arc;
  61150. var rotated;
  61151. var path = new Array();
  61152. for (i = 0; i <= tessellation; i++) {
  61153. var path = [];
  61154. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61155. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61156. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61157. }
  61158. for (p = 0; p < shape.length; p++) {
  61159. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61160. path.push(rotated);
  61161. }
  61162. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61163. 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));
  61164. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61165. }
  61166. paths.push(path);
  61167. }
  61168. // lathe ribbon
  61169. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61170. return lathe;
  61171. };
  61172. /**
  61173. * Creates a plane mesh
  61174. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61175. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61176. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61177. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61178. * * 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
  61179. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61180. * @param name defines the name of the mesh
  61181. * @param options defines the options used to create the mesh
  61182. * @param scene defines the hosting scene
  61183. * @returns the plane mesh
  61184. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61185. */
  61186. MeshBuilder.CreatePlane = function (name, options, scene) {
  61187. var plane = new BABYLON.Mesh(name, scene);
  61188. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61189. plane._originalBuilderSideOrientation = options.sideOrientation;
  61190. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61191. vertexData.applyToMesh(plane, options.updatable);
  61192. if (options.sourcePlane) {
  61193. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61194. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61195. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61196. plane.rotate(vectorProduct, product);
  61197. }
  61198. return plane;
  61199. };
  61200. /**
  61201. * Creates a ground mesh
  61202. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61203. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61204. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61205. * @param name defines the name of the mesh
  61206. * @param options defines the options used to create the mesh
  61207. * @param scene defines the hosting scene
  61208. * @returns the ground mesh
  61209. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61210. */
  61211. MeshBuilder.CreateGround = function (name, options, scene) {
  61212. var ground = new BABYLON.GroundMesh(name, scene);
  61213. ground._setReady(false);
  61214. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61215. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61216. ground._width = options.width || 1;
  61217. ground._height = options.height || 1;
  61218. ground._maxX = ground._width / 2;
  61219. ground._maxZ = ground._height / 2;
  61220. ground._minX = -ground._maxX;
  61221. ground._minZ = -ground._maxZ;
  61222. var vertexData = BABYLON.VertexData.CreateGround(options);
  61223. vertexData.applyToMesh(ground, options.updatable);
  61224. ground._setReady(true);
  61225. return ground;
  61226. };
  61227. /**
  61228. * Creates a tiled ground mesh
  61229. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61230. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61231. * * 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
  61232. * * 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
  61233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61234. * @param name defines the name of the mesh
  61235. * @param options defines the options used to create the mesh
  61236. * @param scene defines the hosting scene
  61237. * @returns the tiled ground mesh
  61238. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61239. */
  61240. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61241. var tiledGround = new BABYLON.Mesh(name, scene);
  61242. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61243. vertexData.applyToMesh(tiledGround, options.updatable);
  61244. return tiledGround;
  61245. };
  61246. /**
  61247. * Creates a ground mesh from a height map
  61248. * * The parameter `url` sets the URL of the height map image resource.
  61249. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61250. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61251. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61252. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61253. * * 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.
  61254. * * 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).
  61255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61256. * @param name defines the name of the mesh
  61257. * @param url defines the url to the height map
  61258. * @param options defines the options used to create the mesh
  61259. * @param scene defines the hosting scene
  61260. * @returns the ground mesh
  61261. * @see http://doc.babylonjs.com/babylon101/height_map
  61262. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61263. */
  61264. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61265. var width = options.width || 10.0;
  61266. var height = options.height || 10.0;
  61267. var subdivisions = options.subdivisions || 1 | 0;
  61268. var minHeight = options.minHeight || 0.0;
  61269. var maxHeight = options.maxHeight || 1.0;
  61270. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61271. var updatable = options.updatable;
  61272. var onReady = options.onReady;
  61273. var ground = new BABYLON.GroundMesh(name, scene);
  61274. ground._subdivisionsX = subdivisions;
  61275. ground._subdivisionsY = subdivisions;
  61276. ground._width = width;
  61277. ground._height = height;
  61278. ground._maxX = ground._width / 2.0;
  61279. ground._maxZ = ground._height / 2.0;
  61280. ground._minX = -ground._maxX;
  61281. ground._minZ = -ground._maxZ;
  61282. ground._setReady(false);
  61283. var onload = function (img) {
  61284. // Getting height map data
  61285. var canvas = document.createElement("canvas");
  61286. var context = canvas.getContext("2d");
  61287. if (!context) {
  61288. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61289. }
  61290. if (scene.isDisposed) {
  61291. return;
  61292. }
  61293. var bufferWidth = img.width;
  61294. var bufferHeight = img.height;
  61295. canvas.width = bufferWidth;
  61296. canvas.height = bufferHeight;
  61297. context.drawImage(img, 0, 0);
  61298. // Create VertexData from map data
  61299. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61300. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61301. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61302. width: width, height: height,
  61303. subdivisions: subdivisions,
  61304. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61305. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61306. });
  61307. vertexData.applyToMesh(ground, updatable);
  61308. //execute ready callback, if set
  61309. if (onReady) {
  61310. onReady(ground);
  61311. }
  61312. ground._setReady(true);
  61313. };
  61314. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61315. return ground;
  61316. };
  61317. /**
  61318. * Creates a polygon mesh
  61319. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61320. * * 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
  61321. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61322. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61323. * * 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)
  61324. * * Remember you can only change the shape positions, not their number when updating a polygon
  61325. * @param name defines the name of the mesh
  61326. * @param options defines the options used to create the mesh
  61327. * @param scene defines the hosting scene
  61328. * @returns the polygon mesh
  61329. */
  61330. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61331. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61332. var shape = options.shape;
  61333. var holes = options.holes || [];
  61334. var depth = options.depth || 0;
  61335. var contours = [];
  61336. var hole = [];
  61337. for (var i = 0; i < shape.length; i++) {
  61338. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61339. }
  61340. var epsilon = 0.00000001;
  61341. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61342. contours.pop();
  61343. }
  61344. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61345. for (var hNb = 0; hNb < holes.length; hNb++) {
  61346. hole = [];
  61347. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61348. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61349. }
  61350. polygonTriangulation.addHole(hole);
  61351. }
  61352. var polygon = polygonTriangulation.build(options.updatable, depth);
  61353. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61354. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61355. vertexData.applyToMesh(polygon, options.updatable);
  61356. return polygon;
  61357. };
  61358. ;
  61359. /**
  61360. * Creates an extruded polygon mesh, with depth in the Y direction.
  61361. * * 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)
  61362. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61363. * @param name defines the name of the mesh
  61364. * @param options defines the options used to create the mesh
  61365. * @param scene defines the hosting scene
  61366. * @returns the polygon mesh
  61367. */
  61368. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61369. return MeshBuilder.CreatePolygon(name, options, scene);
  61370. };
  61371. ;
  61372. /**
  61373. * Creates a tube mesh.
  61374. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61375. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61376. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61377. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61378. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61379. * * 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)
  61380. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61381. * * 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
  61382. * * 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
  61383. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61384. * * 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
  61385. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61386. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61387. * @param name defines the name of the mesh
  61388. * @param options defines the options used to create the mesh
  61389. * @param scene defines the hosting scene
  61390. * @returns the tube mesh
  61391. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61392. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61393. */
  61394. MeshBuilder.CreateTube = function (name, options, scene) {
  61395. var path = options.path;
  61396. var instance = options.instance;
  61397. var radius = 1.0;
  61398. if (instance) {
  61399. radius = instance.radius;
  61400. }
  61401. if (options.radius !== undefined) {
  61402. radius = options.radius;
  61403. }
  61404. ;
  61405. var tessellation = options.tessellation || 64 | 0;
  61406. var radiusFunction = options.radiusFunction || null;
  61407. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61408. var invertUV = options.invertUV || false;
  61409. var updatable = options.updatable;
  61410. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61411. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61412. // tube geometry
  61413. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61414. var tangents = path3D.getTangents();
  61415. var normals = path3D.getNormals();
  61416. var distances = path3D.getDistances();
  61417. var pi2 = Math.PI * 2;
  61418. var step = pi2 / tessellation * arc;
  61419. var returnRadius = function () { return radius; };
  61420. var radiusFunctionFinal = radiusFunction || returnRadius;
  61421. var circlePath;
  61422. var rad;
  61423. var normal;
  61424. var rotated;
  61425. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61426. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61427. for (var i = 0; i < path.length; i++) {
  61428. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61429. circlePath = Array(); // current circle array
  61430. normal = normals[i]; // current normal
  61431. for (var t = 0; t < tessellation; t++) {
  61432. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61433. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61434. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61435. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61436. circlePath[t] = rotated;
  61437. }
  61438. circlePaths[index] = circlePath;
  61439. index++;
  61440. }
  61441. // cap
  61442. var capPath = function (nbPoints, pathIndex) {
  61443. var pointCap = Array();
  61444. for (var i = 0; i < nbPoints; i++) {
  61445. pointCap.push(path[pathIndex]);
  61446. }
  61447. return pointCap;
  61448. };
  61449. switch (cap) {
  61450. case BABYLON.Mesh.NO_CAP:
  61451. break;
  61452. case BABYLON.Mesh.CAP_START:
  61453. circlePaths[0] = capPath(tessellation, 0);
  61454. circlePaths[1] = circlePaths[2].slice(0);
  61455. break;
  61456. case BABYLON.Mesh.CAP_END:
  61457. circlePaths[index] = circlePaths[index - 1].slice(0);
  61458. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61459. break;
  61460. case BABYLON.Mesh.CAP_ALL:
  61461. circlePaths[0] = capPath(tessellation, 0);
  61462. circlePaths[1] = circlePaths[2].slice(0);
  61463. circlePaths[index] = circlePaths[index - 1].slice(0);
  61464. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61465. break;
  61466. default:
  61467. break;
  61468. }
  61469. return circlePaths;
  61470. };
  61471. var path3D;
  61472. var pathArray;
  61473. if (instance) { // tube update
  61474. var arc = options.arc || instance.arc;
  61475. path3D = (instance.path3D).update(path);
  61476. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61477. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61478. instance.path3D = path3D;
  61479. instance.pathArray = pathArray;
  61480. instance.arc = arc;
  61481. instance.radius = radius;
  61482. return instance;
  61483. }
  61484. // tube creation
  61485. path3D = new BABYLON.Path3D(path);
  61486. var newPathArray = new Array();
  61487. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61488. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61489. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61490. tube.pathArray = pathArray;
  61491. tube.path3D = path3D;
  61492. tube.tessellation = tessellation;
  61493. tube.cap = cap;
  61494. tube.arc = options.arc;
  61495. tube.radius = radius;
  61496. return tube;
  61497. };
  61498. /**
  61499. * Creates a polyhedron mesh
  61500. * * 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
  61501. * * The parameter `size` (positive float, default 1) sets the polygon size
  61502. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61503. * * 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`
  61504. * * 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
  61505. * * 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)`)
  61506. * * 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
  61507. * * 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
  61508. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61509. * * 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
  61510. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61511. * @param name defines the name of the mesh
  61512. * @param options defines the options used to create the mesh
  61513. * @param scene defines the hosting scene
  61514. * @returns the polyhedron mesh
  61515. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61516. */
  61517. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61518. var polyhedron = new BABYLON.Mesh(name, scene);
  61519. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61520. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61521. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61522. vertexData.applyToMesh(polyhedron, options.updatable);
  61523. return polyhedron;
  61524. };
  61525. /**
  61526. * Creates a decal mesh.
  61527. * 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
  61528. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61529. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61530. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61531. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61532. * @param name defines the name of the mesh
  61533. * @param sourceMesh defines the mesh where the decal must be applied
  61534. * @param options defines the options used to create the mesh
  61535. * @param scene defines the hosting scene
  61536. * @returns the decal mesh
  61537. * @see http://doc.babylonjs.com/how_to/decals
  61538. */
  61539. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61540. var indices = sourceMesh.getIndices();
  61541. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61542. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61543. var position = options.position || BABYLON.Vector3.Zero();
  61544. var normal = options.normal || BABYLON.Vector3.Up();
  61545. var size = options.size || BABYLON.Vector3.One();
  61546. var angle = options.angle || 0;
  61547. // Getting correct rotation
  61548. if (!normal) {
  61549. var target = new BABYLON.Vector3(0, 0, 1);
  61550. var camera = sourceMesh.getScene().activeCamera;
  61551. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61552. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61553. }
  61554. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61555. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61556. var pitch = Math.atan2(normal.y, len);
  61557. // Matrix
  61558. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61559. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61560. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61561. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61562. var vertexData = new BABYLON.VertexData();
  61563. vertexData.indices = [];
  61564. vertexData.positions = [];
  61565. vertexData.normals = [];
  61566. vertexData.uvs = [];
  61567. var currentVertexDataIndex = 0;
  61568. var extractDecalVector3 = function (indexId) {
  61569. var result = new BABYLON.PositionNormalVertex();
  61570. if (!indices || !positions || !normals) {
  61571. return result;
  61572. }
  61573. var vertexId = indices[indexId];
  61574. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61575. // Send vector to decal local world
  61576. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61577. // Get normal
  61578. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61579. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61580. return result;
  61581. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61582. var clip = function (vertices, axis) {
  61583. if (vertices.length === 0) {
  61584. return vertices;
  61585. }
  61586. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61587. var clipVertices = function (v0, v1) {
  61588. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61589. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61590. };
  61591. var result = new Array();
  61592. for (var index = 0; index < vertices.length; index += 3) {
  61593. var v1Out;
  61594. var v2Out;
  61595. var v3Out;
  61596. var total = 0;
  61597. var nV1 = null;
  61598. var nV2 = null;
  61599. var nV3 = null;
  61600. var nV4 = null;
  61601. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61602. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61603. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61604. v1Out = d1 > 0;
  61605. v2Out = d2 > 0;
  61606. v3Out = d3 > 0;
  61607. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61608. switch (total) {
  61609. case 0:
  61610. result.push(vertices[index]);
  61611. result.push(vertices[index + 1]);
  61612. result.push(vertices[index + 2]);
  61613. break;
  61614. case 1:
  61615. if (v1Out) {
  61616. nV1 = vertices[index + 1];
  61617. nV2 = vertices[index + 2];
  61618. nV3 = clipVertices(vertices[index], nV1);
  61619. nV4 = clipVertices(vertices[index], nV2);
  61620. }
  61621. if (v2Out) {
  61622. nV1 = vertices[index];
  61623. nV2 = vertices[index + 2];
  61624. nV3 = clipVertices(vertices[index + 1], nV1);
  61625. nV4 = clipVertices(vertices[index + 1], nV2);
  61626. result.push(nV3);
  61627. result.push(nV2.clone());
  61628. result.push(nV1.clone());
  61629. result.push(nV2.clone());
  61630. result.push(nV3.clone());
  61631. result.push(nV4);
  61632. break;
  61633. }
  61634. if (v3Out) {
  61635. nV1 = vertices[index];
  61636. nV2 = vertices[index + 1];
  61637. nV3 = clipVertices(vertices[index + 2], nV1);
  61638. nV4 = clipVertices(vertices[index + 2], nV2);
  61639. }
  61640. if (nV1 && nV2 && nV3 && nV4) {
  61641. result.push(nV1.clone());
  61642. result.push(nV2.clone());
  61643. result.push(nV3);
  61644. result.push(nV4);
  61645. result.push(nV3.clone());
  61646. result.push(nV2.clone());
  61647. }
  61648. break;
  61649. case 2:
  61650. if (!v1Out) {
  61651. nV1 = vertices[index].clone();
  61652. nV2 = clipVertices(nV1, vertices[index + 1]);
  61653. nV3 = clipVertices(nV1, vertices[index + 2]);
  61654. result.push(nV1);
  61655. result.push(nV2);
  61656. result.push(nV3);
  61657. }
  61658. if (!v2Out) {
  61659. nV1 = vertices[index + 1].clone();
  61660. nV2 = clipVertices(nV1, vertices[index + 2]);
  61661. nV3 = clipVertices(nV1, vertices[index]);
  61662. result.push(nV1);
  61663. result.push(nV2);
  61664. result.push(nV3);
  61665. }
  61666. if (!v3Out) {
  61667. nV1 = vertices[index + 2].clone();
  61668. nV2 = clipVertices(nV1, vertices[index]);
  61669. nV3 = clipVertices(nV1, vertices[index + 1]);
  61670. result.push(nV1);
  61671. result.push(nV2);
  61672. result.push(nV3);
  61673. }
  61674. break;
  61675. case 3:
  61676. break;
  61677. }
  61678. }
  61679. return result;
  61680. };
  61681. for (var index = 0; index < indices.length; index += 3) {
  61682. var faceVertices = new Array();
  61683. faceVertices.push(extractDecalVector3(index));
  61684. faceVertices.push(extractDecalVector3(index + 1));
  61685. faceVertices.push(extractDecalVector3(index + 2));
  61686. // Clip
  61687. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61688. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61689. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61690. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61691. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61692. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61693. if (faceVertices.length === 0) {
  61694. continue;
  61695. }
  61696. // Add UVs and get back to world
  61697. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61698. var vertex = faceVertices[vIndex];
  61699. //TODO check for Int32Array | Uint32Array | Uint16Array
  61700. vertexData.indices.push(currentVertexDataIndex);
  61701. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61702. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61703. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61704. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61705. currentVertexDataIndex++;
  61706. }
  61707. }
  61708. // Return mesh
  61709. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61710. vertexData.applyToMesh(decal);
  61711. decal.position = position.clone();
  61712. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61713. return decal;
  61714. };
  61715. // Privates
  61716. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61717. // extrusion geometry
  61718. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61719. var tangents = path3D.getTangents();
  61720. var normals = path3D.getNormals();
  61721. var binormals = path3D.getBinormals();
  61722. var distances = path3D.getDistances();
  61723. var angle = 0;
  61724. var returnScale = function () { return scale !== null ? scale : 1; };
  61725. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61726. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61727. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61728. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61729. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61730. for (var i = 0; i < curve.length; i++) {
  61731. var shapePath = new Array();
  61732. var angleStep = rotate(i, distances[i]);
  61733. var scaleRatio = scl(i, distances[i]);
  61734. for (var p = 0; p < shape.length; p++) {
  61735. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61736. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61737. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61738. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61739. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61740. shapePath[p] = rotated;
  61741. }
  61742. shapePaths[index] = shapePath;
  61743. angle += angleStep;
  61744. index++;
  61745. }
  61746. // cap
  61747. var capPath = function (shapePath) {
  61748. var pointCap = Array();
  61749. var barycenter = BABYLON.Vector3.Zero();
  61750. var i;
  61751. for (i = 0; i < shapePath.length; i++) {
  61752. barycenter.addInPlace(shapePath[i]);
  61753. }
  61754. barycenter.scaleInPlace(1.0 / shapePath.length);
  61755. for (i = 0; i < shapePath.length; i++) {
  61756. pointCap.push(barycenter);
  61757. }
  61758. return pointCap;
  61759. };
  61760. switch (cap) {
  61761. case BABYLON.Mesh.NO_CAP:
  61762. break;
  61763. case BABYLON.Mesh.CAP_START:
  61764. shapePaths[0] = capPath(shapePaths[2]);
  61765. shapePaths[1] = shapePaths[2];
  61766. break;
  61767. case BABYLON.Mesh.CAP_END:
  61768. shapePaths[index] = shapePaths[index - 1];
  61769. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61770. break;
  61771. case BABYLON.Mesh.CAP_ALL:
  61772. shapePaths[0] = capPath(shapePaths[2]);
  61773. shapePaths[1] = shapePaths[2];
  61774. shapePaths[index] = shapePaths[index - 1];
  61775. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61776. break;
  61777. default:
  61778. break;
  61779. }
  61780. return shapePaths;
  61781. };
  61782. var path3D;
  61783. var pathArray;
  61784. if (instance) { // instance update
  61785. path3D = (instance.path3D).update(curve);
  61786. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61787. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61788. return instance;
  61789. }
  61790. // extruded shape creation
  61791. path3D = new BABYLON.Path3D(curve);
  61792. var newShapePaths = new Array();
  61793. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61794. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61795. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61796. extrudedGeneric.pathArray = pathArray;
  61797. extrudedGeneric.path3D = path3D;
  61798. extrudedGeneric.cap = cap;
  61799. return extrudedGeneric;
  61800. };
  61801. return MeshBuilder;
  61802. }());
  61803. BABYLON.MeshBuilder = MeshBuilder;
  61804. })(BABYLON || (BABYLON = {}));
  61805. //# sourceMappingURL=babylon.meshBuilder.js.map
  61806. var BABYLON;
  61807. (function (BABYLON) {
  61808. /**
  61809. * Draco compression (https://google.github.io/draco/)
  61810. */
  61811. var DracoCompression = /** @class */ (function () {
  61812. /**
  61813. * Constructor
  61814. */
  61815. function DracoCompression() {
  61816. }
  61817. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61818. /**
  61819. * Returns true if the decoder is available.
  61820. */
  61821. get: function () {
  61822. if (typeof DracoDecoderModule !== "undefined") {
  61823. return true;
  61824. }
  61825. var decoder = DracoCompression.Configuration.decoder;
  61826. if (decoder) {
  61827. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61828. return true;
  61829. }
  61830. if (decoder.fallbackUrl) {
  61831. return true;
  61832. }
  61833. }
  61834. return false;
  61835. },
  61836. enumerable: true,
  61837. configurable: true
  61838. });
  61839. /**
  61840. * Stop all async operations and release resources.
  61841. */
  61842. DracoCompression.prototype.dispose = function () {
  61843. };
  61844. /**
  61845. * Decode Draco compressed mesh data to vertex data.
  61846. * @param data The array buffer view for the Draco compression data
  61847. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61848. * @returns A promise that resolves with the decoded vertex data
  61849. */
  61850. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61851. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61852. var module = wrappedModule.module;
  61853. var vertexData = new BABYLON.VertexData();
  61854. var buffer = new module.DecoderBuffer();
  61855. buffer.Init(data, data.byteLength);
  61856. var decoder = new module.Decoder();
  61857. var geometry;
  61858. var status;
  61859. try {
  61860. var type = decoder.GetEncodedGeometryType(buffer);
  61861. switch (type) {
  61862. case module.TRIANGULAR_MESH:
  61863. geometry = new module.Mesh();
  61864. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61865. break;
  61866. case module.POINT_CLOUD:
  61867. geometry = new module.PointCloud();
  61868. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61869. break;
  61870. default:
  61871. throw new Error("Invalid geometry type " + type);
  61872. }
  61873. if (!status.ok() || !geometry.ptr) {
  61874. throw new Error(status.error_msg());
  61875. }
  61876. var numPoints = geometry.num_points();
  61877. if (type === module.TRIANGULAR_MESH) {
  61878. var numFaces = geometry.num_faces();
  61879. var faceIndices = new module.DracoInt32Array();
  61880. try {
  61881. var indices = new Uint32Array(numFaces * 3);
  61882. for (var i = 0; i < numFaces; i++) {
  61883. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61884. var offset = i * 3;
  61885. indices[offset + 0] = faceIndices.GetValue(0);
  61886. indices[offset + 1] = faceIndices.GetValue(1);
  61887. indices[offset + 2] = faceIndices.GetValue(2);
  61888. }
  61889. vertexData.indices = indices;
  61890. }
  61891. finally {
  61892. module.destroy(faceIndices);
  61893. }
  61894. }
  61895. for (var kind in attributes) {
  61896. var uniqueId = attributes[kind];
  61897. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61898. var dracoData = new module.DracoFloat32Array();
  61899. try {
  61900. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61901. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61902. for (var i = 0; i < babylonData.length; i++) {
  61903. babylonData[i] = dracoData.GetValue(i);
  61904. }
  61905. vertexData.set(babylonData, kind);
  61906. }
  61907. finally {
  61908. module.destroy(dracoData);
  61909. }
  61910. }
  61911. }
  61912. finally {
  61913. if (geometry) {
  61914. module.destroy(geometry);
  61915. }
  61916. module.destroy(decoder);
  61917. module.destroy(buffer);
  61918. }
  61919. return vertexData;
  61920. });
  61921. };
  61922. DracoCompression._GetDecoderModule = function () {
  61923. if (!DracoCompression._DecoderModulePromise) {
  61924. var promise = null;
  61925. var config_1 = {};
  61926. if (typeof DracoDecoderModule !== "undefined") {
  61927. promise = Promise.resolve();
  61928. }
  61929. else {
  61930. var decoder = DracoCompression.Configuration.decoder;
  61931. if (decoder) {
  61932. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61933. promise = Promise.all([
  61934. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61935. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61936. config_1.wasmBinary = data;
  61937. })
  61938. ]);
  61939. }
  61940. else if (decoder.fallbackUrl) {
  61941. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61942. }
  61943. }
  61944. }
  61945. if (!promise) {
  61946. throw new Error("Draco decoder module is not available");
  61947. }
  61948. DracoCompression._DecoderModulePromise = promise.then(function () {
  61949. return new Promise(function (resolve) {
  61950. config_1.onModuleLoaded = function (decoderModule) {
  61951. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61952. resolve({ module: decoderModule });
  61953. };
  61954. DracoDecoderModule(config_1);
  61955. });
  61956. });
  61957. }
  61958. return DracoCompression._DecoderModulePromise;
  61959. };
  61960. DracoCompression._LoadScriptAsync = function (url) {
  61961. return new Promise(function (resolve, reject) {
  61962. BABYLON.Tools.LoadScript(url, function () {
  61963. resolve();
  61964. }, function (message) {
  61965. reject(new Error(message));
  61966. });
  61967. });
  61968. };
  61969. DracoCompression._LoadFileAsync = function (url) {
  61970. return new Promise(function (resolve, reject) {
  61971. BABYLON.Tools.LoadFile(url, function (data) {
  61972. resolve(data);
  61973. }, undefined, undefined, true, function (request, exception) {
  61974. reject(exception);
  61975. });
  61976. });
  61977. };
  61978. /**
  61979. * The configuration.
  61980. */
  61981. DracoCompression.Configuration = {
  61982. decoder: {
  61983. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61984. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61985. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61986. }
  61987. };
  61988. return DracoCompression;
  61989. }());
  61990. BABYLON.DracoCompression = DracoCompression;
  61991. })(BABYLON || (BABYLON = {}));
  61992. //# sourceMappingURL=babylon.dracoCompression.js.map
  61993. var BABYLON;
  61994. (function (BABYLON) {
  61995. var AudioEngine = /** @class */ (function () {
  61996. function AudioEngine() {
  61997. this._audioContext = null;
  61998. this._audioContextInitialized = false;
  61999. this.canUseWebAudio = false;
  62000. this.WarnedWebAudioUnsupported = false;
  62001. this.unlocked = false;
  62002. this.isMP3supported = false;
  62003. this.isOGGsupported = false;
  62004. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62005. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62006. this.canUseWebAudio = true;
  62007. }
  62008. var audioElem = document.createElement('audio');
  62009. try {
  62010. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62011. this.isMP3supported = true;
  62012. }
  62013. }
  62014. catch (e) {
  62015. // protect error during capability check.
  62016. }
  62017. try {
  62018. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62019. this.isOGGsupported = true;
  62020. }
  62021. }
  62022. catch (e) {
  62023. // protect error during capability check.
  62024. }
  62025. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62026. this._unlockiOSaudio();
  62027. }
  62028. else {
  62029. this.unlocked = true;
  62030. }
  62031. }
  62032. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62033. get: function () {
  62034. if (!this._audioContextInitialized) {
  62035. this._initializeAudioContext();
  62036. }
  62037. return this._audioContext;
  62038. },
  62039. enumerable: true,
  62040. configurable: true
  62041. });
  62042. AudioEngine.prototype._unlockiOSaudio = function () {
  62043. var _this = this;
  62044. var unlockaudio = function () {
  62045. if (!_this.audioContext) {
  62046. return;
  62047. }
  62048. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62049. var source = _this.audioContext.createBufferSource();
  62050. source.buffer = buffer;
  62051. source.connect(_this.audioContext.destination);
  62052. source.start(0);
  62053. setTimeout(function () {
  62054. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62055. _this.unlocked = true;
  62056. window.removeEventListener('touchend', unlockaudio, false);
  62057. if (_this.onAudioUnlocked) {
  62058. _this.onAudioUnlocked();
  62059. }
  62060. }
  62061. }, 0);
  62062. };
  62063. window.addEventListener('touchend', unlockaudio, false);
  62064. };
  62065. AudioEngine.prototype._initializeAudioContext = function () {
  62066. try {
  62067. if (this.canUseWebAudio) {
  62068. this._audioContext = new AudioContext();
  62069. // create a global volume gain node
  62070. this.masterGain = this._audioContext.createGain();
  62071. this.masterGain.gain.value = 1;
  62072. this.masterGain.connect(this._audioContext.destination);
  62073. this._audioContextInitialized = true;
  62074. }
  62075. }
  62076. catch (e) {
  62077. this.canUseWebAudio = false;
  62078. BABYLON.Tools.Error("Web Audio: " + e.message);
  62079. }
  62080. };
  62081. AudioEngine.prototype.dispose = function () {
  62082. if (this.canUseWebAudio && this._audioContextInitialized) {
  62083. if (this._connectedAnalyser && this._audioContext) {
  62084. this._connectedAnalyser.stopDebugCanvas();
  62085. this._connectedAnalyser.dispose();
  62086. this.masterGain.disconnect();
  62087. this.masterGain.connect(this._audioContext.destination);
  62088. this._connectedAnalyser = null;
  62089. }
  62090. this.masterGain.gain.value = 1;
  62091. }
  62092. this.WarnedWebAudioUnsupported = false;
  62093. };
  62094. AudioEngine.prototype.getGlobalVolume = function () {
  62095. if (this.canUseWebAudio && this._audioContextInitialized) {
  62096. return this.masterGain.gain.value;
  62097. }
  62098. else {
  62099. return -1;
  62100. }
  62101. };
  62102. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62103. if (this.canUseWebAudio && this._audioContextInitialized) {
  62104. this.masterGain.gain.value = newVolume;
  62105. }
  62106. };
  62107. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62108. if (this._connectedAnalyser) {
  62109. this._connectedAnalyser.stopDebugCanvas();
  62110. }
  62111. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62112. this._connectedAnalyser = analyser;
  62113. this.masterGain.disconnect();
  62114. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62115. }
  62116. };
  62117. return AudioEngine;
  62118. }());
  62119. BABYLON.AudioEngine = AudioEngine;
  62120. })(BABYLON || (BABYLON = {}));
  62121. //# sourceMappingURL=babylon.audioEngine.js.map
  62122. var BABYLON;
  62123. (function (BABYLON) {
  62124. var Sound = /** @class */ (function () {
  62125. /**
  62126. * Create a sound and attach it to a scene
  62127. * @param name Name of your sound
  62128. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62129. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62130. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62131. */
  62132. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62133. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62134. var _this = this;
  62135. this.autoplay = false;
  62136. this.loop = false;
  62137. this.useCustomAttenuation = false;
  62138. this.spatialSound = false;
  62139. this.refDistance = 1;
  62140. this.rolloffFactor = 1;
  62141. this.maxDistance = 100;
  62142. this.distanceModel = "linear";
  62143. this._panningModel = "equalpower";
  62144. this._playbackRate = 1;
  62145. this._streaming = false;
  62146. this._startTime = 0;
  62147. this._startOffset = 0;
  62148. this._position = BABYLON.Vector3.Zero();
  62149. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62150. this._volume = 1;
  62151. this._isReadyToPlay = false;
  62152. this.isPlaying = false;
  62153. this.isPaused = false;
  62154. this._isDirectional = false;
  62155. // Used if you'd like to create a directional sound.
  62156. // If not set, the sound will be omnidirectional
  62157. this._coneInnerAngle = 360;
  62158. this._coneOuterAngle = 360;
  62159. this._coneOuterGain = 0;
  62160. this._isOutputConnected = false;
  62161. this._urlType = "Unknown";
  62162. this.name = name;
  62163. this._scene = scene;
  62164. this._readyToPlayCallback = readyToPlayCallback;
  62165. // Default custom attenuation function is a linear attenuation
  62166. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62167. if (currentDistance < maxDistance) {
  62168. return currentVolume * (1 - currentDistance / maxDistance);
  62169. }
  62170. else {
  62171. return 0;
  62172. }
  62173. };
  62174. if (options) {
  62175. this.autoplay = options.autoplay || false;
  62176. this.loop = options.loop || false;
  62177. // if volume === 0, we need another way to check this option
  62178. if (options.volume !== undefined) {
  62179. this._volume = options.volume;
  62180. }
  62181. this.spatialSound = options.spatialSound || false;
  62182. this.maxDistance = options.maxDistance || 100;
  62183. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62184. this.rolloffFactor = options.rolloffFactor || 1;
  62185. this.refDistance = options.refDistance || 1;
  62186. this.distanceModel = options.distanceModel || "linear";
  62187. this._playbackRate = options.playbackRate || 1;
  62188. this._streaming = options.streaming || false;
  62189. }
  62190. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62191. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62192. this._soundGain.gain.value = this._volume;
  62193. this._inputAudioNode = this._soundGain;
  62194. this._ouputAudioNode = this._soundGain;
  62195. if (this.spatialSound) {
  62196. this._createSpatialParameters();
  62197. }
  62198. this._scene.mainSoundTrack.AddSound(this);
  62199. var validParameter = true;
  62200. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62201. if (urlOrArrayBuffer) {
  62202. try {
  62203. if (typeof (urlOrArrayBuffer) === "string")
  62204. this._urlType = "String";
  62205. if (Array.isArray(urlOrArrayBuffer))
  62206. this._urlType = "Array";
  62207. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62208. this._urlType = "ArrayBuffer";
  62209. var urls = [];
  62210. var codecSupportedFound = false;
  62211. switch (this._urlType) {
  62212. case "ArrayBuffer":
  62213. if (urlOrArrayBuffer.byteLength > 0) {
  62214. codecSupportedFound = true;
  62215. this._soundLoaded(urlOrArrayBuffer);
  62216. }
  62217. break;
  62218. case "String":
  62219. urls.push(urlOrArrayBuffer);
  62220. case "Array":
  62221. if (urls.length === 0)
  62222. urls = urlOrArrayBuffer;
  62223. // If we found a supported format, we load it immediately and stop the loop
  62224. for (var i = 0; i < urls.length; i++) {
  62225. var url = urls[i];
  62226. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62227. codecSupportedFound = true;
  62228. }
  62229. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62230. codecSupportedFound = true;
  62231. }
  62232. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62233. codecSupportedFound = true;
  62234. }
  62235. if (url.indexOf("blob:") !== -1) {
  62236. codecSupportedFound = true;
  62237. }
  62238. if (codecSupportedFound) {
  62239. // Loading sound using XHR2
  62240. if (!this._streaming) {
  62241. this._scene._loadFile(url, function (data) {
  62242. _this._soundLoaded(data);
  62243. }, undefined, true, true, function (exception) {
  62244. if (exception) {
  62245. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62246. }
  62247. BABYLON.Tools.Error("Sound creation aborted.");
  62248. _this._scene.mainSoundTrack.RemoveSound(_this);
  62249. });
  62250. }
  62251. // Streaming sound using HTML5 Audio tag
  62252. else {
  62253. this._htmlAudioElement = new Audio(url);
  62254. this._htmlAudioElement.controls = false;
  62255. this._htmlAudioElement.loop = this.loop;
  62256. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62257. this._htmlAudioElement.preload = "auto";
  62258. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62259. _this._isReadyToPlay = true;
  62260. if (_this.autoplay) {
  62261. _this.play();
  62262. }
  62263. if (_this._readyToPlayCallback) {
  62264. _this._readyToPlayCallback();
  62265. }
  62266. });
  62267. document.body.appendChild(this._htmlAudioElement);
  62268. }
  62269. break;
  62270. }
  62271. }
  62272. break;
  62273. default:
  62274. validParameter = false;
  62275. break;
  62276. }
  62277. if (!validParameter) {
  62278. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62279. }
  62280. else {
  62281. if (!codecSupportedFound) {
  62282. this._isReadyToPlay = true;
  62283. // Simulating a ready to play event to avoid breaking code path
  62284. if (this._readyToPlayCallback) {
  62285. window.setTimeout(function () {
  62286. if (_this._readyToPlayCallback) {
  62287. _this._readyToPlayCallback();
  62288. }
  62289. }, 1000);
  62290. }
  62291. }
  62292. }
  62293. }
  62294. catch (ex) {
  62295. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62296. this._scene.mainSoundTrack.RemoveSound(this);
  62297. }
  62298. }
  62299. }
  62300. else {
  62301. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62302. this._scene.mainSoundTrack.AddSound(this);
  62303. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62304. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62305. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62306. }
  62307. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62308. if (this._readyToPlayCallback) {
  62309. window.setTimeout(function () {
  62310. if (_this._readyToPlayCallback) {
  62311. _this._readyToPlayCallback();
  62312. }
  62313. }, 1000);
  62314. }
  62315. }
  62316. }
  62317. Sound.prototype.dispose = function () {
  62318. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62319. if (this.isPlaying) {
  62320. this.stop();
  62321. }
  62322. this._isReadyToPlay = false;
  62323. if (this.soundTrackId === -1) {
  62324. this._scene.mainSoundTrack.RemoveSound(this);
  62325. }
  62326. else {
  62327. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62328. }
  62329. if (this._soundGain) {
  62330. this._soundGain.disconnect();
  62331. this._soundGain = null;
  62332. }
  62333. if (this._soundPanner) {
  62334. this._soundPanner.disconnect();
  62335. this._soundPanner = null;
  62336. }
  62337. if (this._soundSource) {
  62338. this._soundSource.disconnect();
  62339. this._soundSource = null;
  62340. }
  62341. this._audioBuffer = null;
  62342. if (this._htmlAudioElement) {
  62343. this._htmlAudioElement.pause();
  62344. this._htmlAudioElement.src = "";
  62345. document.body.removeChild(this._htmlAudioElement);
  62346. }
  62347. if (this._connectedMesh && this._registerFunc) {
  62348. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62349. this._connectedMesh = null;
  62350. }
  62351. }
  62352. };
  62353. Sound.prototype.isReady = function () {
  62354. return this._isReadyToPlay;
  62355. };
  62356. Sound.prototype._soundLoaded = function (audioData) {
  62357. var _this = this;
  62358. if (!BABYLON.Engine.audioEngine.audioContext) {
  62359. return;
  62360. }
  62361. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62362. _this._audioBuffer = buffer;
  62363. _this._isReadyToPlay = true;
  62364. if (_this.autoplay) {
  62365. _this.play();
  62366. }
  62367. if (_this._readyToPlayCallback) {
  62368. _this._readyToPlayCallback();
  62369. }
  62370. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62371. };
  62372. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62373. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62374. this._audioBuffer = audioBuffer;
  62375. this._isReadyToPlay = true;
  62376. }
  62377. };
  62378. Sound.prototype.updateOptions = function (options) {
  62379. if (options) {
  62380. this.loop = options.loop || this.loop;
  62381. this.maxDistance = options.maxDistance || this.maxDistance;
  62382. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62383. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62384. this.refDistance = options.refDistance || this.refDistance;
  62385. this.distanceModel = options.distanceModel || this.distanceModel;
  62386. this._playbackRate = options.playbackRate || this._playbackRate;
  62387. this._updateSpatialParameters();
  62388. if (this.isPlaying) {
  62389. if (this._streaming) {
  62390. this._htmlAudioElement.playbackRate = this._playbackRate;
  62391. }
  62392. else {
  62393. if (this._soundSource) {
  62394. this._soundSource.playbackRate.value = this._playbackRate;
  62395. }
  62396. }
  62397. }
  62398. }
  62399. };
  62400. Sound.prototype._createSpatialParameters = function () {
  62401. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62402. if (this._scene.headphone) {
  62403. this._panningModel = "HRTF";
  62404. }
  62405. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62406. this._updateSpatialParameters();
  62407. this._soundPanner.connect(this._ouputAudioNode);
  62408. this._inputAudioNode = this._soundPanner;
  62409. }
  62410. };
  62411. Sound.prototype._updateSpatialParameters = function () {
  62412. if (this.spatialSound && this._soundPanner) {
  62413. if (this.useCustomAttenuation) {
  62414. // Tricks to disable in a way embedded Web Audio attenuation
  62415. this._soundPanner.distanceModel = "linear";
  62416. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62417. this._soundPanner.refDistance = 1;
  62418. this._soundPanner.rolloffFactor = 1;
  62419. this._soundPanner.panningModel = this._panningModel;
  62420. }
  62421. else {
  62422. this._soundPanner.distanceModel = this.distanceModel;
  62423. this._soundPanner.maxDistance = this.maxDistance;
  62424. this._soundPanner.refDistance = this.refDistance;
  62425. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62426. this._soundPanner.panningModel = this._panningModel;
  62427. }
  62428. }
  62429. };
  62430. Sound.prototype.switchPanningModelToHRTF = function () {
  62431. this._panningModel = "HRTF";
  62432. this._switchPanningModel();
  62433. };
  62434. Sound.prototype.switchPanningModelToEqualPower = function () {
  62435. this._panningModel = "equalpower";
  62436. this._switchPanningModel();
  62437. };
  62438. Sound.prototype._switchPanningModel = function () {
  62439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62440. this._soundPanner.panningModel = this._panningModel;
  62441. }
  62442. };
  62443. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62444. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62445. if (this._isOutputConnected) {
  62446. this._ouputAudioNode.disconnect();
  62447. }
  62448. this._ouputAudioNode.connect(soundTrackAudioNode);
  62449. this._isOutputConnected = true;
  62450. }
  62451. };
  62452. /**
  62453. * Transform this sound into a directional source
  62454. * @param coneInnerAngle Size of the inner cone in degree
  62455. * @param coneOuterAngle Size of the outer cone in degree
  62456. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62457. */
  62458. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62459. if (coneOuterAngle < coneInnerAngle) {
  62460. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62461. return;
  62462. }
  62463. this._coneInnerAngle = coneInnerAngle;
  62464. this._coneOuterAngle = coneOuterAngle;
  62465. this._coneOuterGain = coneOuterGain;
  62466. this._isDirectional = true;
  62467. if (this.isPlaying && this.loop) {
  62468. this.stop();
  62469. this.play();
  62470. }
  62471. };
  62472. Sound.prototype.setPosition = function (newPosition) {
  62473. this._position = newPosition;
  62474. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62475. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62476. }
  62477. };
  62478. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62479. this._localDirection = newLocalDirection;
  62480. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62481. this._updateDirection();
  62482. }
  62483. };
  62484. Sound.prototype._updateDirection = function () {
  62485. if (!this._connectedMesh || !this._soundPanner) {
  62486. return;
  62487. }
  62488. var mat = this._connectedMesh.getWorldMatrix();
  62489. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62490. direction.normalize();
  62491. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62492. };
  62493. Sound.prototype.updateDistanceFromListener = function () {
  62494. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62495. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62496. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62497. }
  62498. };
  62499. Sound.prototype.setAttenuationFunction = function (callback) {
  62500. this._customAttenuationFunction = callback;
  62501. };
  62502. /**
  62503. * Play the sound
  62504. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62505. * @param offset (optional) Start the sound setting it at a specific time
  62506. */
  62507. Sound.prototype.play = function (time, offset) {
  62508. var _this = this;
  62509. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62510. try {
  62511. if (this._startOffset < 0) {
  62512. time = -this._startOffset;
  62513. this._startOffset = 0;
  62514. }
  62515. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62516. if (!this._soundSource || !this._streamingSource) {
  62517. if (this.spatialSound && this._soundPanner) {
  62518. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62519. if (this._isDirectional) {
  62520. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62521. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62522. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62523. if (this._connectedMesh) {
  62524. this._updateDirection();
  62525. }
  62526. else {
  62527. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62528. }
  62529. }
  62530. }
  62531. }
  62532. if (this._streaming) {
  62533. if (!this._streamingSource) {
  62534. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62535. this._htmlAudioElement.onended = function () { _this._onended(); };
  62536. this._htmlAudioElement.playbackRate = this._playbackRate;
  62537. }
  62538. this._streamingSource.disconnect();
  62539. this._streamingSource.connect(this._inputAudioNode);
  62540. this._htmlAudioElement.play();
  62541. }
  62542. else {
  62543. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62544. this._soundSource.buffer = this._audioBuffer;
  62545. this._soundSource.connect(this._inputAudioNode);
  62546. this._soundSource.loop = this.loop;
  62547. this._soundSource.playbackRate.value = this._playbackRate;
  62548. this._soundSource.onended = function () { _this._onended(); };
  62549. if (this._soundSource.buffer) {
  62550. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62551. }
  62552. }
  62553. this._startTime = startTime;
  62554. this.isPlaying = true;
  62555. this.isPaused = false;
  62556. }
  62557. catch (ex) {
  62558. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62559. }
  62560. }
  62561. };
  62562. Sound.prototype._onended = function () {
  62563. this.isPlaying = false;
  62564. if (this.onended) {
  62565. this.onended();
  62566. }
  62567. };
  62568. /**
  62569. * Stop the sound
  62570. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62571. */
  62572. Sound.prototype.stop = function (time) {
  62573. if (this.isPlaying) {
  62574. if (this._streaming) {
  62575. this._htmlAudioElement.pause();
  62576. // Test needed for Firefox or it will generate an Invalid State Error
  62577. if (this._htmlAudioElement.currentTime > 0) {
  62578. this._htmlAudioElement.currentTime = 0;
  62579. }
  62580. }
  62581. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62582. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62583. this._soundSource.stop(stopTime);
  62584. this._soundSource.onended = function () { };
  62585. if (!this.isPaused) {
  62586. this._startOffset = 0;
  62587. }
  62588. }
  62589. this.isPlaying = false;
  62590. }
  62591. };
  62592. Sound.prototype.pause = function () {
  62593. if (this.isPlaying) {
  62594. this.isPaused = true;
  62595. if (this._streaming) {
  62596. this._htmlAudioElement.pause();
  62597. }
  62598. else if (BABYLON.Engine.audioEngine.audioContext) {
  62599. this.stop(0);
  62600. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62601. }
  62602. }
  62603. };
  62604. Sound.prototype.setVolume = function (newVolume, time) {
  62605. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62606. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62607. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62608. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62609. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62610. }
  62611. else {
  62612. this._soundGain.gain.value = newVolume;
  62613. }
  62614. }
  62615. this._volume = newVolume;
  62616. };
  62617. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62618. this._playbackRate = newPlaybackRate;
  62619. if (this.isPlaying) {
  62620. if (this._streaming) {
  62621. this._htmlAudioElement.playbackRate = this._playbackRate;
  62622. }
  62623. else if (this._soundSource) {
  62624. this._soundSource.playbackRate.value = this._playbackRate;
  62625. }
  62626. }
  62627. };
  62628. Sound.prototype.getVolume = function () {
  62629. return this._volume;
  62630. };
  62631. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62632. var _this = this;
  62633. if (this._connectedMesh && this._registerFunc) {
  62634. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62635. this._registerFunc = null;
  62636. }
  62637. this._connectedMesh = meshToConnectTo;
  62638. if (!this.spatialSound) {
  62639. this.spatialSound = true;
  62640. this._createSpatialParameters();
  62641. if (this.isPlaying && this.loop) {
  62642. this.stop();
  62643. this.play();
  62644. }
  62645. }
  62646. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62647. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62648. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62649. };
  62650. Sound.prototype.detachFromMesh = function () {
  62651. if (this._connectedMesh && this._registerFunc) {
  62652. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62653. this._registerFunc = null;
  62654. this._connectedMesh = null;
  62655. }
  62656. };
  62657. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62658. if (!node.getBoundingInfo) {
  62659. return;
  62660. }
  62661. var mesh = node;
  62662. var boundingInfo = mesh.getBoundingInfo();
  62663. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62665. this._updateDirection();
  62666. }
  62667. };
  62668. Sound.prototype.clone = function () {
  62669. var _this = this;
  62670. if (!this._streaming) {
  62671. var setBufferAndRun = function () {
  62672. if (_this._isReadyToPlay) {
  62673. clonedSound._audioBuffer = _this.getAudioBuffer();
  62674. clonedSound._isReadyToPlay = true;
  62675. if (clonedSound.autoplay) {
  62676. clonedSound.play();
  62677. }
  62678. }
  62679. else {
  62680. window.setTimeout(setBufferAndRun, 300);
  62681. }
  62682. };
  62683. var currentOptions = {
  62684. autoplay: this.autoplay, loop: this.loop,
  62685. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62686. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62687. refDistance: this.refDistance, distanceModel: this.distanceModel
  62688. };
  62689. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62690. if (this.useCustomAttenuation) {
  62691. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62692. }
  62693. clonedSound.setPosition(this._position);
  62694. clonedSound.setPlaybackRate(this._playbackRate);
  62695. setBufferAndRun();
  62696. return clonedSound;
  62697. }
  62698. // Can't clone a streaming sound
  62699. else {
  62700. return null;
  62701. }
  62702. };
  62703. Sound.prototype.getAudioBuffer = function () {
  62704. return this._audioBuffer;
  62705. };
  62706. Sound.prototype.serialize = function () {
  62707. var serializationObject = {
  62708. name: this.name,
  62709. url: this.name,
  62710. autoplay: this.autoplay,
  62711. loop: this.loop,
  62712. volume: this._volume,
  62713. spatialSound: this.spatialSound,
  62714. maxDistance: this.maxDistance,
  62715. rolloffFactor: this.rolloffFactor,
  62716. refDistance: this.refDistance,
  62717. distanceModel: this.distanceModel,
  62718. playbackRate: this._playbackRate,
  62719. panningModel: this._panningModel,
  62720. soundTrackId: this.soundTrackId
  62721. };
  62722. if (this.spatialSound) {
  62723. if (this._connectedMesh)
  62724. serializationObject.connectedMeshId = this._connectedMesh.id;
  62725. serializationObject.position = this._position.asArray();
  62726. serializationObject.refDistance = this.refDistance;
  62727. serializationObject.distanceModel = this.distanceModel;
  62728. serializationObject.isDirectional = this._isDirectional;
  62729. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62730. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62731. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62732. serializationObject.coneOuterGain = this._coneOuterGain;
  62733. }
  62734. return serializationObject;
  62735. };
  62736. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62737. var soundName = parsedSound.name;
  62738. var soundUrl;
  62739. if (parsedSound.url) {
  62740. soundUrl = rootUrl + parsedSound.url;
  62741. }
  62742. else {
  62743. soundUrl = rootUrl + soundName;
  62744. }
  62745. var options = {
  62746. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62747. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62748. rolloffFactor: parsedSound.rolloffFactor,
  62749. refDistance: parsedSound.refDistance,
  62750. distanceModel: parsedSound.distanceModel,
  62751. playbackRate: parsedSound.playbackRate
  62752. };
  62753. var newSound;
  62754. if (!sourceSound) {
  62755. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62756. scene._addPendingData(newSound);
  62757. }
  62758. else {
  62759. var setBufferAndRun = function () {
  62760. if (sourceSound._isReadyToPlay) {
  62761. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62762. newSound._isReadyToPlay = true;
  62763. if (newSound.autoplay) {
  62764. newSound.play();
  62765. }
  62766. }
  62767. else {
  62768. window.setTimeout(setBufferAndRun, 300);
  62769. }
  62770. };
  62771. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62772. setBufferAndRun();
  62773. }
  62774. if (parsedSound.position) {
  62775. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62776. newSound.setPosition(soundPosition);
  62777. }
  62778. if (parsedSound.isDirectional) {
  62779. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62780. if (parsedSound.localDirectionToMesh) {
  62781. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62782. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62783. }
  62784. }
  62785. if (parsedSound.connectedMeshId) {
  62786. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62787. if (connectedMesh) {
  62788. newSound.attachToMesh(connectedMesh);
  62789. }
  62790. }
  62791. return newSound;
  62792. };
  62793. return Sound;
  62794. }());
  62795. BABYLON.Sound = Sound;
  62796. })(BABYLON || (BABYLON = {}));
  62797. //# sourceMappingURL=babylon.sound.js.map
  62798. var BABYLON;
  62799. (function (BABYLON) {
  62800. var SoundTrack = /** @class */ (function () {
  62801. function SoundTrack(scene, options) {
  62802. this.id = -1;
  62803. this._isMainTrack = false;
  62804. this._isInitialized = false;
  62805. this._scene = scene;
  62806. this.soundCollection = new Array();
  62807. this._options = options;
  62808. if (!this._isMainTrack) {
  62809. this._scene.soundTracks.push(this);
  62810. this.id = this._scene.soundTracks.length - 1;
  62811. }
  62812. }
  62813. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62814. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62815. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62816. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62817. if (this._options) {
  62818. if (this._options.volume) {
  62819. this._outputAudioNode.gain.value = this._options.volume;
  62820. }
  62821. if (this._options.mainTrack) {
  62822. this._isMainTrack = this._options.mainTrack;
  62823. }
  62824. }
  62825. this._isInitialized = true;
  62826. }
  62827. };
  62828. SoundTrack.prototype.dispose = function () {
  62829. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62830. if (this._connectedAnalyser) {
  62831. this._connectedAnalyser.stopDebugCanvas();
  62832. }
  62833. while (this.soundCollection.length) {
  62834. this.soundCollection[0].dispose();
  62835. }
  62836. if (this._outputAudioNode) {
  62837. this._outputAudioNode.disconnect();
  62838. }
  62839. this._outputAudioNode = null;
  62840. }
  62841. };
  62842. SoundTrack.prototype.AddSound = function (sound) {
  62843. if (!this._isInitialized) {
  62844. this._initializeSoundTrackAudioGraph();
  62845. }
  62846. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62847. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62848. }
  62849. if (sound.soundTrackId) {
  62850. if (sound.soundTrackId === -1) {
  62851. this._scene.mainSoundTrack.RemoveSound(sound);
  62852. }
  62853. else {
  62854. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62855. }
  62856. }
  62857. this.soundCollection.push(sound);
  62858. sound.soundTrackId = this.id;
  62859. };
  62860. SoundTrack.prototype.RemoveSound = function (sound) {
  62861. var index = this.soundCollection.indexOf(sound);
  62862. if (index !== -1) {
  62863. this.soundCollection.splice(index, 1);
  62864. }
  62865. };
  62866. SoundTrack.prototype.setVolume = function (newVolume) {
  62867. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62868. this._outputAudioNode.gain.value = newVolume;
  62869. }
  62870. };
  62871. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62872. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62873. for (var i = 0; i < this.soundCollection.length; i++) {
  62874. this.soundCollection[i].switchPanningModelToHRTF();
  62875. }
  62876. }
  62877. };
  62878. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62879. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62880. for (var i = 0; i < this.soundCollection.length; i++) {
  62881. this.soundCollection[i].switchPanningModelToEqualPower();
  62882. }
  62883. }
  62884. };
  62885. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62886. if (this._connectedAnalyser) {
  62887. this._connectedAnalyser.stopDebugCanvas();
  62888. }
  62889. this._connectedAnalyser = analyser;
  62890. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62891. this._outputAudioNode.disconnect();
  62892. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62893. }
  62894. };
  62895. return SoundTrack;
  62896. }());
  62897. BABYLON.SoundTrack = SoundTrack;
  62898. })(BABYLON || (BABYLON = {}));
  62899. //# sourceMappingURL=babylon.soundtrack.js.map
  62900. var BABYLON;
  62901. (function (BABYLON) {
  62902. /**
  62903. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62904. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62905. */
  62906. var Analyser = /** @class */ (function () {
  62907. /**
  62908. * Creates a new analyser
  62909. * @param scene defines hosting scene
  62910. */
  62911. function Analyser(scene) {
  62912. /**
  62913. * Gets or sets the smoothing
  62914. * @ignorenaming
  62915. */
  62916. this.SMOOTHING = 0.75;
  62917. /**
  62918. * Gets or sets the FFT table size
  62919. * @ignorenaming
  62920. */
  62921. this.FFT_SIZE = 512;
  62922. /**
  62923. * Gets or sets the bar graph amplitude
  62924. * @ignorenaming
  62925. */
  62926. this.BARGRAPHAMPLITUDE = 256;
  62927. /**
  62928. * Gets or sets the position of the debug canvas
  62929. * @ignorenaming
  62930. */
  62931. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62932. /**
  62933. * Gets or sets the debug canvas size
  62934. * @ignorenaming
  62935. */
  62936. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62937. this._scene = scene;
  62938. this._audioEngine = BABYLON.Engine.audioEngine;
  62939. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62940. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62941. this._webAudioAnalyser.minDecibels = -140;
  62942. this._webAudioAnalyser.maxDecibels = 0;
  62943. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62944. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62945. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62946. }
  62947. }
  62948. /**
  62949. * Get the number of data values you will have to play with for the visualization
  62950. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62951. * @returns a number
  62952. */
  62953. Analyser.prototype.getFrequencyBinCount = function () {
  62954. if (this._audioEngine.canUseWebAudio) {
  62955. return this._webAudioAnalyser.frequencyBinCount;
  62956. }
  62957. else {
  62958. return 0;
  62959. }
  62960. };
  62961. /**
  62962. * Gets the current frequency data as a byte array
  62963. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62964. * @returns a Uint8Array
  62965. */
  62966. Analyser.prototype.getByteFrequencyData = function () {
  62967. if (this._audioEngine.canUseWebAudio) {
  62968. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62969. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62970. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62971. }
  62972. return this._byteFreqs;
  62973. };
  62974. /**
  62975. * Gets the current waveform as a byte array
  62976. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62977. * @returns a Uint8Array
  62978. */
  62979. Analyser.prototype.getByteTimeDomainData = function () {
  62980. if (this._audioEngine.canUseWebAudio) {
  62981. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62982. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62983. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62984. }
  62985. return this._byteTime;
  62986. };
  62987. /**
  62988. * Gets the current frequency data as a float array
  62989. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62990. * @returns a Float32Array
  62991. */
  62992. Analyser.prototype.getFloatFrequencyData = function () {
  62993. if (this._audioEngine.canUseWebAudio) {
  62994. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62995. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62996. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62997. }
  62998. return this._floatFreqs;
  62999. };
  63000. /**
  63001. * Renders the debug canvas
  63002. */
  63003. Analyser.prototype.drawDebugCanvas = function () {
  63004. var _this = this;
  63005. if (this._audioEngine.canUseWebAudio) {
  63006. if (!this._debugCanvas) {
  63007. this._debugCanvas = document.createElement("canvas");
  63008. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63009. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63010. this._debugCanvas.style.position = "absolute";
  63011. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63012. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63013. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63014. document.body.appendChild(this._debugCanvas);
  63015. this._registerFunc = function () {
  63016. _this.drawDebugCanvas();
  63017. };
  63018. this._scene.registerBeforeRender(this._registerFunc);
  63019. }
  63020. if (this._registerFunc && this._debugCanvasContext) {
  63021. var workingArray = this.getByteFrequencyData();
  63022. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63023. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63024. // Draw the frequency domain chart.
  63025. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63026. var value = workingArray[i];
  63027. var percent = value / this.BARGRAPHAMPLITUDE;
  63028. var height = this.DEBUGCANVASSIZE.height * percent;
  63029. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63030. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63031. var hue = i / this.getFrequencyBinCount() * 360;
  63032. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63033. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63034. }
  63035. }
  63036. }
  63037. };
  63038. /**
  63039. * Stops rendering the debug canvas and removes it
  63040. */
  63041. Analyser.prototype.stopDebugCanvas = function () {
  63042. if (this._debugCanvas) {
  63043. if (this._registerFunc) {
  63044. this._scene.unregisterBeforeRender(this._registerFunc);
  63045. this._registerFunc = null;
  63046. }
  63047. document.body.removeChild(this._debugCanvas);
  63048. this._debugCanvas = null;
  63049. this._debugCanvasContext = null;
  63050. }
  63051. };
  63052. /**
  63053. * Connects two audio nodes
  63054. * @param inputAudioNode defines first node to connect
  63055. * @param outputAudioNode defines second node to connect
  63056. */
  63057. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63058. if (this._audioEngine.canUseWebAudio) {
  63059. inputAudioNode.connect(this._webAudioAnalyser);
  63060. this._webAudioAnalyser.connect(outputAudioNode);
  63061. }
  63062. };
  63063. /**
  63064. * Releases all associated resources
  63065. */
  63066. Analyser.prototype.dispose = function () {
  63067. if (this._audioEngine.canUseWebAudio) {
  63068. this._webAudioAnalyser.disconnect();
  63069. }
  63070. };
  63071. return Analyser;
  63072. }());
  63073. BABYLON.Analyser = Analyser;
  63074. })(BABYLON || (BABYLON = {}));
  63075. //# sourceMappingURL=babylon.analyser.js.map
  63076. var BABYLON;
  63077. (function (BABYLON) {
  63078. var CubeTexture = /** @class */ (function (_super) {
  63079. __extends(CubeTexture, _super);
  63080. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63081. if (extensions === void 0) { extensions = null; }
  63082. if (noMipmap === void 0) { noMipmap = false; }
  63083. if (files === void 0) { files = null; }
  63084. if (onLoad === void 0) { onLoad = null; }
  63085. if (onError === void 0) { onError = null; }
  63086. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63087. if (prefiltered === void 0) { prefiltered = false; }
  63088. if (forcedExtension === void 0) { forcedExtension = null; }
  63089. var _this = _super.call(this, scene) || this;
  63090. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63091. /**
  63092. * Gets or sets the center of the bounding box associated with the cube texture
  63093. * It must define where the camera used to render the texture was set
  63094. */
  63095. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63096. _this._rotationY = 0;
  63097. _this.name = rootUrl;
  63098. _this.url = rootUrl;
  63099. _this._noMipmap = noMipmap;
  63100. _this.hasAlpha = false;
  63101. _this._format = format;
  63102. _this._prefiltered = prefiltered;
  63103. _this.isCube = true;
  63104. _this._textureMatrix = BABYLON.Matrix.Identity();
  63105. if (prefiltered) {
  63106. _this.gammaSpace = false;
  63107. }
  63108. if (!rootUrl && !files) {
  63109. return _this;
  63110. }
  63111. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63112. var lastDot = rootUrl.lastIndexOf(".");
  63113. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63114. var isDDS = (extension === ".dds");
  63115. if (!files) {
  63116. if (!isDDS && !extensions) {
  63117. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63118. }
  63119. files = [];
  63120. if (extensions) {
  63121. for (var index = 0; index < extensions.length; index++) {
  63122. files.push(rootUrl + extensions[index]);
  63123. }
  63124. }
  63125. }
  63126. _this._files = files;
  63127. if (!_this._texture) {
  63128. if (!scene.useDelayedTextureLoading) {
  63129. if (prefiltered) {
  63130. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63131. }
  63132. else {
  63133. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63134. }
  63135. }
  63136. else {
  63137. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63138. }
  63139. }
  63140. else if (onLoad) {
  63141. if (_this._texture.isReady) {
  63142. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63143. }
  63144. else {
  63145. _this._texture.onLoadedObservable.add(onLoad);
  63146. }
  63147. }
  63148. return _this;
  63149. }
  63150. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63151. get: function () {
  63152. return this._boundingBoxSize;
  63153. },
  63154. /**
  63155. * Gets or sets the size of the bounding box associated with the cube texture
  63156. * When defined, the cubemap will switch to local mode
  63157. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63158. * @example https://www.babylonjs-playground.com/#RNASML
  63159. */
  63160. set: function (value) {
  63161. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63162. return;
  63163. }
  63164. this._boundingBoxSize = value;
  63165. var scene = this.getScene();
  63166. if (scene) {
  63167. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63168. }
  63169. },
  63170. enumerable: true,
  63171. configurable: true
  63172. });
  63173. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63174. /**
  63175. * Gets texture matrix rotation angle around Y axis radians.
  63176. */
  63177. get: function () {
  63178. return this._rotationY;
  63179. },
  63180. /**
  63181. * Sets texture matrix rotation angle around Y axis in radians.
  63182. */
  63183. set: function (value) {
  63184. this._rotationY = value;
  63185. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63191. var rootUrlKey = "";
  63192. files.forEach(function (url) { return rootUrlKey += url; });
  63193. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63194. };
  63195. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63196. if (forcedExtension === void 0) { forcedExtension = null; }
  63197. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63198. };
  63199. // Methods
  63200. CubeTexture.prototype.delayLoad = function () {
  63201. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63202. return;
  63203. }
  63204. var scene = this.getScene();
  63205. if (!scene) {
  63206. return;
  63207. }
  63208. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63209. this._texture = this._getFromCache(this.url, this._noMipmap);
  63210. if (!this._texture) {
  63211. if (this._prefiltered) {
  63212. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63213. }
  63214. else {
  63215. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63216. }
  63217. }
  63218. };
  63219. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63220. return this._textureMatrix;
  63221. };
  63222. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63223. this._textureMatrix = value;
  63224. };
  63225. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63226. var texture = BABYLON.SerializationHelper.Parse(function () {
  63227. var prefiltered = false;
  63228. if (parsedTexture.prefiltered) {
  63229. prefiltered = parsedTexture.prefiltered;
  63230. }
  63231. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63232. }, parsedTexture, scene);
  63233. // Local Cubemaps
  63234. if (parsedTexture.boundingBoxPosition) {
  63235. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63236. }
  63237. if (parsedTexture.boundingBoxSize) {
  63238. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63239. }
  63240. // Animations
  63241. if (parsedTexture.animations) {
  63242. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63243. var parsedAnimation = parsedTexture.animations[animationIndex];
  63244. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63245. }
  63246. }
  63247. return texture;
  63248. };
  63249. CubeTexture.prototype.clone = function () {
  63250. var _this = this;
  63251. return BABYLON.SerializationHelper.Clone(function () {
  63252. var scene = _this.getScene();
  63253. if (!scene) {
  63254. return _this;
  63255. }
  63256. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63257. }, this);
  63258. };
  63259. __decorate([
  63260. BABYLON.serialize("rotationY")
  63261. ], CubeTexture.prototype, "_rotationY", void 0);
  63262. return CubeTexture;
  63263. }(BABYLON.BaseTexture));
  63264. BABYLON.CubeTexture = CubeTexture;
  63265. })(BABYLON || (BABYLON = {}));
  63266. //# sourceMappingURL=babylon.cubeTexture.js.map
  63267. var BABYLON;
  63268. (function (BABYLON) {
  63269. var RenderTargetTexture = /** @class */ (function (_super) {
  63270. __extends(RenderTargetTexture, _super);
  63271. /**
  63272. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63273. * or used a shadow, depth texture...
  63274. * @param name The friendly name of the texture
  63275. * @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)
  63276. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63277. * @param generateMipMaps True if mip maps need to be generated after render.
  63278. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63279. * @param type The type of the buffer in the RTT (int, half float, float...)
  63280. * @param isCube True if a cube texture needs to be created
  63281. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63282. * @param generateDepthBuffer True to generate a depth buffer
  63283. * @param generateStencilBuffer True to generate a stencil buffer
  63284. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63285. */
  63286. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63287. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63288. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63289. if (isCube === void 0) { isCube = false; }
  63290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63291. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63292. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63293. if (isMulti === void 0) { isMulti = false; }
  63294. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63295. _this.isCube = isCube;
  63296. /**
  63297. * Use this list to define the list of mesh you want to render.
  63298. */
  63299. _this.renderList = new Array();
  63300. _this.renderParticles = true;
  63301. _this.renderSprites = false;
  63302. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63303. _this.ignoreCameraViewport = false;
  63304. // Events
  63305. /**
  63306. * An event triggered when the texture is unbind.
  63307. */
  63308. _this.onBeforeBindObservable = new BABYLON.Observable();
  63309. /**
  63310. * An event triggered when the texture is unbind.
  63311. */
  63312. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63313. /**
  63314. * An event triggered before rendering the texture
  63315. */
  63316. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63317. /**
  63318. * An event triggered after rendering the texture
  63319. */
  63320. _this.onAfterRenderObservable = new BABYLON.Observable();
  63321. /**
  63322. * An event triggered after the texture clear
  63323. */
  63324. _this.onClearObservable = new BABYLON.Observable();
  63325. _this._currentRefreshId = -1;
  63326. _this._refreshRate = 1;
  63327. _this._samples = 1;
  63328. /**
  63329. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63330. * It must define where the camera used to render the texture is set
  63331. */
  63332. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63333. scene = _this.getScene();
  63334. if (!scene) {
  63335. return _this;
  63336. }
  63337. _this._engine = scene.getEngine();
  63338. _this.name = name;
  63339. _this.isRenderTarget = true;
  63340. _this._initialSizeParameter = size;
  63341. _this._processSizeParameter(size);
  63342. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63343. });
  63344. _this._generateMipMaps = generateMipMaps ? true : false;
  63345. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63346. // Rendering groups
  63347. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63348. if (isMulti) {
  63349. return _this;
  63350. }
  63351. _this._renderTargetOptions = {
  63352. generateMipMaps: generateMipMaps,
  63353. type: type,
  63354. samplingMode: samplingMode,
  63355. generateDepthBuffer: generateDepthBuffer,
  63356. generateStencilBuffer: generateStencilBuffer
  63357. };
  63358. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63359. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63360. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63361. }
  63362. if (isCube) {
  63363. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63364. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63365. _this._textureMatrix = BABYLON.Matrix.Identity();
  63366. }
  63367. else {
  63368. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63369. }
  63370. return _this;
  63371. }
  63372. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63373. get: function () {
  63374. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63375. },
  63376. enumerable: true,
  63377. configurable: true
  63378. });
  63379. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63380. get: function () {
  63381. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63382. },
  63383. enumerable: true,
  63384. configurable: true
  63385. });
  63386. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63387. get: function () {
  63388. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63389. },
  63390. enumerable: true,
  63391. configurable: true
  63392. });
  63393. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63394. set: function (callback) {
  63395. if (this._onAfterUnbindObserver) {
  63396. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63397. }
  63398. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63399. },
  63400. enumerable: true,
  63401. configurable: true
  63402. });
  63403. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63404. set: function (callback) {
  63405. if (this._onBeforeRenderObserver) {
  63406. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63407. }
  63408. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63409. },
  63410. enumerable: true,
  63411. configurable: true
  63412. });
  63413. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63414. set: function (callback) {
  63415. if (this._onAfterRenderObserver) {
  63416. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63417. }
  63418. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63419. },
  63420. enumerable: true,
  63421. configurable: true
  63422. });
  63423. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63424. set: function (callback) {
  63425. if (this._onClearObserver) {
  63426. this.onClearObservable.remove(this._onClearObserver);
  63427. }
  63428. this._onClearObserver = this.onClearObservable.add(callback);
  63429. },
  63430. enumerable: true,
  63431. configurable: true
  63432. });
  63433. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63434. get: function () {
  63435. return this._renderTargetOptions;
  63436. },
  63437. enumerable: true,
  63438. configurable: true
  63439. });
  63440. RenderTargetTexture.prototype._onRatioRescale = function () {
  63441. if (this._sizeRatio) {
  63442. this.resize(this._initialSizeParameter);
  63443. }
  63444. };
  63445. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63446. get: function () {
  63447. return this._boundingBoxSize;
  63448. },
  63449. /**
  63450. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63451. * When defined, the cubemap will switch to local mode
  63452. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63453. * @example https://www.babylonjs-playground.com/#RNASML
  63454. */
  63455. set: function (value) {
  63456. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63457. return;
  63458. }
  63459. this._boundingBoxSize = value;
  63460. var scene = this.getScene();
  63461. if (scene) {
  63462. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63463. }
  63464. },
  63465. enumerable: true,
  63466. configurable: true
  63467. });
  63468. /**
  63469. * Creates a depth stencil texture.
  63470. * This is only available in WebGL 2 or with the depth texture extension available.
  63471. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63472. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63473. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63474. */
  63475. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63476. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63477. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63478. if (generateStencil === void 0) { generateStencil = false; }
  63479. if (!this.getScene()) {
  63480. return;
  63481. }
  63482. var engine = this.getScene().getEngine();
  63483. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63484. bilinearFiltering: bilinearFiltering,
  63485. comparisonFunction: comparisonFunction,
  63486. generateStencil: generateStencil,
  63487. isCube: this.isCube
  63488. });
  63489. engine.setFrameBufferDepthStencilTexture(this);
  63490. };
  63491. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63492. if (size.ratio) {
  63493. this._sizeRatio = size.ratio;
  63494. this._size = {
  63495. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63496. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63497. };
  63498. }
  63499. else {
  63500. this._size = size;
  63501. }
  63502. };
  63503. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63504. get: function () {
  63505. return this._samples;
  63506. },
  63507. set: function (value) {
  63508. if (this._samples === value) {
  63509. return;
  63510. }
  63511. var scene = this.getScene();
  63512. if (!scene) {
  63513. return;
  63514. }
  63515. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63516. },
  63517. enumerable: true,
  63518. configurable: true
  63519. });
  63520. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63521. this._currentRefreshId = -1;
  63522. };
  63523. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63524. get: function () {
  63525. return this._refreshRate;
  63526. },
  63527. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63528. set: function (value) {
  63529. this._refreshRate = value;
  63530. this.resetRefreshCounter();
  63531. },
  63532. enumerable: true,
  63533. configurable: true
  63534. });
  63535. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63536. if (!this._postProcessManager) {
  63537. var scene = this.getScene();
  63538. if (!scene) {
  63539. return;
  63540. }
  63541. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63542. this._postProcesses = new Array();
  63543. }
  63544. this._postProcesses.push(postProcess);
  63545. this._postProcesses[0].autoClear = false;
  63546. };
  63547. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63548. if (!this._postProcesses) {
  63549. return;
  63550. }
  63551. if (dispose) {
  63552. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63553. var postProcess = _a[_i];
  63554. postProcess.dispose();
  63555. }
  63556. }
  63557. this._postProcesses = [];
  63558. };
  63559. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63560. if (!this._postProcesses) {
  63561. return;
  63562. }
  63563. var index = this._postProcesses.indexOf(postProcess);
  63564. if (index === -1) {
  63565. return;
  63566. }
  63567. this._postProcesses.splice(index, 1);
  63568. if (this._postProcesses.length > 0) {
  63569. this._postProcesses[0].autoClear = false;
  63570. }
  63571. };
  63572. RenderTargetTexture.prototype._shouldRender = function () {
  63573. if (this._currentRefreshId === -1) { // At least render once
  63574. this._currentRefreshId = 1;
  63575. return true;
  63576. }
  63577. if (this.refreshRate === this._currentRefreshId) {
  63578. this._currentRefreshId = 1;
  63579. return true;
  63580. }
  63581. this._currentRefreshId++;
  63582. return false;
  63583. };
  63584. RenderTargetTexture.prototype.getRenderSize = function () {
  63585. if (this._size.width) {
  63586. return this._size.width;
  63587. }
  63588. return this._size;
  63589. };
  63590. RenderTargetTexture.prototype.getRenderWidth = function () {
  63591. if (this._size.width) {
  63592. return this._size.width;
  63593. }
  63594. return this._size;
  63595. };
  63596. RenderTargetTexture.prototype.getRenderHeight = function () {
  63597. if (this._size.width) {
  63598. return this._size.height;
  63599. }
  63600. return this._size;
  63601. };
  63602. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63603. get: function () {
  63604. return true;
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. RenderTargetTexture.prototype.scale = function (ratio) {
  63610. var newSize = this.getRenderSize() * ratio;
  63611. this.resize(newSize);
  63612. };
  63613. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63614. if (this.isCube) {
  63615. return this._textureMatrix;
  63616. }
  63617. return _super.prototype.getReflectionTextureMatrix.call(this);
  63618. };
  63619. RenderTargetTexture.prototype.resize = function (size) {
  63620. this.releaseInternalTexture();
  63621. var scene = this.getScene();
  63622. if (!scene) {
  63623. return;
  63624. }
  63625. this._processSizeParameter(size);
  63626. if (this.isCube) {
  63627. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63628. }
  63629. else {
  63630. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63631. }
  63632. };
  63633. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63634. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63635. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63636. var scene = this.getScene();
  63637. if (!scene) {
  63638. return;
  63639. }
  63640. var engine = scene.getEngine();
  63641. if (this.useCameraPostProcesses !== undefined) {
  63642. useCameraPostProcess = this.useCameraPostProcesses;
  63643. }
  63644. if (this._waitingRenderList) {
  63645. this.renderList = [];
  63646. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63647. var id = this._waitingRenderList[index];
  63648. var mesh_1 = scene.getMeshByID(id);
  63649. if (mesh_1) {
  63650. this.renderList.push(mesh_1);
  63651. }
  63652. }
  63653. delete this._waitingRenderList;
  63654. }
  63655. // Is predicate defined?
  63656. if (this.renderListPredicate) {
  63657. if (this.renderList) {
  63658. this.renderList.splice(0); // Clear previous renderList
  63659. }
  63660. else {
  63661. this.renderList = [];
  63662. }
  63663. var scene = this.getScene();
  63664. if (!scene) {
  63665. return;
  63666. }
  63667. var sceneMeshes = scene.meshes;
  63668. for (var index = 0; index < sceneMeshes.length; index++) {
  63669. var mesh = sceneMeshes[index];
  63670. if (this.renderListPredicate(mesh)) {
  63671. this.renderList.push(mesh);
  63672. }
  63673. }
  63674. }
  63675. this.onBeforeBindObservable.notifyObservers(this);
  63676. // Set custom projection.
  63677. // Needs to be before binding to prevent changing the aspect ratio.
  63678. var camera;
  63679. if (this.activeCamera) {
  63680. camera = this.activeCamera;
  63681. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63682. if (this.activeCamera !== scene.activeCamera) {
  63683. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63684. }
  63685. }
  63686. else {
  63687. camera = scene.activeCamera;
  63688. if (camera) {
  63689. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63690. }
  63691. }
  63692. // Prepare renderingManager
  63693. this._renderingManager.reset();
  63694. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63695. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63696. var sceneRenderId = scene.getRenderId();
  63697. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63698. var mesh = currentRenderList[meshIndex];
  63699. if (mesh) {
  63700. if (!mesh.isReady(this.refreshRate === 0)) {
  63701. this.resetRefreshCounter();
  63702. continue;
  63703. }
  63704. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63705. var isMasked = void 0;
  63706. if (!this.renderList && camera) {
  63707. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63708. }
  63709. else {
  63710. isMasked = false;
  63711. }
  63712. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63713. mesh._activate(sceneRenderId);
  63714. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63715. var subMesh = mesh.subMeshes[subIndex];
  63716. scene._activeIndices.addCount(subMesh.indexCount, false);
  63717. this._renderingManager.dispatch(subMesh, mesh);
  63718. }
  63719. }
  63720. }
  63721. }
  63722. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63723. var particleSystem = scene.particleSystems[particleIndex];
  63724. var emitter = particleSystem.emitter;
  63725. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63726. continue;
  63727. }
  63728. if (currentRenderList.indexOf(emitter) >= 0) {
  63729. this._renderingManager.dispatchParticles(particleSystem);
  63730. }
  63731. }
  63732. if (this.isCube) {
  63733. for (var face = 0; face < 6; face++) {
  63734. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63735. scene.incrementRenderId();
  63736. scene.resetCachedMaterial();
  63737. }
  63738. }
  63739. else {
  63740. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63741. }
  63742. this.onAfterUnbindObservable.notifyObservers(this);
  63743. if (scene.activeCamera) {
  63744. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63745. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63746. }
  63747. engine.setViewport(scene.activeCamera.viewport);
  63748. }
  63749. scene.resetCachedMaterial();
  63750. };
  63751. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63752. var minimum = 128;
  63753. var x = renderDimension * scale;
  63754. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63755. // Ensure we don't exceed the render dimension (while staying POT)
  63756. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63757. };
  63758. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63759. var _this = this;
  63760. if (!this._texture) {
  63761. return;
  63762. }
  63763. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63764. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63765. });
  63766. };
  63767. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63768. var scene = this.getScene();
  63769. if (!scene) {
  63770. return;
  63771. }
  63772. var engine = scene.getEngine();
  63773. if (!this._texture) {
  63774. return;
  63775. }
  63776. // Bind
  63777. if (this._postProcessManager) {
  63778. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63779. }
  63780. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63781. if (this._texture) {
  63782. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63783. }
  63784. }
  63785. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63786. // Clear
  63787. if (this.onClearObservable.hasObservers()) {
  63788. this.onClearObservable.notifyObservers(engine);
  63789. }
  63790. else {
  63791. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63792. }
  63793. if (!this._doNotChangeAspectRatio) {
  63794. scene.updateTransformMatrix(true);
  63795. }
  63796. // Render
  63797. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63798. if (this._postProcessManager) {
  63799. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63800. }
  63801. else if (useCameraPostProcess) {
  63802. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63803. }
  63804. if (!this._doNotChangeAspectRatio) {
  63805. scene.updateTransformMatrix(true);
  63806. }
  63807. // Dump ?
  63808. if (dumpForDebug) {
  63809. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63810. }
  63811. // Unbind
  63812. if (!this.isCube || faceIndex === 5) {
  63813. if (this.isCube) {
  63814. if (faceIndex === 5) {
  63815. engine.generateMipMapsForCubemap(this._texture);
  63816. }
  63817. }
  63818. this.unbindFrameBuffer(engine, faceIndex);
  63819. }
  63820. else {
  63821. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63822. }
  63823. };
  63824. /**
  63825. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63826. * This allowed control for front to back rendering or reversly depending of the special needs.
  63827. *
  63828. * @param renderingGroupId The rendering group id corresponding to its index
  63829. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63830. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63831. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63832. */
  63833. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63834. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63835. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63836. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63837. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63838. };
  63839. /**
  63840. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63841. *
  63842. * @param renderingGroupId The rendering group id corresponding to its index
  63843. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63844. */
  63845. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63846. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63847. };
  63848. RenderTargetTexture.prototype.clone = function () {
  63849. var textureSize = this.getSize();
  63850. 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);
  63851. // Base texture
  63852. newTexture.hasAlpha = this.hasAlpha;
  63853. newTexture.level = this.level;
  63854. // RenderTarget Texture
  63855. newTexture.coordinatesMode = this.coordinatesMode;
  63856. if (this.renderList) {
  63857. newTexture.renderList = this.renderList.slice(0);
  63858. }
  63859. return newTexture;
  63860. };
  63861. RenderTargetTexture.prototype.serialize = function () {
  63862. if (!this.name) {
  63863. return null;
  63864. }
  63865. var serializationObject = _super.prototype.serialize.call(this);
  63866. serializationObject.renderTargetSize = this.getRenderSize();
  63867. serializationObject.renderList = [];
  63868. if (this.renderList) {
  63869. for (var index = 0; index < this.renderList.length; index++) {
  63870. serializationObject.renderList.push(this.renderList[index].id);
  63871. }
  63872. }
  63873. return serializationObject;
  63874. };
  63875. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63876. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63877. var objBuffer = this.getInternalTexture();
  63878. var scene = this.getScene();
  63879. if (objBuffer && scene) {
  63880. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63881. }
  63882. };
  63883. RenderTargetTexture.prototype.dispose = function () {
  63884. if (this._postProcessManager) {
  63885. this._postProcessManager.dispose();
  63886. this._postProcessManager = null;
  63887. }
  63888. this.clearPostProcesses(true);
  63889. if (this._resizeObserver) {
  63890. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63891. this._resizeObserver = null;
  63892. }
  63893. this.renderList = null;
  63894. // Remove from custom render targets
  63895. var scene = this.getScene();
  63896. if (!scene) {
  63897. return;
  63898. }
  63899. var index = scene.customRenderTargets.indexOf(this);
  63900. if (index >= 0) {
  63901. scene.customRenderTargets.splice(index, 1);
  63902. }
  63903. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63904. var camera = _a[_i];
  63905. index = camera.customRenderTargets.indexOf(this);
  63906. if (index >= 0) {
  63907. camera.customRenderTargets.splice(index, 1);
  63908. }
  63909. }
  63910. _super.prototype.dispose.call(this);
  63911. };
  63912. RenderTargetTexture.prototype._rebuild = function () {
  63913. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63914. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63915. }
  63916. if (this._postProcessManager) {
  63917. this._postProcessManager._rebuild();
  63918. }
  63919. };
  63920. /**
  63921. * Clear the info related to rendering groups preventing retention point in material dispose.
  63922. */
  63923. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63924. if (this._renderingManager) {
  63925. this._renderingManager.freeRenderingGroups();
  63926. }
  63927. };
  63928. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63929. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63930. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63931. return RenderTargetTexture;
  63932. }(BABYLON.Texture));
  63933. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63934. })(BABYLON || (BABYLON = {}));
  63935. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63936. var BABYLON;
  63937. (function (BABYLON) {
  63938. ;
  63939. var MultiRenderTarget = /** @class */ (function (_super) {
  63940. __extends(MultiRenderTarget, _super);
  63941. function MultiRenderTarget(name, size, count, scene, options) {
  63942. var _this = this;
  63943. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63944. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63945. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63946. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63947. _this._engine = scene.getEngine();
  63948. if (!_this.isSupported) {
  63949. _this.dispose();
  63950. return;
  63951. }
  63952. var types = [];
  63953. var samplingModes = [];
  63954. for (var i = 0; i < count; i++) {
  63955. if (options && options.types && options.types[i] !== undefined) {
  63956. types.push(options.types[i]);
  63957. }
  63958. else {
  63959. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63960. }
  63961. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63962. samplingModes.push(options.samplingModes[i]);
  63963. }
  63964. else {
  63965. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63966. }
  63967. }
  63968. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63969. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63970. _this._size = size;
  63971. _this._multiRenderTargetOptions = {
  63972. samplingModes: samplingModes,
  63973. generateMipMaps: generateMipMaps,
  63974. generateDepthBuffer: generateDepthBuffer,
  63975. generateStencilBuffer: generateStencilBuffer,
  63976. generateDepthTexture: generateDepthTexture,
  63977. types: types,
  63978. textureCount: count
  63979. };
  63980. _this._createInternalTextures();
  63981. _this._createTextures();
  63982. return _this;
  63983. }
  63984. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63985. get: function () {
  63986. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63987. },
  63988. enumerable: true,
  63989. configurable: true
  63990. });
  63991. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63992. get: function () {
  63993. return this._textures;
  63994. },
  63995. enumerable: true,
  63996. configurable: true
  63997. });
  63998. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63999. get: function () {
  64000. return this._textures[this._textures.length - 1];
  64001. },
  64002. enumerable: true,
  64003. configurable: true
  64004. });
  64005. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64006. set: function (wrap) {
  64007. if (this._textures) {
  64008. for (var i = 0; i < this._textures.length; i++) {
  64009. this._textures[i].wrapU = wrap;
  64010. }
  64011. }
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64017. set: function (wrap) {
  64018. if (this._textures) {
  64019. for (var i = 0; i < this._textures.length; i++) {
  64020. this._textures[i].wrapV = wrap;
  64021. }
  64022. }
  64023. },
  64024. enumerable: true,
  64025. configurable: true
  64026. });
  64027. MultiRenderTarget.prototype._rebuild = function () {
  64028. this.releaseInternalTextures();
  64029. this._createInternalTextures();
  64030. for (var i = 0; i < this._internalTextures.length; i++) {
  64031. var texture = this._textures[i];
  64032. texture._texture = this._internalTextures[i];
  64033. }
  64034. // Keeps references to frame buffer and stencil/depth buffer
  64035. this._texture = this._internalTextures[0];
  64036. };
  64037. MultiRenderTarget.prototype._createInternalTextures = function () {
  64038. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64039. };
  64040. MultiRenderTarget.prototype._createTextures = function () {
  64041. this._textures = [];
  64042. for (var i = 0; i < this._internalTextures.length; i++) {
  64043. var texture = new BABYLON.Texture(null, this.getScene());
  64044. texture._texture = this._internalTextures[i];
  64045. this._textures.push(texture);
  64046. }
  64047. // Keeps references to frame buffer and stencil/depth buffer
  64048. this._texture = this._internalTextures[0];
  64049. };
  64050. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64051. get: function () {
  64052. return this._samples;
  64053. },
  64054. set: function (value) {
  64055. if (this._samples === value) {
  64056. return;
  64057. }
  64058. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. MultiRenderTarget.prototype.resize = function (size) {
  64064. this.releaseInternalTextures();
  64065. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64066. this._createInternalTextures();
  64067. };
  64068. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64069. var _this = this;
  64070. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64071. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64072. });
  64073. };
  64074. MultiRenderTarget.prototype.dispose = function () {
  64075. this.releaseInternalTextures();
  64076. _super.prototype.dispose.call(this);
  64077. };
  64078. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64079. if (!this._internalTextures) {
  64080. return;
  64081. }
  64082. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64083. if (this._internalTextures[i] !== undefined) {
  64084. this._internalTextures[i].dispose();
  64085. this._internalTextures.splice(i, 1);
  64086. }
  64087. }
  64088. };
  64089. return MultiRenderTarget;
  64090. }(BABYLON.RenderTargetTexture));
  64091. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64092. })(BABYLON || (BABYLON = {}));
  64093. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64094. var BABYLON;
  64095. (function (BABYLON) {
  64096. var MirrorTexture = /** @class */ (function (_super) {
  64097. __extends(MirrorTexture, _super);
  64098. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64099. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64101. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64102. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64103. _this.scene = scene;
  64104. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64105. _this._transformMatrix = BABYLON.Matrix.Zero();
  64106. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64107. _this._adaptiveBlurKernel = 0;
  64108. _this._blurKernelX = 0;
  64109. _this._blurKernelY = 0;
  64110. _this._blurRatio = 1.0;
  64111. _this.ignoreCameraViewport = true;
  64112. _this._updateGammaSpace();
  64113. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64114. _this._updateGammaSpace;
  64115. });
  64116. _this.onBeforeRenderObservable.add(function () {
  64117. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64118. _this._savedViewMatrix = scene.getViewMatrix();
  64119. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64120. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64121. scene.clipPlane = _this.mirrorPlane;
  64122. scene.getEngine().cullBackFaces = false;
  64123. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64124. });
  64125. _this.onAfterRenderObservable.add(function () {
  64126. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64127. scene.getEngine().cullBackFaces = true;
  64128. scene._mirroredCameraPosition = null;
  64129. delete scene.clipPlane;
  64130. });
  64131. return _this;
  64132. }
  64133. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64134. get: function () {
  64135. return this._blurRatio;
  64136. },
  64137. set: function (value) {
  64138. if (this._blurRatio === value) {
  64139. return;
  64140. }
  64141. this._blurRatio = value;
  64142. this._preparePostProcesses();
  64143. },
  64144. enumerable: true,
  64145. configurable: true
  64146. });
  64147. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64148. set: function (value) {
  64149. this._adaptiveBlurKernel = value;
  64150. this._autoComputeBlurKernel();
  64151. },
  64152. enumerable: true,
  64153. configurable: true
  64154. });
  64155. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64156. set: function (value) {
  64157. this.blurKernelX = value;
  64158. this.blurKernelY = value;
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64164. get: function () {
  64165. return this._blurKernelX;
  64166. },
  64167. set: function (value) {
  64168. if (this._blurKernelX === value) {
  64169. return;
  64170. }
  64171. this._blurKernelX = value;
  64172. this._preparePostProcesses();
  64173. },
  64174. enumerable: true,
  64175. configurable: true
  64176. });
  64177. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64178. get: function () {
  64179. return this._blurKernelY;
  64180. },
  64181. set: function (value) {
  64182. if (this._blurKernelY === value) {
  64183. return;
  64184. }
  64185. this._blurKernelY = value;
  64186. this._preparePostProcesses();
  64187. },
  64188. enumerable: true,
  64189. configurable: true
  64190. });
  64191. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64192. var engine = this.getScene().getEngine();
  64193. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64194. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64195. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64196. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64197. };
  64198. MirrorTexture.prototype._onRatioRescale = function () {
  64199. if (this._sizeRatio) {
  64200. this.resize(this._initialSizeParameter);
  64201. if (!this._adaptiveBlurKernel) {
  64202. this._preparePostProcesses();
  64203. }
  64204. }
  64205. if (this._adaptiveBlurKernel) {
  64206. this._autoComputeBlurKernel();
  64207. }
  64208. };
  64209. MirrorTexture.prototype._updateGammaSpace = function () {
  64210. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64211. };
  64212. MirrorTexture.prototype._preparePostProcesses = function () {
  64213. this.clearPostProcesses(true);
  64214. if (this._blurKernelX && this._blurKernelY) {
  64215. var engine = this.getScene().getEngine();
  64216. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64217. 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);
  64218. this._blurX.autoClear = false;
  64219. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64220. this._blurX.inputTexture = this._texture;
  64221. }
  64222. else {
  64223. this._blurX.alwaysForcePOT = true;
  64224. }
  64225. 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);
  64226. this._blurY.autoClear = false;
  64227. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64228. this.addPostProcess(this._blurX);
  64229. this.addPostProcess(this._blurY);
  64230. }
  64231. else {
  64232. if (this._blurY) {
  64233. this.removePostProcess(this._blurY);
  64234. this._blurY.dispose();
  64235. this._blurY = null;
  64236. }
  64237. if (this._blurX) {
  64238. this.removePostProcess(this._blurX);
  64239. this._blurX.dispose();
  64240. this._blurX = null;
  64241. }
  64242. }
  64243. };
  64244. MirrorTexture.prototype.clone = function () {
  64245. var scene = this.getScene();
  64246. if (!scene) {
  64247. return this;
  64248. }
  64249. var textureSize = this.getSize();
  64250. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64251. // Base texture
  64252. newTexture.hasAlpha = this.hasAlpha;
  64253. newTexture.level = this.level;
  64254. // Mirror Texture
  64255. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64256. if (this.renderList) {
  64257. newTexture.renderList = this.renderList.slice(0);
  64258. }
  64259. return newTexture;
  64260. };
  64261. MirrorTexture.prototype.serialize = function () {
  64262. if (!this.name) {
  64263. return null;
  64264. }
  64265. var serializationObject = _super.prototype.serialize.call(this);
  64266. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64267. return serializationObject;
  64268. };
  64269. MirrorTexture.prototype.dispose = function () {
  64270. _super.prototype.dispose.call(this);
  64271. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64272. };
  64273. return MirrorTexture;
  64274. }(BABYLON.RenderTargetTexture));
  64275. BABYLON.MirrorTexture = MirrorTexture;
  64276. })(BABYLON || (BABYLON = {}));
  64277. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64278. var BABYLON;
  64279. (function (BABYLON) {
  64280. /**
  64281. * Creates a refraction texture used by refraction channel of the standard material.
  64282. * @param name the texture name
  64283. * @param size size of the underlying texture
  64284. * @param scene root scene
  64285. */
  64286. var RefractionTexture = /** @class */ (function (_super) {
  64287. __extends(RefractionTexture, _super);
  64288. function RefractionTexture(name, size, scene, generateMipMaps) {
  64289. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64290. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64291. _this.depth = 2.0;
  64292. _this.onBeforeRenderObservable.add(function () {
  64293. scene.clipPlane = _this.refractionPlane;
  64294. });
  64295. _this.onAfterRenderObservable.add(function () {
  64296. delete scene.clipPlane;
  64297. });
  64298. return _this;
  64299. }
  64300. RefractionTexture.prototype.clone = function () {
  64301. var scene = this.getScene();
  64302. if (!scene) {
  64303. return this;
  64304. }
  64305. var textureSize = this.getSize();
  64306. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64307. // Base texture
  64308. newTexture.hasAlpha = this.hasAlpha;
  64309. newTexture.level = this.level;
  64310. // Refraction Texture
  64311. newTexture.refractionPlane = this.refractionPlane.clone();
  64312. if (this.renderList) {
  64313. newTexture.renderList = this.renderList.slice(0);
  64314. }
  64315. newTexture.depth = this.depth;
  64316. return newTexture;
  64317. };
  64318. RefractionTexture.prototype.serialize = function () {
  64319. if (!this.name) {
  64320. return null;
  64321. }
  64322. var serializationObject = _super.prototype.serialize.call(this);
  64323. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64324. serializationObject.depth = this.depth;
  64325. return serializationObject;
  64326. };
  64327. return RefractionTexture;
  64328. }(BABYLON.RenderTargetTexture));
  64329. BABYLON.RefractionTexture = RefractionTexture;
  64330. })(BABYLON || (BABYLON = {}));
  64331. //# sourceMappingURL=babylon.refractionTexture.js.map
  64332. var BABYLON;
  64333. (function (BABYLON) {
  64334. /**
  64335. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64336. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64337. */
  64338. var DynamicTexture = /** @class */ (function (_super) {
  64339. __extends(DynamicTexture, _super);
  64340. /**
  64341. * Creates a {BABYLON.DynamicTexture}
  64342. * @param name defines the name of the texture
  64343. * @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
  64344. * @param scene defines the scene where you want the texture
  64345. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64346. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64347. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64348. */
  64349. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64350. if (scene === void 0) { scene = null; }
  64351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64352. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64353. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64354. _this.name = name;
  64355. _this._engine = _this.getScene().getEngine();
  64356. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64357. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64358. _this._generateMipMaps = generateMipMaps;
  64359. if (options.getContext) {
  64360. _this._canvas = options;
  64361. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64362. }
  64363. else {
  64364. _this._canvas = document.createElement("canvas");
  64365. if (options.width || options.width === 0) {
  64366. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64367. }
  64368. else {
  64369. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64370. }
  64371. }
  64372. var textureSize = _this.getSize();
  64373. _this._canvas.width = textureSize.width;
  64374. _this._canvas.height = textureSize.height;
  64375. _this._context = _this._canvas.getContext("2d");
  64376. return _this;
  64377. }
  64378. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64379. /**
  64380. * Gets the current state of canRescale
  64381. */
  64382. get: function () {
  64383. return true;
  64384. },
  64385. enumerable: true,
  64386. configurable: true
  64387. });
  64388. DynamicTexture.prototype._recreate = function (textureSize) {
  64389. this._canvas.width = textureSize.width;
  64390. this._canvas.height = textureSize.height;
  64391. this.releaseInternalTexture();
  64392. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64393. };
  64394. /**
  64395. * Scales the texture
  64396. * @param ratio the scale factor to apply to both width and height
  64397. */
  64398. DynamicTexture.prototype.scale = function (ratio) {
  64399. var textureSize = this.getSize();
  64400. textureSize.width *= ratio;
  64401. textureSize.height *= ratio;
  64402. this._recreate(textureSize);
  64403. };
  64404. /**
  64405. * Resizes the texture
  64406. * @param width the new width
  64407. * @param height the new height
  64408. */
  64409. DynamicTexture.prototype.scaleTo = function (width, height) {
  64410. var textureSize = this.getSize();
  64411. textureSize.width = width;
  64412. textureSize.height = height;
  64413. this._recreate(textureSize);
  64414. };
  64415. /**
  64416. * Gets the context of the canvas used by the texture
  64417. * @returns the canvas context of the dynamic texture
  64418. */
  64419. DynamicTexture.prototype.getContext = function () {
  64420. return this._context;
  64421. };
  64422. /**
  64423. * Clears the texture
  64424. */
  64425. DynamicTexture.prototype.clear = function () {
  64426. var size = this.getSize();
  64427. this._context.fillRect(0, 0, size.width, size.height);
  64428. };
  64429. /**
  64430. * Updates the texture
  64431. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64432. */
  64433. DynamicTexture.prototype.update = function (invertY) {
  64434. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64435. };
  64436. /**
  64437. * Draws text onto the texture
  64438. * @param text defines the text to be drawn
  64439. * @param x defines the placement of the text from the left
  64440. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64441. * @param font defines the font to be used with font-style, font-size, font-name
  64442. * @param color defines the color used for the text
  64443. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64444. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64445. * @param update defines whether texture is immediately update (default is true)
  64446. */
  64447. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64448. if (update === void 0) { update = true; }
  64449. var size = this.getSize();
  64450. if (clearColor) {
  64451. this._context.fillStyle = clearColor;
  64452. this._context.fillRect(0, 0, size.width, size.height);
  64453. }
  64454. this._context.font = font;
  64455. if (x === null || x === undefined) {
  64456. var textSize = this._context.measureText(text);
  64457. x = (size.width - textSize.width) / 2;
  64458. }
  64459. if (y === null || y === undefined) {
  64460. var fontSize = parseInt((font.replace(/\D/g, '')));
  64461. y = (size.height / 2) + (fontSize / 3.65);
  64462. }
  64463. this._context.fillStyle = color;
  64464. this._context.fillText(text, x, y);
  64465. if (update) {
  64466. this.update(invertY);
  64467. }
  64468. };
  64469. /**
  64470. * Clones the texture
  64471. * @returns the clone of the texture.
  64472. */
  64473. DynamicTexture.prototype.clone = function () {
  64474. var scene = this.getScene();
  64475. if (!scene) {
  64476. return this;
  64477. }
  64478. var textureSize = this.getSize();
  64479. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64480. // Base texture
  64481. newTexture.hasAlpha = this.hasAlpha;
  64482. newTexture.level = this.level;
  64483. // Dynamic Texture
  64484. newTexture.wrapU = this.wrapU;
  64485. newTexture.wrapV = this.wrapV;
  64486. return newTexture;
  64487. };
  64488. /** @hidden */
  64489. DynamicTexture.prototype._rebuild = function () {
  64490. this.update();
  64491. };
  64492. return DynamicTexture;
  64493. }(BABYLON.Texture));
  64494. BABYLON.DynamicTexture = DynamicTexture;
  64495. })(BABYLON || (BABYLON = {}));
  64496. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64497. var BABYLON;
  64498. (function (BABYLON) {
  64499. var VideoTexture = /** @class */ (function (_super) {
  64500. __extends(VideoTexture, _super);
  64501. /**
  64502. * Creates a video texture.
  64503. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64504. * @param {string | null} name optional name, will detect from video source, if not defined
  64505. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64506. * @param {BABYLON.Scene} scene is obviously the current scene.
  64507. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64508. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64509. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64510. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64511. */
  64512. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64513. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64514. if (invertY === void 0) { invertY = false; }
  64515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64516. if (settings === void 0) { settings = {
  64517. autoPlay: true,
  64518. loop: true,
  64519. autoUpdateTexture: true,
  64520. }; }
  64521. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64522. _this._stillImageCaptured = false;
  64523. _this._createInternalTexture = function () {
  64524. if (_this._texture != null) {
  64525. return;
  64526. }
  64527. if (!_this._engine.needPOTTextures ||
  64528. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64529. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64530. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64531. }
  64532. else {
  64533. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64534. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64535. _this._generateMipMaps = false;
  64536. }
  64537. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64538. if (!_this.video.autoplay) {
  64539. var oldHandler_1 = _this.video.onplaying;
  64540. _this.video.onplaying = function () {
  64541. _this.video.onplaying = oldHandler_1;
  64542. _this._texture.isReady = true;
  64543. _this._updateInternalTexture();
  64544. _this.video.pause();
  64545. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64546. _this.onLoadObservable.notifyObservers(_this);
  64547. }
  64548. };
  64549. _this.video.play();
  64550. }
  64551. else {
  64552. _this._texture.isReady = true;
  64553. _this._updateInternalTexture();
  64554. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64555. _this.onLoadObservable.notifyObservers(_this);
  64556. }
  64557. }
  64558. };
  64559. _this.reset = function () {
  64560. if (_this._texture == null) {
  64561. return;
  64562. }
  64563. _this._texture.dispose();
  64564. _this._texture = null;
  64565. };
  64566. _this._updateInternalTexture = function (e) {
  64567. if (_this._texture == null || !_this._texture.isReady) {
  64568. return;
  64569. }
  64570. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64571. return;
  64572. }
  64573. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64574. };
  64575. _this._engine = _this.getScene().getEngine();
  64576. _this._generateMipMaps = generateMipMaps;
  64577. _this._samplingMode = samplingMode;
  64578. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64579. _this.name = name || _this._getName(src);
  64580. _this.video = _this._getVideo(src);
  64581. if (settings.autoPlay !== undefined) {
  64582. _this.video.autoplay = settings.autoPlay;
  64583. }
  64584. if (settings.loop !== undefined) {
  64585. _this.video.loop = settings.loop;
  64586. }
  64587. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64588. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64589. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64590. _this.video.addEventListener("emptied", _this.reset);
  64591. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64592. _this._createInternalTexture();
  64593. }
  64594. return _this;
  64595. }
  64596. VideoTexture.prototype._getName = function (src) {
  64597. if (src instanceof HTMLVideoElement) {
  64598. return src.currentSrc;
  64599. }
  64600. if (typeof src === "object") {
  64601. return src.toString();
  64602. }
  64603. return src;
  64604. };
  64605. ;
  64606. VideoTexture.prototype._getVideo = function (src) {
  64607. if (src instanceof HTMLVideoElement) {
  64608. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64609. return src;
  64610. }
  64611. var video = document.createElement("video");
  64612. if (typeof src === "string") {
  64613. BABYLON.Tools.SetCorsBehavior(src, video);
  64614. video.src = src;
  64615. }
  64616. else {
  64617. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64618. src.forEach(function (url) {
  64619. var source = document.createElement("source");
  64620. source.src = url;
  64621. video.appendChild(source);
  64622. });
  64623. }
  64624. return video;
  64625. };
  64626. ;
  64627. /**
  64628. * Internal method to initiate `update`.
  64629. */
  64630. VideoTexture.prototype._rebuild = function () {
  64631. this.update();
  64632. };
  64633. /**
  64634. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64635. */
  64636. VideoTexture.prototype.update = function () {
  64637. if (!this.autoUpdateTexture) {
  64638. // Expecting user to call `updateTexture` manually
  64639. return;
  64640. }
  64641. this.updateTexture(true);
  64642. };
  64643. /**
  64644. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64645. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64646. */
  64647. VideoTexture.prototype.updateTexture = function (isVisible) {
  64648. if (!isVisible) {
  64649. return;
  64650. }
  64651. if (this.video.paused && this._stillImageCaptured) {
  64652. return;
  64653. }
  64654. this._stillImageCaptured = true;
  64655. this._updateInternalTexture();
  64656. };
  64657. /**
  64658. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64659. * @param url New url.
  64660. */
  64661. VideoTexture.prototype.updateURL = function (url) {
  64662. this.video.src = url;
  64663. };
  64664. VideoTexture.prototype.dispose = function () {
  64665. _super.prototype.dispose.call(this);
  64666. this.video.removeEventListener("canplay", this._createInternalTexture);
  64667. this.video.removeEventListener("paused", this._updateInternalTexture);
  64668. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64669. this.video.removeEventListener("emptied", this.reset);
  64670. this.video.pause();
  64671. };
  64672. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64673. var video = document.createElement("video");
  64674. var constraintsDeviceId;
  64675. if (constraints && constraints.deviceId) {
  64676. constraintsDeviceId = {
  64677. exact: constraints.deviceId,
  64678. };
  64679. }
  64680. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64681. if (navigator.mediaDevices) {
  64682. navigator.mediaDevices.getUserMedia({ video: constraints })
  64683. .then(function (stream) {
  64684. if (video.mozSrcObject !== undefined) {
  64685. // hack for Firefox < 19
  64686. video.mozSrcObject = stream;
  64687. }
  64688. else {
  64689. video.srcObject = stream;
  64690. }
  64691. var onPlaying = function () {
  64692. if (onReady) {
  64693. onReady(new VideoTexture("video", video, scene, true, true));
  64694. }
  64695. video.removeEventListener("playing", onPlaying);
  64696. };
  64697. video.addEventListener("playing", onPlaying);
  64698. video.play();
  64699. })
  64700. .catch(function (err) {
  64701. BABYLON.Tools.Error(err.name);
  64702. });
  64703. }
  64704. else {
  64705. navigator.getUserMedia =
  64706. navigator.getUserMedia ||
  64707. navigator.webkitGetUserMedia ||
  64708. navigator.mozGetUserMedia ||
  64709. navigator.msGetUserMedia;
  64710. if (navigator.getUserMedia) {
  64711. navigator.getUserMedia({
  64712. video: {
  64713. deviceId: constraintsDeviceId,
  64714. width: {
  64715. min: (constraints && constraints.minWidth) || 256,
  64716. max: (constraints && constraints.maxWidth) || 640,
  64717. },
  64718. height: {
  64719. min: (constraints && constraints.minHeight) || 256,
  64720. max: (constraints && constraints.maxHeight) || 480,
  64721. },
  64722. },
  64723. }, function (stream) {
  64724. if (video.mozSrcObject !== undefined) {
  64725. // hack for Firefox < 19
  64726. video.mozSrcObject = stream;
  64727. }
  64728. else {
  64729. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64730. }
  64731. video.play();
  64732. if (onReady) {
  64733. onReady(new VideoTexture("video", video, scene, true, true));
  64734. }
  64735. }, function (e) {
  64736. BABYLON.Tools.Error(e.name);
  64737. });
  64738. }
  64739. }
  64740. };
  64741. return VideoTexture;
  64742. }(BABYLON.Texture));
  64743. BABYLON.VideoTexture = VideoTexture;
  64744. })(BABYLON || (BABYLON = {}));
  64745. //# sourceMappingURL=babylon.videoTexture.js.map
  64746. var BABYLON;
  64747. (function (BABYLON) {
  64748. var RawTexture = /** @class */ (function (_super) {
  64749. __extends(RawTexture, _super);
  64750. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64752. if (invertY === void 0) { invertY = false; }
  64753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64754. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64755. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64756. _this.format = format;
  64757. _this._engine = scene.getEngine();
  64758. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64759. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64760. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64761. return _this;
  64762. }
  64763. RawTexture.prototype.update = function (data) {
  64764. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64765. };
  64766. // Statics
  64767. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64769. if (invertY === void 0) { invertY = false; }
  64770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64771. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64772. };
  64773. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64774. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64775. if (invertY === void 0) { invertY = false; }
  64776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64778. };
  64779. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64781. if (invertY === void 0) { invertY = false; }
  64782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64783. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64784. };
  64785. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64786. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64787. if (invertY === void 0) { invertY = false; }
  64788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64789. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64790. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64791. };
  64792. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64794. if (invertY === void 0) { invertY = false; }
  64795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64796. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64797. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64798. };
  64799. return RawTexture;
  64800. }(BABYLON.Texture));
  64801. BABYLON.RawTexture = RawTexture;
  64802. })(BABYLON || (BABYLON = {}));
  64803. //# sourceMappingURL=babylon.rawTexture.js.map
  64804. var BABYLON;
  64805. (function (BABYLON) {
  64806. /**
  64807. * Class used to store 3D textures containing user data
  64808. */
  64809. var RawTexture3D = /** @class */ (function (_super) {
  64810. __extends(RawTexture3D, _super);
  64811. /**
  64812. * Create a new RawTexture3D
  64813. * @param data defines the data of the texture
  64814. * @param width defines the width of the texture
  64815. * @param height defines the height of the texture
  64816. * @param depth defines the depth of the texture
  64817. * @param format defines the texture format to use
  64818. * @param scene defines the hosting scene
  64819. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64820. * @param invertY defines if texture must be stored with Y axis inverted
  64821. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64822. */
  64823. function RawTexture3D(data, width, height, depth,
  64824. /** Gets or sets the texture format to use*/
  64825. format, scene, generateMipMaps, invertY, samplingMode) {
  64826. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64827. if (invertY === void 0) { invertY = false; }
  64828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64829. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64830. _this.format = format;
  64831. _this._engine = scene.getEngine();
  64832. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64833. _this.is3D = true;
  64834. return _this;
  64835. }
  64836. /**
  64837. * Update the texture with new data
  64838. * @param data defines the data to store in the texture
  64839. */
  64840. RawTexture3D.prototype.update = function (data) {
  64841. if (!this._texture) {
  64842. return;
  64843. }
  64844. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64845. };
  64846. return RawTexture3D;
  64847. }(BABYLON.Texture));
  64848. BABYLON.RawTexture3D = RawTexture3D;
  64849. })(BABYLON || (BABYLON = {}));
  64850. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64851. var BABYLON;
  64852. (function (BABYLON) {
  64853. /**
  64854. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64855. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64856. */
  64857. var PostProcess = /** @class */ (function () {
  64858. /**
  64859. * Creates a new instance PostProcess
  64860. * @param name The name of the PostProcess.
  64861. * @param fragmentUrl The url of the fragment shader to be used.
  64862. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64863. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64864. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64865. * @param camera The camera to apply the render pass to.
  64866. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64867. * @param engine The engine which the post process will be applied. (default: current engine)
  64868. * @param reusable If the post process can be reused on the same frame. (default: false)
  64869. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64870. * @param textureType Type of textures used when performing the post process. (default: 0)
  64871. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64872. * @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
  64873. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64874. */
  64875. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64877. if (defines === void 0) { defines = null; }
  64878. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64879. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64880. if (blockCompilation === void 0) { blockCompilation = false; }
  64881. this.name = name;
  64882. /**
  64883. * Width of the texture to apply the post process on
  64884. */
  64885. this.width = -1;
  64886. /**
  64887. * Height of the texture to apply the post process on
  64888. */
  64889. this.height = -1;
  64890. /**
  64891. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64892. */
  64893. this._outputTexture = null;
  64894. /**
  64895. * If the buffer needs to be cleared before applying the post process. (default: true)
  64896. * Should be set to false if shader will overwrite all previous pixels.
  64897. */
  64898. this.autoClear = true;
  64899. /**
  64900. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64901. */
  64902. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64903. /**
  64904. * Animations to be used for the post processing
  64905. */
  64906. this.animations = new Array();
  64907. /**
  64908. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64909. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64910. */
  64911. this.enablePixelPerfectMode = false;
  64912. /**
  64913. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64914. */
  64915. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64916. /**
  64917. * Force textures to be a power of two (default: false)
  64918. */
  64919. this.alwaysForcePOT = false;
  64920. /**
  64921. * Number of sample textures (default: 1)
  64922. */
  64923. this.samples = 1;
  64924. /**
  64925. * Modify the scale of the post process to be the same as the viewport (default: false)
  64926. */
  64927. this.adaptScaleToCurrentViewport = false;
  64928. this._reusable = false;
  64929. /**
  64930. * Smart array of input and output textures for the post process.
  64931. */
  64932. this._textures = new BABYLON.SmartArray(2);
  64933. /**
  64934. * The index in _textures that corresponds to the output texture.
  64935. */
  64936. this._currentRenderTextureInd = 0;
  64937. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64938. this._texelSize = BABYLON.Vector2.Zero();
  64939. // Events
  64940. /**
  64941. * An event triggered when the postprocess is activated.
  64942. */
  64943. this.onActivateObservable = new BABYLON.Observable();
  64944. /**
  64945. * An event triggered when the postprocess changes its size.
  64946. */
  64947. this.onSizeChangedObservable = new BABYLON.Observable();
  64948. /**
  64949. * An event triggered when the postprocess applies its effect.
  64950. */
  64951. this.onApplyObservable = new BABYLON.Observable();
  64952. /**
  64953. * An event triggered before rendering the postprocess
  64954. */
  64955. this.onBeforeRenderObservable = new BABYLON.Observable();
  64956. /**
  64957. * An event triggered after rendering the postprocess
  64958. */
  64959. this.onAfterRenderObservable = new BABYLON.Observable();
  64960. if (camera != null) {
  64961. this._camera = camera;
  64962. this._scene = camera.getScene();
  64963. camera.attachPostProcess(this);
  64964. this._engine = this._scene.getEngine();
  64965. this._scene.postProcesses.push(this);
  64966. }
  64967. else if (engine) {
  64968. this._engine = engine;
  64969. this._engine.postProcesses.push(this);
  64970. }
  64971. this._options = options;
  64972. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64973. this._reusable = reusable || false;
  64974. this._textureType = textureType;
  64975. this._samplers = samplers || [];
  64976. this._samplers.push("textureSampler");
  64977. this._fragmentUrl = fragmentUrl;
  64978. this._vertexUrl = vertexUrl;
  64979. this._parameters = parameters || [];
  64980. this._parameters.push("scale");
  64981. this._indexParameters = indexParameters;
  64982. if (!blockCompilation) {
  64983. this.updateEffect(defines);
  64984. }
  64985. }
  64986. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64987. /**
  64988. * A function that is added to the onActivateObservable
  64989. */
  64990. set: function (callback) {
  64991. if (this._onActivateObserver) {
  64992. this.onActivateObservable.remove(this._onActivateObserver);
  64993. }
  64994. if (callback) {
  64995. this._onActivateObserver = this.onActivateObservable.add(callback);
  64996. }
  64997. },
  64998. enumerable: true,
  64999. configurable: true
  65000. });
  65001. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65002. /**
  65003. * A function that is added to the onSizeChangedObservable
  65004. */
  65005. set: function (callback) {
  65006. if (this._onSizeChangedObserver) {
  65007. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65008. }
  65009. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65010. },
  65011. enumerable: true,
  65012. configurable: true
  65013. });
  65014. Object.defineProperty(PostProcess.prototype, "onApply", {
  65015. /**
  65016. * A function that is added to the onApplyObservable
  65017. */
  65018. set: function (callback) {
  65019. if (this._onApplyObserver) {
  65020. this.onApplyObservable.remove(this._onApplyObserver);
  65021. }
  65022. this._onApplyObserver = this.onApplyObservable.add(callback);
  65023. },
  65024. enumerable: true,
  65025. configurable: true
  65026. });
  65027. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65028. /**
  65029. * A function that is added to the onBeforeRenderObservable
  65030. */
  65031. set: function (callback) {
  65032. if (this._onBeforeRenderObserver) {
  65033. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65034. }
  65035. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65041. /**
  65042. * A function that is added to the onAfterRenderObservable
  65043. */
  65044. set: function (callback) {
  65045. if (this._onAfterRenderObserver) {
  65046. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65047. }
  65048. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65049. },
  65050. enumerable: true,
  65051. configurable: true
  65052. });
  65053. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65054. /**
  65055. * 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
  65056. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65057. */
  65058. get: function () {
  65059. return this._textures.data[this._currentRenderTextureInd];
  65060. },
  65061. set: function (value) {
  65062. this._forcedOutputTexture = value;
  65063. },
  65064. enumerable: true,
  65065. configurable: true
  65066. });
  65067. /**
  65068. * Gets the camera which post process is applied to.
  65069. * @returns The camera the post process is applied to.
  65070. */
  65071. PostProcess.prototype.getCamera = function () {
  65072. return this._camera;
  65073. };
  65074. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65075. /**
  65076. * Gets the texel size of the postprocess.
  65077. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65078. */
  65079. get: function () {
  65080. if (this._shareOutputWithPostProcess) {
  65081. return this._shareOutputWithPostProcess.texelSize;
  65082. }
  65083. if (this._forcedOutputTexture) {
  65084. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65085. }
  65086. return this._texelSize;
  65087. },
  65088. enumerable: true,
  65089. configurable: true
  65090. });
  65091. /**
  65092. * Gets the engine which this post process belongs to.
  65093. * @returns The engine the post process was enabled with.
  65094. */
  65095. PostProcess.prototype.getEngine = function () {
  65096. return this._engine;
  65097. };
  65098. /**
  65099. * The effect that is created when initializing the post process.
  65100. * @returns The created effect corrisponding the the postprocess.
  65101. */
  65102. PostProcess.prototype.getEffect = function () {
  65103. return this._effect;
  65104. };
  65105. /**
  65106. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65107. * @param postProcess The post process to share the output with.
  65108. * @returns This post process.
  65109. */
  65110. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65111. this._disposeTextures();
  65112. this._shareOutputWithPostProcess = postProcess;
  65113. return this;
  65114. };
  65115. /**
  65116. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65117. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65118. */
  65119. PostProcess.prototype.useOwnOutput = function () {
  65120. if (this._textures.length == 0) {
  65121. this._textures = new BABYLON.SmartArray(2);
  65122. }
  65123. this._shareOutputWithPostProcess = null;
  65124. };
  65125. /**
  65126. * Updates the effect with the current post process compile time values and recompiles the shader.
  65127. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65128. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65129. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65130. * @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
  65131. * @param onCompiled Called when the shader has been compiled.
  65132. * @param onError Called if there is an error when compiling a shader.
  65133. */
  65134. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65135. if (defines === void 0) { defines = null; }
  65136. if (uniforms === void 0) { uniforms = null; }
  65137. if (samplers === void 0) { samplers = null; }
  65138. 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);
  65139. };
  65140. /**
  65141. * The post process is reusable if it can be used multiple times within one frame.
  65142. * @returns If the post process is reusable
  65143. */
  65144. PostProcess.prototype.isReusable = function () {
  65145. return this._reusable;
  65146. };
  65147. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65148. PostProcess.prototype.markTextureDirty = function () {
  65149. this.width = -1;
  65150. };
  65151. /**
  65152. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65153. * 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.
  65154. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65155. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65156. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65157. * @returns The target texture that was bound to be written to.
  65158. */
  65159. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65160. var _this = this;
  65161. if (sourceTexture === void 0) { sourceTexture = null; }
  65162. camera = camera || this._camera;
  65163. var scene = camera.getScene();
  65164. var engine = scene.getEngine();
  65165. var maxSize = engine.getCaps().maxTextureSize;
  65166. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65167. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65168. // 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
  65169. var webVRCamera = camera.parent;
  65170. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65171. requiredWidth /= 2;
  65172. }
  65173. var desiredWidth = (this._options.width || requiredWidth);
  65174. var desiredHeight = this._options.height || requiredHeight;
  65175. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65176. if (this.adaptScaleToCurrentViewport) {
  65177. var currentViewport = engine.currentViewport;
  65178. if (currentViewport) {
  65179. desiredWidth *= currentViewport.width;
  65180. desiredHeight *= currentViewport.height;
  65181. }
  65182. }
  65183. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65184. if (!this._options.width) {
  65185. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65186. }
  65187. if (!this._options.height) {
  65188. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65189. }
  65190. }
  65191. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65192. if (this._textures.length > 0) {
  65193. for (var i = 0; i < this._textures.length; i++) {
  65194. this._engine._releaseTexture(this._textures.data[i]);
  65195. }
  65196. this._textures.reset();
  65197. }
  65198. this.width = desiredWidth;
  65199. this.height = desiredHeight;
  65200. var textureSize = { width: this.width, height: this.height };
  65201. var textureOptions = {
  65202. generateMipMaps: false,
  65203. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65204. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65205. samplingMode: this.renderTargetSamplingMode,
  65206. type: this._textureType
  65207. };
  65208. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65209. if (this._reusable) {
  65210. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65211. }
  65212. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65213. this.onSizeChangedObservable.notifyObservers(this);
  65214. }
  65215. this._textures.forEach(function (texture) {
  65216. if (texture.samples !== _this.samples) {
  65217. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65218. }
  65219. });
  65220. }
  65221. var target;
  65222. if (this._shareOutputWithPostProcess) {
  65223. target = this._shareOutputWithPostProcess.inputTexture;
  65224. }
  65225. else if (this._forcedOutputTexture) {
  65226. target = this._forcedOutputTexture;
  65227. this.width = this._forcedOutputTexture.width;
  65228. this.height = this._forcedOutputTexture.height;
  65229. }
  65230. else {
  65231. target = this.inputTexture;
  65232. }
  65233. // Bind the input of this post process to be used as the output of the previous post process.
  65234. if (this.enablePixelPerfectMode) {
  65235. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65236. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65237. }
  65238. else {
  65239. this._scaleRatio.copyFromFloats(1, 1);
  65240. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65241. }
  65242. this.onActivateObservable.notifyObservers(camera);
  65243. // Clear
  65244. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65245. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65246. }
  65247. if (this._reusable) {
  65248. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65249. }
  65250. return target;
  65251. };
  65252. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65253. /**
  65254. * If the post process is supported.
  65255. */
  65256. get: function () {
  65257. return this._effect.isSupported;
  65258. },
  65259. enumerable: true,
  65260. configurable: true
  65261. });
  65262. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65263. /**
  65264. * The aspect ratio of the output texture.
  65265. */
  65266. get: function () {
  65267. if (this._shareOutputWithPostProcess) {
  65268. return this._shareOutputWithPostProcess.aspectRatio;
  65269. }
  65270. if (this._forcedOutputTexture) {
  65271. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65272. }
  65273. return this.width / this.height;
  65274. },
  65275. enumerable: true,
  65276. configurable: true
  65277. });
  65278. /**
  65279. * Get a value indicating if the post-process is ready to be used
  65280. * @returns true if the post-process is ready (shader is compiled)
  65281. */
  65282. PostProcess.prototype.isReady = function () {
  65283. return this._effect && this._effect.isReady();
  65284. };
  65285. /**
  65286. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65287. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65288. */
  65289. PostProcess.prototype.apply = function () {
  65290. // Check
  65291. if (!this._effect || !this._effect.isReady())
  65292. return null;
  65293. // States
  65294. this._engine.enableEffect(this._effect);
  65295. this._engine.setState(false);
  65296. this._engine.setDepthBuffer(false);
  65297. this._engine.setDepthWrite(false);
  65298. // Alpha
  65299. this._engine.setAlphaMode(this.alphaMode);
  65300. if (this.alphaConstants) {
  65301. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65302. }
  65303. // Bind the output texture of the preivous post process as the input to this post process.
  65304. var source;
  65305. if (this._shareOutputWithPostProcess) {
  65306. source = this._shareOutputWithPostProcess.inputTexture;
  65307. }
  65308. else if (this._forcedOutputTexture) {
  65309. source = this._forcedOutputTexture;
  65310. }
  65311. else {
  65312. source = this.inputTexture;
  65313. }
  65314. this._effect._bindTexture("textureSampler", source);
  65315. // Parameters
  65316. this._effect.setVector2("scale", this._scaleRatio);
  65317. this.onApplyObservable.notifyObservers(this._effect);
  65318. return this._effect;
  65319. };
  65320. PostProcess.prototype._disposeTextures = function () {
  65321. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65322. return;
  65323. }
  65324. if (this._textures.length > 0) {
  65325. for (var i = 0; i < this._textures.length; i++) {
  65326. this._engine._releaseTexture(this._textures.data[i]);
  65327. }
  65328. }
  65329. this._textures.dispose();
  65330. };
  65331. /**
  65332. * Disposes the post process.
  65333. * @param camera The camera to dispose the post process on.
  65334. */
  65335. PostProcess.prototype.dispose = function (camera) {
  65336. camera = camera || this._camera;
  65337. this._disposeTextures();
  65338. if (this._scene) {
  65339. var index_1 = this._scene.postProcesses.indexOf(this);
  65340. if (index_1 !== -1) {
  65341. this._scene.postProcesses.splice(index_1, 1);
  65342. }
  65343. }
  65344. else {
  65345. var index_2 = this._engine.postProcesses.indexOf(this);
  65346. if (index_2 !== -1) {
  65347. this._engine.postProcesses.splice(index_2, 1);
  65348. }
  65349. }
  65350. if (!camera) {
  65351. return;
  65352. }
  65353. camera.detachPostProcess(this);
  65354. var index = camera._postProcesses.indexOf(this);
  65355. if (index === 0 && camera._postProcesses.length > 0) {
  65356. var firstPostProcess = this._camera._getFirstPostProcess();
  65357. if (firstPostProcess) {
  65358. firstPostProcess.markTextureDirty();
  65359. }
  65360. }
  65361. this.onActivateObservable.clear();
  65362. this.onAfterRenderObservable.clear();
  65363. this.onApplyObservable.clear();
  65364. this.onBeforeRenderObservable.clear();
  65365. this.onSizeChangedObservable.clear();
  65366. };
  65367. return PostProcess;
  65368. }());
  65369. BABYLON.PostProcess = PostProcess;
  65370. })(BABYLON || (BABYLON = {}));
  65371. //# sourceMappingURL=babylon.postProcess.js.map
  65372. var BABYLON;
  65373. (function (BABYLON) {
  65374. var PassPostProcess = /** @class */ (function (_super) {
  65375. __extends(PassPostProcess, _super);
  65376. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65377. if (camera === void 0) { camera = null; }
  65378. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65379. if (blockCompilation === void 0) { blockCompilation = false; }
  65380. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65381. }
  65382. return PassPostProcess;
  65383. }(BABYLON.PostProcess));
  65384. BABYLON.PassPostProcess = PassPostProcess;
  65385. })(BABYLON || (BABYLON = {}));
  65386. //# sourceMappingURL=babylon.passPostProcess.js.map
  65387. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65388. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65389. s = arguments[i];
  65390. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65391. t[p] = s[p];
  65392. }
  65393. return t;
  65394. };
  65395. var BABYLON;
  65396. (function (BABYLON) {
  65397. /**
  65398. * Default implementation IShadowGenerator.
  65399. * This is the main object responsible of generating shadows in the framework.
  65400. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65401. */
  65402. var ShadowGenerator = /** @class */ (function () {
  65403. /**
  65404. * Creates a ShadowGenerator object.
  65405. * A ShadowGenerator is the required tool to use the shadows.
  65406. * Each light casting shadows needs to use its own ShadowGenerator.
  65407. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65408. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65409. * @param light The light object generating the shadows.
  65410. * @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.
  65411. */
  65412. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65413. this._bias = 0.00005;
  65414. this._normalBias = 0;
  65415. this._blurBoxOffset = 1;
  65416. this._blurScale = 2;
  65417. this._blurKernel = 1;
  65418. this._useKernelBlur = false;
  65419. this._filter = ShadowGenerator.FILTER_NONE;
  65420. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65421. this._contactHardeningLightSizeUVRatio = 0.1;
  65422. this._darkness = 0;
  65423. this._transparencyShadow = false;
  65424. /**
  65425. * Controls the extent to which the shadows fade out at the edge of the frustum
  65426. * Used only by directionals and spots
  65427. */
  65428. this.frustumEdgeFalloff = 0;
  65429. /**
  65430. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65431. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65432. * It might on the other hand introduce peter panning.
  65433. */
  65434. this.forceBackFacesOnly = false;
  65435. this._lightDirection = BABYLON.Vector3.Zero();
  65436. this._viewMatrix = BABYLON.Matrix.Zero();
  65437. this._projectionMatrix = BABYLON.Matrix.Zero();
  65438. this._transformMatrix = BABYLON.Matrix.Zero();
  65439. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65440. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65441. this._currentFaceIndex = 0;
  65442. this._currentFaceIndexCache = 0;
  65443. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65444. this._mapSize = mapSize;
  65445. this._light = light;
  65446. this._scene = light.getScene();
  65447. light._shadowGenerator = this;
  65448. // Texture type fallback from float to int if not supported.
  65449. var caps = this._scene.getEngine().getCaps();
  65450. if (!useFullFloatFirst) {
  65451. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65452. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65453. }
  65454. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65455. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65456. }
  65457. else {
  65458. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65459. }
  65460. }
  65461. else {
  65462. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65463. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65464. }
  65465. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65466. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65467. }
  65468. else {
  65469. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65470. }
  65471. }
  65472. this._initializeGenerator();
  65473. this._applyFilterValues();
  65474. }
  65475. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65476. /**
  65477. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65478. */
  65479. get: function () {
  65480. return this._bias;
  65481. },
  65482. /**
  65483. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65484. */
  65485. set: function (bias) {
  65486. this._bias = bias;
  65487. },
  65488. enumerable: true,
  65489. configurable: true
  65490. });
  65491. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65492. /**
  65493. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65494. */
  65495. get: function () {
  65496. return this._normalBias;
  65497. },
  65498. /**
  65499. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65500. */
  65501. set: function (normalBias) {
  65502. this._normalBias = normalBias;
  65503. },
  65504. enumerable: true,
  65505. configurable: true
  65506. });
  65507. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65508. /**
  65509. * Gets the blur box offset: offset applied during the blur pass.
  65510. * Only usefull if useKernelBlur = false
  65511. */
  65512. get: function () {
  65513. return this._blurBoxOffset;
  65514. },
  65515. /**
  65516. * Sets the blur box offset: offset applied during the blur pass.
  65517. * Only usefull if useKernelBlur = false
  65518. */
  65519. set: function (value) {
  65520. if (this._blurBoxOffset === value) {
  65521. return;
  65522. }
  65523. this._blurBoxOffset = value;
  65524. this._disposeBlurPostProcesses();
  65525. },
  65526. enumerable: true,
  65527. configurable: true
  65528. });
  65529. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65530. /**
  65531. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65532. * 2 means half of the size.
  65533. */
  65534. get: function () {
  65535. return this._blurScale;
  65536. },
  65537. /**
  65538. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65539. * 2 means half of the size.
  65540. */
  65541. set: function (value) {
  65542. if (this._blurScale === value) {
  65543. return;
  65544. }
  65545. this._blurScale = value;
  65546. this._disposeBlurPostProcesses();
  65547. },
  65548. enumerable: true,
  65549. configurable: true
  65550. });
  65551. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65552. /**
  65553. * Gets the blur kernel: kernel size of the blur pass.
  65554. * Only usefull if useKernelBlur = true
  65555. */
  65556. get: function () {
  65557. return this._blurKernel;
  65558. },
  65559. /**
  65560. * Sets the blur kernel: kernel size of the blur pass.
  65561. * Only usefull if useKernelBlur = true
  65562. */
  65563. set: function (value) {
  65564. if (this._blurKernel === value) {
  65565. return;
  65566. }
  65567. this._blurKernel = value;
  65568. this._disposeBlurPostProcesses();
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65574. /**
  65575. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65576. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65577. */
  65578. get: function () {
  65579. return this._useKernelBlur;
  65580. },
  65581. /**
  65582. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65583. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65584. */
  65585. set: function (value) {
  65586. if (this._useKernelBlur === value) {
  65587. return;
  65588. }
  65589. this._useKernelBlur = value;
  65590. this._disposeBlurPostProcesses();
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65596. /**
  65597. * Gets the depth scale used in ESM mode.
  65598. */
  65599. get: function () {
  65600. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65601. },
  65602. /**
  65603. * Sets the depth scale used in ESM mode.
  65604. * This can override the scale stored on the light.
  65605. */
  65606. set: function (value) {
  65607. this._depthScale = value;
  65608. },
  65609. enumerable: true,
  65610. configurable: true
  65611. });
  65612. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65613. /**
  65614. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65615. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65616. */
  65617. get: function () {
  65618. return this._filter;
  65619. },
  65620. /**
  65621. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65622. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65623. */
  65624. set: function (value) {
  65625. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65626. if (this._light.needCube()) {
  65627. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65628. this.useExponentialShadowMap = true;
  65629. return;
  65630. }
  65631. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65632. this.useCloseExponentialShadowMap = true;
  65633. return;
  65634. }
  65635. // PCF on cubemap would also be expensive
  65636. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65637. this.usePoissonSampling = true;
  65638. return;
  65639. }
  65640. }
  65641. // Weblg1 fallback for PCF.
  65642. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65643. if (this._scene.getEngine().webGLVersion === 1) {
  65644. this.usePoissonSampling = true;
  65645. return;
  65646. }
  65647. }
  65648. if (this._filter === value) {
  65649. return;
  65650. }
  65651. this._filter = value;
  65652. this._disposeBlurPostProcesses();
  65653. this._applyFilterValues();
  65654. this._light._markMeshesAsLightDirty();
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65660. /**
  65661. * Gets if the current filter is set to Poisson Sampling.
  65662. */
  65663. get: function () {
  65664. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65665. },
  65666. /**
  65667. * Sets the current filter to Poisson Sampling.
  65668. */
  65669. set: function (value) {
  65670. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65671. return;
  65672. }
  65673. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65679. /**
  65680. * Gets if the current filter is set to VSM.
  65681. * DEPRECATED. Should use useExponentialShadowMap instead.
  65682. */
  65683. get: function () {
  65684. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65685. return this.useExponentialShadowMap;
  65686. },
  65687. /**
  65688. * Sets the current filter is to VSM.
  65689. * DEPRECATED. Should use useExponentialShadowMap instead.
  65690. */
  65691. set: function (value) {
  65692. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65693. this.useExponentialShadowMap = value;
  65694. },
  65695. enumerable: true,
  65696. configurable: true
  65697. });
  65698. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65699. /**
  65700. * Gets if the current filter is set to blurred VSM.
  65701. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65702. */
  65703. get: function () {
  65704. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65705. return this.useBlurExponentialShadowMap;
  65706. },
  65707. /**
  65708. * Sets the current filter is to blurred VSM.
  65709. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65710. */
  65711. set: function (value) {
  65712. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65713. this.useBlurExponentialShadowMap = value;
  65714. },
  65715. enumerable: true,
  65716. configurable: true
  65717. });
  65718. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65719. /**
  65720. * Gets if the current filter is set to ESM.
  65721. */
  65722. get: function () {
  65723. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65724. },
  65725. /**
  65726. * Sets the current filter is to ESM.
  65727. */
  65728. set: function (value) {
  65729. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65730. return;
  65731. }
  65732. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65733. },
  65734. enumerable: true,
  65735. configurable: true
  65736. });
  65737. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65738. /**
  65739. * Gets if the current filter is set to filtered ESM.
  65740. */
  65741. get: function () {
  65742. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65743. },
  65744. /**
  65745. * Gets if the current filter is set to filtered ESM.
  65746. */
  65747. set: function (value) {
  65748. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65749. return;
  65750. }
  65751. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65752. },
  65753. enumerable: true,
  65754. configurable: true
  65755. });
  65756. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65757. /**
  65758. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65759. * exponential to prevent steep falloff artifacts).
  65760. */
  65761. get: function () {
  65762. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65763. },
  65764. /**
  65765. * Sets the current filter to "close ESM" (using the inverse of the
  65766. * exponential to prevent steep falloff artifacts).
  65767. */
  65768. set: function (value) {
  65769. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65770. return;
  65771. }
  65772. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65773. },
  65774. enumerable: true,
  65775. configurable: true
  65776. });
  65777. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65778. /**
  65779. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65780. * exponential to prevent steep falloff artifacts).
  65781. */
  65782. get: function () {
  65783. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65784. },
  65785. /**
  65786. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65787. * exponential to prevent steep falloff artifacts).
  65788. */
  65789. set: function (value) {
  65790. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65791. return;
  65792. }
  65793. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65794. },
  65795. enumerable: true,
  65796. configurable: true
  65797. });
  65798. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65799. /**
  65800. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65801. */
  65802. get: function () {
  65803. return this.filter === ShadowGenerator.FILTER_PCF;
  65804. },
  65805. /**
  65806. * Sets the current filter to "PCF" (percentage closer filtering).
  65807. */
  65808. set: function (value) {
  65809. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65810. return;
  65811. }
  65812. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65813. },
  65814. enumerable: true,
  65815. configurable: true
  65816. });
  65817. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65818. /**
  65819. * Gets the PCF or PCSS Quality.
  65820. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65821. */
  65822. get: function () {
  65823. return this._filteringQuality;
  65824. },
  65825. /**
  65826. * Sets the PCF or PCSS Quality.
  65827. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65828. */
  65829. set: function (filteringQuality) {
  65830. this._filteringQuality = filteringQuality;
  65831. },
  65832. enumerable: true,
  65833. configurable: true
  65834. });
  65835. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65836. /**
  65837. * Gets if the current filter is set to "PCSS" (contact hardening).
  65838. */
  65839. get: function () {
  65840. return this.filter === ShadowGenerator.FILTER_PCSS;
  65841. },
  65842. /**
  65843. * Sets the current filter to "PCSS" (contact hardening).
  65844. */
  65845. set: function (value) {
  65846. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65847. return;
  65848. }
  65849. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65850. },
  65851. enumerable: true,
  65852. configurable: true
  65853. });
  65854. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65855. /**
  65856. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65857. * Using a ratio helps keeping shape stability independently of the map size.
  65858. *
  65859. * It does not account for the light projection as it was having too much
  65860. * instability during the light setup or during light position changes.
  65861. *
  65862. * Only valid if useContactHardeningShadow is true.
  65863. */
  65864. get: function () {
  65865. return this._contactHardeningLightSizeUVRatio;
  65866. },
  65867. /**
  65868. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65869. * Using a ratio helps keeping shape stability independently of the map size.
  65870. *
  65871. * It does not account for the light projection as it was having too much
  65872. * instability during the light setup or during light position changes.
  65873. *
  65874. * Only valid if useContactHardeningShadow is true.
  65875. */
  65876. set: function (contactHardeningLightSizeUVRatio) {
  65877. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65878. },
  65879. enumerable: true,
  65880. configurable: true
  65881. });
  65882. /**
  65883. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65884. * 0 means strongest and 1 would means no shadow.
  65885. * @returns the darkness.
  65886. */
  65887. ShadowGenerator.prototype.getDarkness = function () {
  65888. return this._darkness;
  65889. };
  65890. /**
  65891. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65892. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65893. * @returns the shadow generator allowing fluent coding.
  65894. */
  65895. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65896. if (darkness >= 1.0)
  65897. this._darkness = 1.0;
  65898. else if (darkness <= 0.0)
  65899. this._darkness = 0.0;
  65900. else
  65901. this._darkness = darkness;
  65902. return this;
  65903. };
  65904. /**
  65905. * Sets the ability to have transparent shadow (boolean).
  65906. * @param transparent True if transparent else False
  65907. * @returns the shadow generator allowing fluent coding
  65908. */
  65909. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65910. this._transparencyShadow = transparent;
  65911. return this;
  65912. };
  65913. /**
  65914. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65915. * @returns The render target texture if present otherwise, null
  65916. */
  65917. ShadowGenerator.prototype.getShadowMap = function () {
  65918. return this._shadowMap;
  65919. };
  65920. /**
  65921. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65922. * @returns The render target texture if the shadow map is present otherwise, null
  65923. */
  65924. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65925. if (this._shadowMap2) {
  65926. return this._shadowMap2;
  65927. }
  65928. return this._shadowMap;
  65929. };
  65930. /**
  65931. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65932. * @param mesh Mesh to add
  65933. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65934. * @returns the Shadow Generator itself
  65935. */
  65936. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65937. if (includeDescendants === void 0) { includeDescendants = true; }
  65938. if (!this._shadowMap) {
  65939. return this;
  65940. }
  65941. if (!this._shadowMap.renderList) {
  65942. this._shadowMap.renderList = [];
  65943. }
  65944. this._shadowMap.renderList.push(mesh);
  65945. if (includeDescendants) {
  65946. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65947. }
  65948. return this;
  65949. var _a;
  65950. };
  65951. /**
  65952. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65953. * @param mesh Mesh to remove
  65954. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65955. * @returns the Shadow Generator itself
  65956. */
  65957. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65958. if (includeDescendants === void 0) { includeDescendants = true; }
  65959. if (!this._shadowMap || !this._shadowMap.renderList) {
  65960. return this;
  65961. }
  65962. var index = this._shadowMap.renderList.indexOf(mesh);
  65963. if (index !== -1) {
  65964. this._shadowMap.renderList.splice(index, 1);
  65965. }
  65966. if (includeDescendants) {
  65967. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65968. var child = _a[_i];
  65969. this.removeShadowCaster(child);
  65970. }
  65971. }
  65972. return this;
  65973. };
  65974. /**
  65975. * Returns the associated light object.
  65976. * @returns the light generating the shadow
  65977. */
  65978. ShadowGenerator.prototype.getLight = function () {
  65979. return this._light;
  65980. };
  65981. ShadowGenerator.prototype._initializeGenerator = function () {
  65982. this._light._markMeshesAsLightDirty();
  65983. this._initializeShadowMap();
  65984. };
  65985. ShadowGenerator.prototype._initializeShadowMap = function () {
  65986. var _this = this;
  65987. // Render target
  65988. var engine = this._scene.getEngine();
  65989. if (engine.webGLVersion > 1) {
  65990. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65991. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65992. }
  65993. else {
  65994. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65995. }
  65996. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65997. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65998. this._shadowMap.anisotropicFilteringLevel = 1;
  65999. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66000. this._shadowMap.renderParticles = false;
  66001. this._shadowMap.ignoreCameraViewport = true;
  66002. // Record Face Index before render.
  66003. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66004. _this._currentFaceIndex = faceIndex;
  66005. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66006. engine.setColorWrite(false);
  66007. }
  66008. });
  66009. // Custom render function.
  66010. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66011. // Blur if required afer render.
  66012. this._shadowMap.onAfterUnbindObservable.add(function () {
  66013. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66014. engine.setColorWrite(true);
  66015. }
  66016. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66017. return;
  66018. }
  66019. var shadowMap = _this.getShadowMapForRendering();
  66020. if (shadowMap) {
  66021. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66022. }
  66023. });
  66024. // Clear according to the chosen filter.
  66025. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66026. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66027. this._shadowMap.onClearObservable.add(function (engine) {
  66028. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66029. engine.clear(clearOne, false, true, false);
  66030. }
  66031. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66032. engine.clear(clearZero, true, true, false);
  66033. }
  66034. else {
  66035. engine.clear(clearOne, true, true, false);
  66036. }
  66037. });
  66038. };
  66039. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66040. var _this = this;
  66041. var engine = this._scene.getEngine();
  66042. var targetSize = this._mapSize / this.blurScale;
  66043. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66044. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66045. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66046. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66047. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66048. }
  66049. if (this.useKernelBlur) {
  66050. 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);
  66051. this._kernelBlurXPostprocess.width = targetSize;
  66052. this._kernelBlurXPostprocess.height = targetSize;
  66053. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66054. effect.setTexture("textureSampler", _this._shadowMap);
  66055. });
  66056. 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);
  66057. this._kernelBlurXPostprocess.autoClear = false;
  66058. this._kernelBlurYPostprocess.autoClear = false;
  66059. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66060. this._kernelBlurXPostprocess.packedFloat = true;
  66061. this._kernelBlurYPostprocess.packedFloat = true;
  66062. }
  66063. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66064. }
  66065. else {
  66066. 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);
  66067. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66068. effect.setFloat2("screenSize", targetSize, targetSize);
  66069. effect.setTexture("textureSampler", _this._shadowMap);
  66070. });
  66071. this._boxBlurPostprocess.autoClear = false;
  66072. this._blurPostProcesses = [this._boxBlurPostprocess];
  66073. }
  66074. };
  66075. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66076. var index;
  66077. var engine = this._scene.getEngine();
  66078. if (depthOnlySubMeshes.length) {
  66079. engine.setColorWrite(false);
  66080. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66081. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66082. }
  66083. engine.setColorWrite(true);
  66084. }
  66085. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66086. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66087. }
  66088. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66089. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66090. }
  66091. if (this._transparencyShadow) {
  66092. for (index = 0; index < transparentSubMeshes.length; index++) {
  66093. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66094. }
  66095. }
  66096. };
  66097. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66098. var _this = this;
  66099. var mesh = subMesh.getRenderingMesh();
  66100. var scene = this._scene;
  66101. var engine = scene.getEngine();
  66102. var material = subMesh.getMaterial();
  66103. if (!material) {
  66104. return;
  66105. }
  66106. // Culling
  66107. engine.setState(material.backFaceCulling);
  66108. // Managing instances
  66109. var batch = mesh._getInstancesRenderList(subMesh._id);
  66110. if (batch.mustReturn) {
  66111. return;
  66112. }
  66113. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66114. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66115. engine.enableEffect(this._effect);
  66116. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66117. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66118. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66119. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66120. this._effect.setVector3("lightData", this._cachedDirection);
  66121. }
  66122. else {
  66123. this._effect.setVector3("lightData", this._cachedPosition);
  66124. }
  66125. if (scene.activeCamera) {
  66126. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66127. }
  66128. // Alpha test
  66129. if (material && material.needAlphaTesting()) {
  66130. var alphaTexture = material.getAlphaTestTexture();
  66131. if (alphaTexture) {
  66132. this._effect.setTexture("diffuseSampler", alphaTexture);
  66133. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66134. }
  66135. }
  66136. // Bones
  66137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66138. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66139. }
  66140. // Morph targets
  66141. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66142. if (this.forceBackFacesOnly) {
  66143. engine.setState(true, 0, false, true);
  66144. }
  66145. // Draw
  66146. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66147. if (this.forceBackFacesOnly) {
  66148. engine.setState(true, 0, false, false);
  66149. }
  66150. }
  66151. else {
  66152. // Need to reset refresh rate of the shadowMap
  66153. if (this._shadowMap) {
  66154. this._shadowMap.resetRefreshCounter();
  66155. }
  66156. }
  66157. };
  66158. ShadowGenerator.prototype._applyFilterValues = function () {
  66159. if (!this._shadowMap) {
  66160. return;
  66161. }
  66162. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66163. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66164. }
  66165. else {
  66166. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66167. }
  66168. };
  66169. /**
  66170. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66171. * @param onCompiled Callback triggered at the and of the effects compilation
  66172. * @param options Sets of optional options forcing the compilation with different modes
  66173. */
  66174. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66175. var _this = this;
  66176. var localOptions = __assign({ useInstances: false }, options);
  66177. var shadowMap = this.getShadowMap();
  66178. if (!shadowMap) {
  66179. if (onCompiled) {
  66180. onCompiled(this);
  66181. }
  66182. return;
  66183. }
  66184. var renderList = shadowMap.renderList;
  66185. if (!renderList) {
  66186. if (onCompiled) {
  66187. onCompiled(this);
  66188. }
  66189. return;
  66190. }
  66191. var subMeshes = new Array();
  66192. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66193. var mesh = renderList_1[_i];
  66194. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66195. }
  66196. if (subMeshes.length === 0) {
  66197. if (onCompiled) {
  66198. onCompiled(this);
  66199. }
  66200. return;
  66201. }
  66202. var currentIndex = 0;
  66203. var checkReady = function () {
  66204. if (!_this._scene || !_this._scene.getEngine()) {
  66205. return;
  66206. }
  66207. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66208. currentIndex++;
  66209. if (currentIndex >= subMeshes.length) {
  66210. if (onCompiled) {
  66211. onCompiled(_this);
  66212. }
  66213. return;
  66214. }
  66215. }
  66216. setTimeout(checkReady, 16);
  66217. };
  66218. checkReady();
  66219. };
  66220. /**
  66221. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66222. * @param options Sets of optional options forcing the compilation with different modes
  66223. * @returns A promise that resolves when the compilation completes
  66224. */
  66225. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66226. var _this = this;
  66227. return new Promise(function (resolve) {
  66228. _this.forceCompilation(function () {
  66229. resolve();
  66230. }, options);
  66231. });
  66232. };
  66233. /**
  66234. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66235. * @param subMesh The submesh we want to render in the shadow map
  66236. * @param useInstances Defines wether will draw in the map using instances
  66237. * @returns true if ready otherwise, false
  66238. */
  66239. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66240. var defines = [];
  66241. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66242. defines.push("#define FLOAT");
  66243. }
  66244. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66245. defines.push("#define ESM");
  66246. }
  66247. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66248. defines.push("#define DEPTHTEXTURE");
  66249. }
  66250. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66251. var mesh = subMesh.getMesh();
  66252. var material = subMesh.getMaterial();
  66253. // Normal bias.
  66254. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66255. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66256. defines.push("#define NORMAL");
  66257. if (mesh.nonUniformScaling) {
  66258. defines.push("#define NONUNIFORMSCALING");
  66259. }
  66260. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66261. defines.push("#define DIRECTIONINLIGHTDATA");
  66262. }
  66263. }
  66264. // Alpha test
  66265. if (material && material.needAlphaTesting()) {
  66266. var alphaTexture = material.getAlphaTestTexture();
  66267. if (alphaTexture) {
  66268. defines.push("#define ALPHATEST");
  66269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66270. attribs.push(BABYLON.VertexBuffer.UVKind);
  66271. defines.push("#define UV1");
  66272. }
  66273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66274. if (alphaTexture.coordinatesIndex === 1) {
  66275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66276. defines.push("#define UV2");
  66277. }
  66278. }
  66279. }
  66280. }
  66281. // Bones
  66282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66285. if (mesh.numBoneInfluencers > 4) {
  66286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66288. }
  66289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66290. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66291. }
  66292. else {
  66293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66294. }
  66295. // Morph targets
  66296. var manager = mesh.morphTargetManager;
  66297. var morphInfluencers = 0;
  66298. if (manager) {
  66299. if (manager.numInfluencers > 0) {
  66300. defines.push("#define MORPHTARGETS");
  66301. morphInfluencers = manager.numInfluencers;
  66302. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66303. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66304. }
  66305. }
  66306. // Instances
  66307. if (useInstances) {
  66308. defines.push("#define INSTANCES");
  66309. attribs.push("world0");
  66310. attribs.push("world1");
  66311. attribs.push("world2");
  66312. attribs.push("world3");
  66313. }
  66314. // Get correct effect
  66315. var join = defines.join("\n");
  66316. if (this._cachedDefines !== join) {
  66317. this._cachedDefines = join;
  66318. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66319. }
  66320. if (!this._effect.isReady()) {
  66321. return false;
  66322. }
  66323. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66324. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66325. this._initializeBlurRTTAndPostProcesses();
  66326. }
  66327. }
  66328. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66329. return false;
  66330. }
  66331. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66332. return false;
  66333. }
  66334. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66335. return false;
  66336. }
  66337. return true;
  66338. };
  66339. /**
  66340. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66341. * @param defines Defines of the material we want to update
  66342. * @param lightIndex Index of the light in the enabled light list of the material
  66343. */
  66344. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66345. var scene = this._scene;
  66346. var light = this._light;
  66347. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66348. return;
  66349. }
  66350. defines["SHADOW" + lightIndex] = true;
  66351. if (this.useContactHardeningShadow) {
  66352. defines["SHADOWPCSS" + lightIndex] = true;
  66353. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66354. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66355. }
  66356. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66357. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66358. }
  66359. // else default to high.
  66360. }
  66361. if (this.usePercentageCloserFiltering) {
  66362. defines["SHADOWPCF" + lightIndex] = true;
  66363. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66364. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66365. }
  66366. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66367. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66368. }
  66369. // else default to high.
  66370. }
  66371. else if (this.usePoissonSampling) {
  66372. defines["SHADOWPOISSON" + lightIndex] = true;
  66373. }
  66374. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66375. defines["SHADOWESM" + lightIndex] = true;
  66376. }
  66377. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66378. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66379. }
  66380. if (light.needCube()) {
  66381. defines["SHADOWCUBE" + lightIndex] = true;
  66382. }
  66383. };
  66384. /**
  66385. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66386. * defined in the generator but impacting the effect).
  66387. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66388. * @param effect The effect we are binfing the information for
  66389. */
  66390. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66391. var light = this._light;
  66392. var scene = this._scene;
  66393. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66394. return;
  66395. }
  66396. var camera = scene.activeCamera;
  66397. if (!camera) {
  66398. return;
  66399. }
  66400. var shadowMap = this.getShadowMap();
  66401. if (!shadowMap) {
  66402. return;
  66403. }
  66404. if (!light.needCube()) {
  66405. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66406. }
  66407. // Only PCF uses depth stencil texture.
  66408. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66409. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66410. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66411. }
  66412. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66413. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66414. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66415. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66416. }
  66417. else {
  66418. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66419. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66420. }
  66421. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66422. };
  66423. /**
  66424. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66425. * (eq to shadow prjection matrix * light transform matrix)
  66426. * @returns The transform matrix used to create the shadow map
  66427. */
  66428. ShadowGenerator.prototype.getTransformMatrix = function () {
  66429. var scene = this._scene;
  66430. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66431. return this._transformMatrix;
  66432. }
  66433. this._currentRenderID = scene.getRenderId();
  66434. this._currentFaceIndexCache = this._currentFaceIndex;
  66435. var lightPosition = this._light.position;
  66436. if (this._light.computeTransformedInformation()) {
  66437. lightPosition = this._light.transformedPosition;
  66438. }
  66439. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66440. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66441. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66442. }
  66443. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66444. this._cachedPosition.copyFrom(lightPosition);
  66445. this._cachedDirection.copyFrom(this._lightDirection);
  66446. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66447. var shadowMap = this.getShadowMap();
  66448. if (shadowMap) {
  66449. var renderList = shadowMap.renderList;
  66450. if (renderList) {
  66451. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66452. }
  66453. }
  66454. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66455. }
  66456. return this._transformMatrix;
  66457. };
  66458. /**
  66459. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66460. * Cube and 2D textures for instance.
  66461. */
  66462. ShadowGenerator.prototype.recreateShadowMap = function () {
  66463. var shadowMap = this._shadowMap;
  66464. if (!shadowMap) {
  66465. return;
  66466. }
  66467. // Track render list.
  66468. var renderList = shadowMap.renderList;
  66469. // Clean up existing data.
  66470. this._disposeRTTandPostProcesses();
  66471. // Reinitializes.
  66472. this._initializeGenerator();
  66473. // Reaffect the filter to ensure a correct fallback if necessary.
  66474. this.filter = this.filter;
  66475. // Reaffect the filter.
  66476. this._applyFilterValues();
  66477. // Reaffect Render List.
  66478. this._shadowMap.renderList = renderList;
  66479. };
  66480. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66481. if (this._shadowMap2) {
  66482. this._shadowMap2.dispose();
  66483. this._shadowMap2 = null;
  66484. }
  66485. if (this._boxBlurPostprocess) {
  66486. this._boxBlurPostprocess.dispose();
  66487. this._boxBlurPostprocess = null;
  66488. }
  66489. if (this._kernelBlurXPostprocess) {
  66490. this._kernelBlurXPostprocess.dispose();
  66491. this._kernelBlurXPostprocess = null;
  66492. }
  66493. if (this._kernelBlurYPostprocess) {
  66494. this._kernelBlurYPostprocess.dispose();
  66495. this._kernelBlurYPostprocess = null;
  66496. }
  66497. this._blurPostProcesses = [];
  66498. };
  66499. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66500. if (this._shadowMap) {
  66501. this._shadowMap.dispose();
  66502. this._shadowMap = null;
  66503. }
  66504. this._disposeBlurPostProcesses();
  66505. };
  66506. /**
  66507. * Disposes the ShadowGenerator.
  66508. * Returns nothing.
  66509. */
  66510. ShadowGenerator.prototype.dispose = function () {
  66511. this._disposeRTTandPostProcesses();
  66512. if (this._light) {
  66513. this._light._shadowGenerator = null;
  66514. this._light._markMeshesAsLightDirty();
  66515. }
  66516. };
  66517. /**
  66518. * Serializes the shadow generator setup to a json object.
  66519. * @returns The serialized JSON object
  66520. */
  66521. ShadowGenerator.prototype.serialize = function () {
  66522. var serializationObject = {};
  66523. var shadowMap = this.getShadowMap();
  66524. if (!shadowMap) {
  66525. return serializationObject;
  66526. }
  66527. serializationObject.lightId = this._light.id;
  66528. serializationObject.mapSize = shadowMap.getRenderSize();
  66529. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66530. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66531. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66532. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66533. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66534. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66535. serializationObject.depthScale = this.depthScale;
  66536. serializationObject.darkness = this.getDarkness();
  66537. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66538. serializationObject.blurKernel = this.blurKernel;
  66539. serializationObject.blurScale = this.blurScale;
  66540. serializationObject.useKernelBlur = this.useKernelBlur;
  66541. serializationObject.transparencyShadow = this._transparencyShadow;
  66542. serializationObject.bias = this.bias;
  66543. serializationObject.normalBias = this.normalBias;
  66544. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66545. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66546. serializationObject.filteringQuality = this.filteringQuality;
  66547. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66548. serializationObject.renderList = [];
  66549. if (shadowMap.renderList) {
  66550. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66551. var mesh = shadowMap.renderList[meshIndex];
  66552. serializationObject.renderList.push(mesh.id);
  66553. }
  66554. }
  66555. return serializationObject;
  66556. };
  66557. /**
  66558. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66559. * @param parsedShadowGenerator The JSON object to parse
  66560. * @param scene The scene to create the shadow map for
  66561. * @returns The parsed shadow generator
  66562. */
  66563. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66564. //casting to point light, as light is missing the position attr and typescript complains.
  66565. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66566. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66567. var shadowMap = shadowGenerator.getShadowMap();
  66568. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66569. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66570. meshes.forEach(function (mesh) {
  66571. if (!shadowMap) {
  66572. return;
  66573. }
  66574. if (!shadowMap.renderList) {
  66575. shadowMap.renderList = [];
  66576. }
  66577. shadowMap.renderList.push(mesh);
  66578. });
  66579. }
  66580. if (parsedShadowGenerator.usePoissonSampling) {
  66581. shadowGenerator.usePoissonSampling = true;
  66582. }
  66583. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66584. shadowGenerator.useExponentialShadowMap = true;
  66585. }
  66586. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66587. shadowGenerator.useBlurExponentialShadowMap = true;
  66588. }
  66589. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66590. shadowGenerator.useCloseExponentialShadowMap = true;
  66591. }
  66592. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66593. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66594. }
  66595. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66596. shadowGenerator.usePercentageCloserFiltering = true;
  66597. }
  66598. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66599. shadowGenerator.useContactHardeningShadow = true;
  66600. }
  66601. if (parsedShadowGenerator.filteringQuality) {
  66602. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66603. }
  66604. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66605. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66606. }
  66607. // Backward compat
  66608. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66609. shadowGenerator.useExponentialShadowMap = true;
  66610. }
  66611. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66612. shadowGenerator.useBlurExponentialShadowMap = true;
  66613. }
  66614. if (parsedShadowGenerator.depthScale) {
  66615. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66616. }
  66617. if (parsedShadowGenerator.blurScale) {
  66618. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66619. }
  66620. if (parsedShadowGenerator.blurBoxOffset) {
  66621. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66622. }
  66623. if (parsedShadowGenerator.useKernelBlur) {
  66624. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66625. }
  66626. if (parsedShadowGenerator.blurKernel) {
  66627. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66628. }
  66629. if (parsedShadowGenerator.bias !== undefined) {
  66630. shadowGenerator.bias = parsedShadowGenerator.bias;
  66631. }
  66632. if (parsedShadowGenerator.normalBias !== undefined) {
  66633. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66634. }
  66635. if (parsedShadowGenerator.darkness) {
  66636. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66637. }
  66638. if (parsedShadowGenerator.transparencyShadow) {
  66639. shadowGenerator.setTransparencyShadow(true);
  66640. }
  66641. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66642. return shadowGenerator;
  66643. };
  66644. /**
  66645. * Shadow generator mode None: no filtering applied.
  66646. */
  66647. ShadowGenerator.FILTER_NONE = 0;
  66648. /**
  66649. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66650. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66651. */
  66652. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66653. /**
  66654. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66655. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66656. */
  66657. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66658. /**
  66659. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66660. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66661. */
  66662. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66663. /**
  66664. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66665. * edge artifacts on steep falloff.
  66666. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66667. */
  66668. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66669. /**
  66670. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66671. * edge artifacts on steep falloff.
  66672. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66673. */
  66674. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66675. /**
  66676. * Shadow generator mode PCF: Percentage Closer Filtering
  66677. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66678. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66679. */
  66680. ShadowGenerator.FILTER_PCF = 6;
  66681. /**
  66682. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66683. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66684. * Contact Hardening
  66685. */
  66686. ShadowGenerator.FILTER_PCSS = 7;
  66687. /**
  66688. * Reserved for PCF and PCSS
  66689. * Highest Quality.
  66690. *
  66691. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66692. *
  66693. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66694. */
  66695. ShadowGenerator.QUALITY_HIGH = 0;
  66696. /**
  66697. * Reserved for PCF and PCSS
  66698. * Good tradeoff for quality/perf cross devices
  66699. *
  66700. * Execute PCF on a 3*3 kernel.
  66701. *
  66702. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66703. */
  66704. ShadowGenerator.QUALITY_MEDIUM = 1;
  66705. /**
  66706. * Reserved for PCF and PCSS
  66707. * The lowest quality but the fastest.
  66708. *
  66709. * Execute PCF on a 1*1 kernel.
  66710. *
  66711. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66712. */
  66713. ShadowGenerator.QUALITY_LOW = 2;
  66714. return ShadowGenerator;
  66715. }());
  66716. BABYLON.ShadowGenerator = ShadowGenerator;
  66717. })(BABYLON || (BABYLON = {}));
  66718. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66719. var BABYLON;
  66720. (function (BABYLON) {
  66721. var DefaultLoadingScreen = /** @class */ (function () {
  66722. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66723. if (_loadingText === void 0) { _loadingText = ""; }
  66724. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66725. var _this = this;
  66726. this._renderingCanvas = _renderingCanvas;
  66727. this._loadingText = _loadingText;
  66728. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66729. // Resize
  66730. this._resizeLoadingUI = function () {
  66731. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66732. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66733. if (!_this._loadingDiv) {
  66734. return;
  66735. }
  66736. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66737. _this._loadingDiv.style.left = canvasRect.left + "px";
  66738. _this._loadingDiv.style.top = canvasRect.top + "px";
  66739. _this._loadingDiv.style.width = canvasRect.width + "px";
  66740. _this._loadingDiv.style.height = canvasRect.height + "px";
  66741. };
  66742. }
  66743. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66744. if (this._loadingDiv) {
  66745. // Do not add a loading screen if there is already one
  66746. return;
  66747. }
  66748. this._loadingDiv = document.createElement("div");
  66749. this._loadingDiv.id = "babylonjsLoadingDiv";
  66750. this._loadingDiv.style.opacity = "0";
  66751. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66752. this._loadingDiv.style.pointerEvents = "none";
  66753. // Loading text
  66754. this._loadingTextDiv = document.createElement("div");
  66755. this._loadingTextDiv.style.position = "absolute";
  66756. this._loadingTextDiv.style.left = "0";
  66757. this._loadingTextDiv.style.top = "50%";
  66758. this._loadingTextDiv.style.marginTop = "80px";
  66759. this._loadingTextDiv.style.width = "100%";
  66760. this._loadingTextDiv.style.height = "20px";
  66761. this._loadingTextDiv.style.fontFamily = "Arial";
  66762. this._loadingTextDiv.style.fontSize = "14px";
  66763. this._loadingTextDiv.style.color = "white";
  66764. this._loadingTextDiv.style.textAlign = "center";
  66765. this._loadingTextDiv.innerHTML = "Loading";
  66766. this._loadingDiv.appendChild(this._loadingTextDiv);
  66767. //set the predefined text
  66768. this._loadingTextDiv.innerHTML = this._loadingText;
  66769. // Generating keyframes
  66770. var style = document.createElement('style');
  66771. style.type = 'text/css';
  66772. 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 }";
  66773. style.innerHTML = keyFrames;
  66774. document.getElementsByTagName('head')[0].appendChild(style);
  66775. // Loading img
  66776. var imgBack = new Image();
  66777. 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";
  66778. imgBack.style.position = "absolute";
  66779. imgBack.style.left = "50%";
  66780. imgBack.style.top = "50%";
  66781. imgBack.style.marginLeft = "-60px";
  66782. imgBack.style.marginTop = "-60px";
  66783. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66784. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66785. imgBack.style.transformOrigin = "50% 50%";
  66786. imgBack.style.webkitTransformOrigin = "50% 50%";
  66787. this._loadingDiv.appendChild(imgBack);
  66788. this._resizeLoadingUI();
  66789. window.addEventListener("resize", this._resizeLoadingUI);
  66790. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66791. document.body.appendChild(this._loadingDiv);
  66792. this._loadingDiv.style.opacity = "1";
  66793. };
  66794. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66795. var _this = this;
  66796. if (!this._loadingDiv) {
  66797. return;
  66798. }
  66799. var onTransitionEnd = function () {
  66800. if (!_this._loadingDiv) {
  66801. return;
  66802. }
  66803. document.body.removeChild(_this._loadingDiv);
  66804. window.removeEventListener("resize", _this._resizeLoadingUI);
  66805. _this._loadingDiv = null;
  66806. };
  66807. this._loadingDiv.style.opacity = "0";
  66808. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66809. };
  66810. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66811. set: function (text) {
  66812. this._loadingText = text;
  66813. if (this._loadingTextDiv) {
  66814. this._loadingTextDiv.innerHTML = this._loadingText;
  66815. }
  66816. },
  66817. enumerable: true,
  66818. configurable: true
  66819. });
  66820. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66821. get: function () {
  66822. return this._loadingDivBackgroundColor;
  66823. },
  66824. set: function (color) {
  66825. this._loadingDivBackgroundColor = color;
  66826. if (!this._loadingDiv) {
  66827. return;
  66828. }
  66829. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66830. },
  66831. enumerable: true,
  66832. configurable: true
  66833. });
  66834. return DefaultLoadingScreen;
  66835. }());
  66836. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66837. })(BABYLON || (BABYLON = {}));
  66838. //# sourceMappingURL=babylon.loadingScreen.js.map
  66839. var BABYLON;
  66840. (function (BABYLON) {
  66841. var SceneLoaderProgressEvent = /** @class */ (function () {
  66842. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66843. this.lengthComputable = lengthComputable;
  66844. this.loaded = loaded;
  66845. this.total = total;
  66846. }
  66847. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66848. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66849. };
  66850. return SceneLoaderProgressEvent;
  66851. }());
  66852. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66853. var SceneLoader = /** @class */ (function () {
  66854. function SceneLoader() {
  66855. }
  66856. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66857. get: function () {
  66858. return 0;
  66859. },
  66860. enumerable: true,
  66861. configurable: true
  66862. });
  66863. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66864. get: function () {
  66865. return 1;
  66866. },
  66867. enumerable: true,
  66868. configurable: true
  66869. });
  66870. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66871. get: function () {
  66872. return 2;
  66873. },
  66874. enumerable: true,
  66875. configurable: true
  66876. });
  66877. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66878. get: function () {
  66879. return 3;
  66880. },
  66881. enumerable: true,
  66882. configurable: true
  66883. });
  66884. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66885. get: function () {
  66886. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66887. },
  66888. set: function (value) {
  66889. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66890. },
  66891. enumerable: true,
  66892. configurable: true
  66893. });
  66894. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66895. get: function () {
  66896. return SceneLoader._ShowLoadingScreen;
  66897. },
  66898. set: function (value) {
  66899. SceneLoader._ShowLoadingScreen = value;
  66900. },
  66901. enumerable: true,
  66902. configurable: true
  66903. });
  66904. Object.defineProperty(SceneLoader, "loggingLevel", {
  66905. get: function () {
  66906. return SceneLoader._loggingLevel;
  66907. },
  66908. set: function (value) {
  66909. SceneLoader._loggingLevel = value;
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66915. get: function () {
  66916. return SceneLoader._CleanBoneMatrixWeights;
  66917. },
  66918. set: function (value) {
  66919. SceneLoader._CleanBoneMatrixWeights = value;
  66920. },
  66921. enumerable: true,
  66922. configurable: true
  66923. });
  66924. SceneLoader._getDefaultPlugin = function () {
  66925. return SceneLoader._registeredPlugins[".babylon"];
  66926. };
  66927. SceneLoader._getPluginForExtension = function (extension) {
  66928. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66929. if (registeredPlugin) {
  66930. return registeredPlugin;
  66931. }
  66932. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66933. return SceneLoader._getDefaultPlugin();
  66934. };
  66935. SceneLoader._getPluginForDirectLoad = function (data) {
  66936. for (var extension in SceneLoader._registeredPlugins) {
  66937. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66938. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66939. return SceneLoader._registeredPlugins[extension];
  66940. }
  66941. }
  66942. return SceneLoader._getDefaultPlugin();
  66943. };
  66944. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66945. if (sceneFilename.name) {
  66946. sceneFilename = sceneFilename.name;
  66947. }
  66948. var queryStringPosition = sceneFilename.indexOf("?");
  66949. if (queryStringPosition !== -1) {
  66950. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66951. }
  66952. var dotPosition = sceneFilename.lastIndexOf(".");
  66953. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66954. return SceneLoader._getPluginForExtension(extension);
  66955. };
  66956. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66957. SceneLoader._getDirectLoad = function (sceneFilename) {
  66958. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66959. return sceneFilename.substr(5);
  66960. }
  66961. return null;
  66962. };
  66963. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66964. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66965. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66966. var plugin;
  66967. if (registeredPlugin.plugin.createPlugin) {
  66968. plugin = registeredPlugin.plugin.createPlugin();
  66969. }
  66970. else {
  66971. plugin = registeredPlugin.plugin;
  66972. }
  66973. var useArrayBuffer = registeredPlugin.isBinary;
  66974. var database;
  66975. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66976. var dataCallback = function (data, responseURL) {
  66977. if (scene.isDisposed) {
  66978. onError("Scene has been disposed");
  66979. return;
  66980. }
  66981. scene.database = database;
  66982. onSuccess(plugin, data, responseURL);
  66983. };
  66984. var request = null;
  66985. var pluginDisposed = false;
  66986. var onDisposeObservable = plugin.onDisposeObservable;
  66987. if (onDisposeObservable) {
  66988. onDisposeObservable.add(function () {
  66989. pluginDisposed = true;
  66990. if (request) {
  66991. request.abort();
  66992. request = null;
  66993. }
  66994. onDispose();
  66995. });
  66996. }
  66997. var manifestChecked = function () {
  66998. if (pluginDisposed) {
  66999. return;
  67000. }
  67001. var url = rootUrl + sceneFilename;
  67002. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67003. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67004. } : undefined, database, useArrayBuffer, function (request, exception) {
  67005. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67006. });
  67007. };
  67008. if (directLoad) {
  67009. dataCallback(directLoad);
  67010. return plugin;
  67011. }
  67012. if (rootUrl.indexOf("file:") === -1) {
  67013. var engine = scene.getEngine();
  67014. var canUseOfflineSupport = engine.enableOfflineSupport;
  67015. if (canUseOfflineSupport) {
  67016. // Also check for exceptions
  67017. var exceptionFound = false;
  67018. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67019. var regex = _a[_i];
  67020. if (regex.test(rootUrl + sceneFilename)) {
  67021. exceptionFound = true;
  67022. break;
  67023. }
  67024. }
  67025. canUseOfflineSupport = !exceptionFound;
  67026. }
  67027. if (canUseOfflineSupport) {
  67028. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67029. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67030. }
  67031. else {
  67032. manifestChecked();
  67033. }
  67034. }
  67035. // Loading file from disk via input file or drag'n'drop
  67036. else {
  67037. var fileOrString = sceneFilename;
  67038. if (fileOrString.name) { // File
  67039. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67040. }
  67041. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67042. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67043. }
  67044. else {
  67045. onError("Unable to find file named " + sceneFilename);
  67046. }
  67047. }
  67048. return plugin;
  67049. };
  67050. // Public functions
  67051. SceneLoader.GetPluginForExtension = function (extension) {
  67052. return SceneLoader._getPluginForExtension(extension).plugin;
  67053. };
  67054. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67055. return !!SceneLoader._registeredPlugins[extension];
  67056. };
  67057. SceneLoader.RegisterPlugin = function (plugin) {
  67058. if (typeof plugin.extensions === "string") {
  67059. var extension = plugin.extensions;
  67060. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67061. plugin: plugin,
  67062. isBinary: false
  67063. };
  67064. }
  67065. else {
  67066. var extensions = plugin.extensions;
  67067. Object.keys(extensions).forEach(function (extension) {
  67068. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67069. plugin: plugin,
  67070. isBinary: extensions[extension].isBinary
  67071. };
  67072. });
  67073. }
  67074. };
  67075. /**
  67076. * Import meshes into a scene
  67077. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67078. * @param rootUrl a string that defines the root url for scene and resources
  67079. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67080. * @param scene the instance of BABYLON.Scene to append to
  67081. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67082. * @param onProgress a callback with a progress event for each file being loaded
  67083. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67084. * @param pluginExtension the extension used to determine the plugin
  67085. * @returns The loaded plugin
  67086. */
  67087. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67088. if (onSuccess === void 0) { onSuccess = null; }
  67089. if (onProgress === void 0) { onProgress = null; }
  67090. if (onError === void 0) { onError = null; }
  67091. if (pluginExtension === void 0) { pluginExtension = null; }
  67092. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67093. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67094. return null;
  67095. }
  67096. var loadingToken = {};
  67097. scene._addPendingData(loadingToken);
  67098. var disposeHandler = function () {
  67099. scene._removePendingData(loadingToken);
  67100. };
  67101. var errorHandler = function (message, exception) {
  67102. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67103. if (onError) {
  67104. onError(scene, errorMessage, exception);
  67105. }
  67106. else {
  67107. BABYLON.Tools.Error(errorMessage);
  67108. // should the exception be thrown?
  67109. }
  67110. disposeHandler();
  67111. };
  67112. var progressHandler = onProgress ? function (event) {
  67113. try {
  67114. onProgress(event);
  67115. }
  67116. catch (e) {
  67117. errorHandler("Error in onProgress callback", e);
  67118. }
  67119. } : undefined;
  67120. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67121. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67122. if (onSuccess) {
  67123. try {
  67124. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67125. }
  67126. catch (e) {
  67127. errorHandler("Error in onSuccess callback", e);
  67128. }
  67129. }
  67130. scene._removePendingData(loadingToken);
  67131. };
  67132. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67133. if (plugin.rewriteRootURL) {
  67134. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67135. }
  67136. if (sceneFilename === "") {
  67137. if (sceneFilename === "") {
  67138. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67139. }
  67140. }
  67141. if (plugin.importMesh) {
  67142. var syncedPlugin = plugin;
  67143. var meshes = new Array();
  67144. var particleSystems = new Array();
  67145. var skeletons = new Array();
  67146. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67147. return;
  67148. }
  67149. scene.loadingPluginName = plugin.name;
  67150. successHandler(meshes, particleSystems, skeletons, []);
  67151. }
  67152. else {
  67153. var asyncedPlugin = plugin;
  67154. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67155. scene.loadingPluginName = plugin.name;
  67156. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67157. }).catch(function (error) {
  67158. errorHandler(error.message, error);
  67159. });
  67160. }
  67161. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67162. };
  67163. /**
  67164. * Import meshes into a scene
  67165. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67166. * @param rootUrl a string that defines the root url for scene and resources
  67167. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67168. * @param scene the instance of BABYLON.Scene to append to
  67169. * @param onProgress a callback with a progress event for each file being loaded
  67170. * @param pluginExtension the extension used to determine the plugin
  67171. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67172. */
  67173. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67174. if (onProgress === void 0) { onProgress = null; }
  67175. if (pluginExtension === void 0) { pluginExtension = null; }
  67176. return new Promise(function (resolve, reject) {
  67177. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67178. resolve({
  67179. meshes: meshes,
  67180. particleSystems: particleSystems,
  67181. skeletons: skeletons,
  67182. animationGroups: animationGroups
  67183. });
  67184. }, onProgress, function (scene, message, exception) {
  67185. reject(exception || new Error(message));
  67186. }, pluginExtension);
  67187. });
  67188. };
  67189. /**
  67190. * Load a scene
  67191. * @param rootUrl a string that defines the root url for scene and resources
  67192. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67193. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67194. * @param onSuccess a callback with the scene when import succeeds
  67195. * @param onProgress a callback with a progress event for each file being loaded
  67196. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67197. * @param pluginExtension the extension used to determine the plugin
  67198. * @returns The loaded plugin
  67199. */
  67200. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67201. if (onSuccess === void 0) { onSuccess = null; }
  67202. if (onProgress === void 0) { onProgress = null; }
  67203. if (onError === void 0) { onError = null; }
  67204. if (pluginExtension === void 0) { pluginExtension = null; }
  67205. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67206. };
  67207. /**
  67208. * Load a scene
  67209. * @param rootUrl a string that defines the root url for scene and resources
  67210. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67211. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67212. * @param onProgress a callback with a progress event for each file being loaded
  67213. * @param pluginExtension the extension used to determine the plugin
  67214. * @returns The loaded scene
  67215. */
  67216. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67217. if (onProgress === void 0) { onProgress = null; }
  67218. if (pluginExtension === void 0) { pluginExtension = null; }
  67219. return new Promise(function (resolve, reject) {
  67220. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67221. resolve(scene);
  67222. }, onProgress, function (scene, message, exception) {
  67223. reject(exception || new Error(message));
  67224. }, pluginExtension);
  67225. });
  67226. };
  67227. /**
  67228. * Append a scene
  67229. * @param rootUrl a string that defines the root url for scene and resources
  67230. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67231. * @param scene is the instance of BABYLON.Scene to append to
  67232. * @param onSuccess a callback with the scene when import succeeds
  67233. * @param onProgress a callback with a progress event for each file being loaded
  67234. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67235. * @param pluginExtension the extension used to determine the plugin
  67236. * @returns The loaded plugin
  67237. */
  67238. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67239. if (onSuccess === void 0) { onSuccess = null; }
  67240. if (onProgress === void 0) { onProgress = null; }
  67241. if (onError === void 0) { onError = null; }
  67242. if (pluginExtension === void 0) { pluginExtension = null; }
  67243. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67244. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67245. return null;
  67246. }
  67247. if (SceneLoader.ShowLoadingScreen) {
  67248. scene.getEngine().displayLoadingUI();
  67249. }
  67250. var loadingToken = {};
  67251. scene._addPendingData(loadingToken);
  67252. var disposeHandler = function () {
  67253. scene._removePendingData(loadingToken);
  67254. scene.getEngine().hideLoadingUI();
  67255. };
  67256. var errorHandler = function (message, exception) {
  67257. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67258. if (onError) {
  67259. onError(scene, errorMessage, exception);
  67260. }
  67261. else {
  67262. BABYLON.Tools.Error(errorMessage);
  67263. // should the exception be thrown?
  67264. }
  67265. disposeHandler();
  67266. };
  67267. var progressHandler = onProgress ? function (event) {
  67268. try {
  67269. onProgress(event);
  67270. }
  67271. catch (e) {
  67272. errorHandler("Error in onProgress callback", e);
  67273. }
  67274. } : undefined;
  67275. var successHandler = function () {
  67276. if (onSuccess) {
  67277. try {
  67278. onSuccess(scene);
  67279. }
  67280. catch (e) {
  67281. errorHandler("Error in onSuccess callback", e);
  67282. }
  67283. }
  67284. scene._removePendingData(loadingToken);
  67285. };
  67286. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67287. if (sceneFilename === "") {
  67288. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67289. }
  67290. if (plugin.load) {
  67291. var syncedPlugin = plugin;
  67292. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67293. return;
  67294. }
  67295. scene.loadingPluginName = plugin.name;
  67296. successHandler();
  67297. }
  67298. else {
  67299. var asyncedPlugin = plugin;
  67300. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67301. scene.loadingPluginName = plugin.name;
  67302. successHandler();
  67303. }).catch(function (error) {
  67304. errorHandler(error.message, error);
  67305. });
  67306. }
  67307. if (SceneLoader.ShowLoadingScreen) {
  67308. scene.executeWhenReady(function () {
  67309. scene.getEngine().hideLoadingUI();
  67310. });
  67311. }
  67312. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67313. };
  67314. /**
  67315. * Append a scene
  67316. * @param rootUrl a string that defines the root url for scene and resources
  67317. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67318. * @param scene is the instance of BABYLON.Scene to append to
  67319. * @param onProgress a callback with a progress event for each file being loaded
  67320. * @param pluginExtension the extension used to determine the plugin
  67321. * @returns The given scene
  67322. */
  67323. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67324. if (onProgress === void 0) { onProgress = null; }
  67325. if (pluginExtension === void 0) { pluginExtension = null; }
  67326. return new Promise(function (resolve, reject) {
  67327. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67328. resolve(scene);
  67329. }, onProgress, function (scene, message, exception) {
  67330. reject(exception || new Error(message));
  67331. }, pluginExtension);
  67332. });
  67333. };
  67334. /**
  67335. * Load a scene into an asset container
  67336. * @param rootUrl a string that defines the root url for scene and resources
  67337. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67338. * @param scene is the instance of BABYLON.Scene to append to
  67339. * @param onSuccess a callback with the scene when import succeeds
  67340. * @param onProgress a callback with a progress event for each file being loaded
  67341. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67342. * @param pluginExtension the extension used to determine the plugin
  67343. * @returns The loaded plugin
  67344. */
  67345. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67346. if (onSuccess === void 0) { onSuccess = null; }
  67347. if (onProgress === void 0) { onProgress = null; }
  67348. if (onError === void 0) { onError = null; }
  67349. if (pluginExtension === void 0) { pluginExtension = null; }
  67350. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67351. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67352. return null;
  67353. }
  67354. var loadingToken = {};
  67355. scene._addPendingData(loadingToken);
  67356. var disposeHandler = function () {
  67357. scene._removePendingData(loadingToken);
  67358. };
  67359. var errorHandler = function (message, exception) {
  67360. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67361. if (onError) {
  67362. onError(scene, errorMessage, exception);
  67363. }
  67364. else {
  67365. BABYLON.Tools.Error(errorMessage);
  67366. // should the exception be thrown?
  67367. }
  67368. disposeHandler();
  67369. };
  67370. var progressHandler = onProgress ? function (event) {
  67371. try {
  67372. onProgress(event);
  67373. }
  67374. catch (e) {
  67375. errorHandler("Error in onProgress callback", e);
  67376. }
  67377. } : undefined;
  67378. var successHandler = function (assets) {
  67379. if (onSuccess) {
  67380. try {
  67381. onSuccess(assets);
  67382. }
  67383. catch (e) {
  67384. errorHandler("Error in onSuccess callback", e);
  67385. }
  67386. }
  67387. scene._removePendingData(loadingToken);
  67388. };
  67389. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67390. if (plugin.loadAssetContainer) {
  67391. var syncedPlugin = plugin;
  67392. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67393. if (!assetContainer) {
  67394. return;
  67395. }
  67396. scene.loadingPluginName = plugin.name;
  67397. successHandler(assetContainer);
  67398. }
  67399. else if (plugin.loadAssetContainerAsync) {
  67400. var asyncedPlugin = plugin;
  67401. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67402. scene.loadingPluginName = plugin.name;
  67403. successHandler(assetContainer);
  67404. }).catch(function (error) {
  67405. errorHandler(error.message, error);
  67406. });
  67407. }
  67408. else {
  67409. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67410. }
  67411. if (SceneLoader.ShowLoadingScreen) {
  67412. scene.executeWhenReady(function () {
  67413. scene.getEngine().hideLoadingUI();
  67414. });
  67415. }
  67416. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67417. };
  67418. /**
  67419. * Load a scene into an asset container
  67420. * @param rootUrl a string that defines the root url for scene and resources
  67421. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67422. * @param scene is the instance of BABYLON.Scene to append to
  67423. * @param onProgress a callback with a progress event for each file being loaded
  67424. * @param pluginExtension the extension used to determine the plugin
  67425. * @returns The loaded asset container
  67426. */
  67427. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67428. if (onProgress === void 0) { onProgress = null; }
  67429. if (pluginExtension === void 0) { pluginExtension = null; }
  67430. return new Promise(function (resolve, reject) {
  67431. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67432. resolve(assetContainer);
  67433. }, onProgress, function (scene, message, exception) {
  67434. reject(exception || new Error(message));
  67435. }, pluginExtension);
  67436. });
  67437. };
  67438. // Flags
  67439. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67440. SceneLoader._ShowLoadingScreen = true;
  67441. SceneLoader._CleanBoneMatrixWeights = false;
  67442. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67443. // Members
  67444. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67445. SceneLoader._registeredPlugins = {};
  67446. return SceneLoader;
  67447. }());
  67448. BABYLON.SceneLoader = SceneLoader;
  67449. ;
  67450. })(BABYLON || (BABYLON = {}));
  67451. //# sourceMappingURL=babylon.sceneLoader.js.map
  67452. var BABYLON;
  67453. (function (BABYLON) {
  67454. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67455. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67456. var parsedMaterial = parsedData.materials[index];
  67457. if (parsedMaterial.id === id) {
  67458. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67459. }
  67460. }
  67461. return null;
  67462. };
  67463. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67464. for (var i in names) {
  67465. if (mesh.name === names[i]) {
  67466. hierarchyIds.push(mesh.id);
  67467. return true;
  67468. }
  67469. }
  67470. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67471. hierarchyIds.push(mesh.id);
  67472. return true;
  67473. }
  67474. return false;
  67475. };
  67476. var logOperation = function (operation, producer) {
  67477. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67478. };
  67479. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67480. if (addToScene === void 0) { addToScene = false; }
  67481. var container = new BABYLON.AssetContainer(scene);
  67482. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67483. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67484. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67485. // and avoid problems with multiple concurrent .babylon loads.
  67486. var log = "importScene has failed JSON parse";
  67487. try {
  67488. var parsedData = JSON.parse(data);
  67489. log = "";
  67490. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67491. var index;
  67492. var cache;
  67493. // Lights
  67494. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67495. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67496. var parsedLight = parsedData.lights[index];
  67497. var light = BABYLON.Light.Parse(parsedLight, scene);
  67498. if (light) {
  67499. container.lights.push(light);
  67500. log += (index === 0 ? "\n\tLights:" : "");
  67501. log += "\n\t\t" + light.toString(fullDetails);
  67502. }
  67503. }
  67504. }
  67505. // Animations
  67506. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67507. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67508. var parsedAnimation = parsedData.animations[index];
  67509. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67510. scene.animations.push(animation);
  67511. container.animations.push(animation);
  67512. log += (index === 0 ? "\n\tAnimations:" : "");
  67513. log += "\n\t\t" + animation.toString(fullDetails);
  67514. }
  67515. }
  67516. // Materials
  67517. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67518. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67519. var parsedMaterial = parsedData.materials[index];
  67520. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67521. container.materials.push(mat);
  67522. log += (index === 0 ? "\n\tMaterials:" : "");
  67523. log += "\n\t\t" + mat.toString(fullDetails);
  67524. }
  67525. }
  67526. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67527. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67528. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67529. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67530. container.multiMaterials.push(mmat);
  67531. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67532. log += "\n\t\t" + mmat.toString(fullDetails);
  67533. }
  67534. }
  67535. // Morph targets
  67536. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67537. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67538. var managerData = _a[_i];
  67539. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67540. }
  67541. }
  67542. // Skeletons
  67543. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67544. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67545. var parsedSkeleton = parsedData.skeletons[index];
  67546. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67547. container.skeletons.push(skeleton);
  67548. log += (index === 0 ? "\n\tSkeletons:" : "");
  67549. log += "\n\t\t" + skeleton.toString(fullDetails);
  67550. }
  67551. }
  67552. // Geometries
  67553. var geometries = parsedData.geometries;
  67554. if (geometries !== undefined && geometries !== null) {
  67555. var addedGeometry = new Array();
  67556. // Boxes
  67557. var boxes = geometries.boxes;
  67558. if (boxes !== undefined && boxes !== null) {
  67559. for (index = 0, cache = boxes.length; index < cache; index++) {
  67560. var parsedBox = boxes[index];
  67561. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67562. }
  67563. }
  67564. // Spheres
  67565. var spheres = geometries.spheres;
  67566. if (spheres !== undefined && spheres !== null) {
  67567. for (index = 0, cache = spheres.length; index < cache; index++) {
  67568. var parsedSphere = spheres[index];
  67569. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67570. }
  67571. }
  67572. // Cylinders
  67573. var cylinders = geometries.cylinders;
  67574. if (cylinders !== undefined && cylinders !== null) {
  67575. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67576. var parsedCylinder = cylinders[index];
  67577. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67578. }
  67579. }
  67580. // Toruses
  67581. var toruses = geometries.toruses;
  67582. if (toruses !== undefined && toruses !== null) {
  67583. for (index = 0, cache = toruses.length; index < cache; index++) {
  67584. var parsedTorus = toruses[index];
  67585. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67586. }
  67587. }
  67588. // Grounds
  67589. var grounds = geometries.grounds;
  67590. if (grounds !== undefined && grounds !== null) {
  67591. for (index = 0, cache = grounds.length; index < cache; index++) {
  67592. var parsedGround = grounds[index];
  67593. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67594. }
  67595. }
  67596. // Planes
  67597. var planes = geometries.planes;
  67598. if (planes !== undefined && planes !== null) {
  67599. for (index = 0, cache = planes.length; index < cache; index++) {
  67600. var parsedPlane = planes[index];
  67601. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67602. }
  67603. }
  67604. // TorusKnots
  67605. var torusKnots = geometries.torusKnots;
  67606. if (torusKnots !== undefined && torusKnots !== null) {
  67607. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67608. var parsedTorusKnot = torusKnots[index];
  67609. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67610. }
  67611. }
  67612. // VertexData
  67613. var vertexData = geometries.vertexData;
  67614. if (vertexData !== undefined && vertexData !== null) {
  67615. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67616. var parsedVertexData = vertexData[index];
  67617. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67618. }
  67619. }
  67620. addedGeometry.forEach(function (g) {
  67621. if (g) {
  67622. container.geometries.push(g);
  67623. }
  67624. });
  67625. }
  67626. // Transform nodes
  67627. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67628. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67629. var parsedTransformNode = parsedData.transformNodes[index];
  67630. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67631. container.transformNodes.push(node);
  67632. }
  67633. }
  67634. // Meshes
  67635. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67636. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67637. var parsedMesh = parsedData.meshes[index];
  67638. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67639. container.meshes.push(mesh);
  67640. log += (index === 0 ? "\n\tMeshes:" : "");
  67641. log += "\n\t\t" + mesh.toString(fullDetails);
  67642. }
  67643. }
  67644. // Cameras
  67645. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67646. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67647. var parsedCamera = parsedData.cameras[index];
  67648. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67649. container.cameras.push(camera);
  67650. log += (index === 0 ? "\n\tCameras:" : "");
  67651. log += "\n\t\t" + camera.toString(fullDetails);
  67652. }
  67653. }
  67654. // Browsing all the graph to connect the dots
  67655. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67656. var camera = scene.cameras[index];
  67657. if (camera._waitingParentId) {
  67658. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67659. camera._waitingParentId = null;
  67660. }
  67661. }
  67662. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67663. var light_1 = scene.lights[index];
  67664. if (light_1 && light_1._waitingParentId) {
  67665. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67666. light_1._waitingParentId = null;
  67667. }
  67668. }
  67669. // Sounds
  67670. // TODO: add sound
  67671. var loadedSounds = [];
  67672. var loadedSound;
  67673. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67674. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67675. var parsedSound = parsedData.sounds[index];
  67676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67677. if (!parsedSound.url)
  67678. parsedSound.url = parsedSound.name;
  67679. if (!loadedSounds[parsedSound.url]) {
  67680. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67681. loadedSounds[parsedSound.url] = loadedSound;
  67682. container.sounds.push(loadedSound);
  67683. }
  67684. else {
  67685. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67686. }
  67687. }
  67688. else {
  67689. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67690. }
  67691. }
  67692. }
  67693. loadedSounds = [];
  67694. // Connect parents & children and parse actions
  67695. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67696. var transformNode = scene.transformNodes[index];
  67697. if (transformNode._waitingParentId) {
  67698. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67699. transformNode._waitingParentId = null;
  67700. }
  67701. }
  67702. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67703. var mesh = scene.meshes[index];
  67704. if (mesh._waitingParentId) {
  67705. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67706. mesh._waitingParentId = null;
  67707. }
  67708. if (mesh._waitingActions) {
  67709. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67710. mesh._waitingActions = null;
  67711. }
  67712. }
  67713. // freeze world matrix application
  67714. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67715. var currentMesh = scene.meshes[index];
  67716. if (currentMesh._waitingFreezeWorldMatrix) {
  67717. currentMesh.freezeWorldMatrix();
  67718. currentMesh._waitingFreezeWorldMatrix = null;
  67719. }
  67720. else {
  67721. currentMesh.computeWorldMatrix(true);
  67722. }
  67723. }
  67724. // Particles Systems
  67725. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67726. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67727. var parsedParticleSystem = parsedData.particleSystems[index];
  67728. if (parsedParticleSystem.activeParticleCount) {
  67729. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67730. container.particleSystems.push(ps);
  67731. }
  67732. else {
  67733. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67734. container.particleSystems.push(ps);
  67735. }
  67736. }
  67737. }
  67738. // Lens flares
  67739. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67740. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67741. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67742. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67743. container.lensFlareSystems.push(lf);
  67744. }
  67745. }
  67746. // Shadows
  67747. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67748. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67749. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67750. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67751. container.shadowGenerators.push(sg);
  67752. }
  67753. }
  67754. // Lights exclusions / inclusions
  67755. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67756. var light_2 = scene.lights[index];
  67757. // Excluded check
  67758. if (light_2._excludedMeshesIds.length > 0) {
  67759. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67760. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67761. if (excludedMesh) {
  67762. light_2.excludedMeshes.push(excludedMesh);
  67763. }
  67764. }
  67765. light_2._excludedMeshesIds = [];
  67766. }
  67767. // Included check
  67768. if (light_2._includedOnlyMeshesIds.length > 0) {
  67769. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67770. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67771. if (includedOnlyMesh) {
  67772. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67773. }
  67774. }
  67775. light_2._includedOnlyMeshesIds = [];
  67776. }
  67777. }
  67778. // Effect layers
  67779. if (parsedData.effectLayers) {
  67780. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67781. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67782. container.effectLayers.push(effectLayer);
  67783. }
  67784. }
  67785. // Actions (scene)
  67786. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67787. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67788. }
  67789. if (!addToScene) {
  67790. container.removeAllFromScene();
  67791. }
  67792. }
  67793. catch (err) {
  67794. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67795. if (onError) {
  67796. onError(msg, err);
  67797. }
  67798. else {
  67799. BABYLON.Tools.Log(msg);
  67800. throw err;
  67801. }
  67802. }
  67803. finally {
  67804. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67805. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67806. }
  67807. }
  67808. return container;
  67809. };
  67810. BABYLON.SceneLoader.RegisterPlugin({
  67811. name: "babylon.js",
  67812. extensions: ".babylon",
  67813. canDirectLoad: function (data) {
  67814. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67815. return true;
  67816. }
  67817. return false;
  67818. },
  67819. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67820. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67821. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67822. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67823. // and avoid problems with multiple concurrent .babylon loads.
  67824. var log = "importMesh has failed JSON parse";
  67825. try {
  67826. var parsedData = JSON.parse(data);
  67827. log = "";
  67828. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67829. if (!meshesNames) {
  67830. meshesNames = null;
  67831. }
  67832. else if (!Array.isArray(meshesNames)) {
  67833. meshesNames = [meshesNames];
  67834. }
  67835. var hierarchyIds = new Array();
  67836. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67837. var loadedSkeletonsIds = [];
  67838. var loadedMaterialsIds = [];
  67839. var index;
  67840. var cache;
  67841. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67842. var parsedMesh = parsedData.meshes[index];
  67843. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67844. if (meshesNames !== null) {
  67845. // Remove found mesh name from list.
  67846. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67847. }
  67848. //Geometry?
  67849. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67850. //does the file contain geometries?
  67851. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67852. //find the correct geometry and add it to the scene
  67853. var found = false;
  67854. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67855. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67856. return;
  67857. }
  67858. else {
  67859. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67860. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67861. switch (geometryType) {
  67862. case "boxes":
  67863. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67864. break;
  67865. case "spheres":
  67866. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67867. break;
  67868. case "cylinders":
  67869. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67870. break;
  67871. case "toruses":
  67872. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67873. break;
  67874. case "grounds":
  67875. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67876. break;
  67877. case "planes":
  67878. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67879. break;
  67880. case "torusKnots":
  67881. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67882. break;
  67883. case "vertexData":
  67884. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67885. break;
  67886. }
  67887. found = true;
  67888. }
  67889. });
  67890. }
  67891. });
  67892. if (found === false) {
  67893. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67894. }
  67895. }
  67896. }
  67897. // Material ?
  67898. if (parsedMesh.materialId) {
  67899. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67900. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67901. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67902. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67903. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67904. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67905. var subMatId = parsedMultiMaterial.materials[matIndex];
  67906. loadedMaterialsIds.push(subMatId);
  67907. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67908. if (mat) {
  67909. log += "\n\tMaterial " + mat.toString(fullDetails);
  67910. }
  67911. }
  67912. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67913. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67914. if (mmat) {
  67915. materialFound = true;
  67916. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67917. }
  67918. break;
  67919. }
  67920. }
  67921. }
  67922. if (materialFound === false) {
  67923. loadedMaterialsIds.push(parsedMesh.materialId);
  67924. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67925. if (!mat) {
  67926. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67927. }
  67928. else {
  67929. log += "\n\tMaterial " + mat.toString(fullDetails);
  67930. }
  67931. }
  67932. }
  67933. // Skeleton ?
  67934. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67935. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67936. if (skeletonAlreadyLoaded === false) {
  67937. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67938. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67939. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67940. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67941. skeletons.push(skeleton);
  67942. loadedSkeletonsIds.push(parsedSkeleton.id);
  67943. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67944. }
  67945. }
  67946. }
  67947. }
  67948. // Morph targets ?
  67949. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67950. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67951. var managerData = _a[_i];
  67952. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67953. }
  67954. }
  67955. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67956. meshes.push(mesh);
  67957. log += "\n\tMesh " + mesh.toString(fullDetails);
  67958. }
  67959. }
  67960. // Connecting parents
  67961. var currentMesh;
  67962. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67963. currentMesh = scene.meshes[index];
  67964. if (currentMesh._waitingParentId) {
  67965. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67966. currentMesh._waitingParentId = null;
  67967. }
  67968. }
  67969. // freeze and compute world matrix application
  67970. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67971. currentMesh = scene.meshes[index];
  67972. if (currentMesh._waitingFreezeWorldMatrix) {
  67973. currentMesh.freezeWorldMatrix();
  67974. currentMesh._waitingFreezeWorldMatrix = null;
  67975. }
  67976. else {
  67977. currentMesh.computeWorldMatrix(true);
  67978. }
  67979. }
  67980. }
  67981. // Particles
  67982. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67983. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67984. var parsedParticleSystem = parsedData.particleSystems[index];
  67985. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67986. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67987. }
  67988. }
  67989. }
  67990. return true;
  67991. }
  67992. catch (err) {
  67993. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67994. if (onError) {
  67995. onError(msg, err);
  67996. }
  67997. else {
  67998. BABYLON.Tools.Log(msg);
  67999. throw err;
  68000. }
  68001. }
  68002. finally {
  68003. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68004. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68005. }
  68006. }
  68007. return false;
  68008. },
  68009. load: function (scene, data, rootUrl, onError) {
  68010. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68011. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68012. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68013. // and avoid problems with multiple concurrent .babylon loads.
  68014. var log = "importScene has failed JSON parse";
  68015. try {
  68016. var parsedData = JSON.parse(data);
  68017. log = "";
  68018. // Scene
  68019. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68020. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68021. }
  68022. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68023. scene.autoClear = parsedData.autoClear;
  68024. }
  68025. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68026. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68027. }
  68028. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68029. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68030. }
  68031. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68032. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68033. }
  68034. // Fog
  68035. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68036. scene.fogMode = parsedData.fogMode;
  68037. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68038. scene.fogStart = parsedData.fogStart;
  68039. scene.fogEnd = parsedData.fogEnd;
  68040. scene.fogDensity = parsedData.fogDensity;
  68041. log += "\tFog mode for scene: ";
  68042. switch (scene.fogMode) {
  68043. // getters not compiling, so using hardcoded
  68044. case 1:
  68045. log += "exp\n";
  68046. break;
  68047. case 2:
  68048. log += "exp2\n";
  68049. break;
  68050. case 3:
  68051. log += "linear\n";
  68052. break;
  68053. }
  68054. }
  68055. //Physics
  68056. if (parsedData.physicsEnabled) {
  68057. var physicsPlugin;
  68058. if (parsedData.physicsEngine === "cannon") {
  68059. physicsPlugin = new BABYLON.CannonJSPlugin();
  68060. }
  68061. else if (parsedData.physicsEngine === "oimo") {
  68062. physicsPlugin = new BABYLON.OimoJSPlugin();
  68063. }
  68064. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68065. //else - default engine, which is currently oimo
  68066. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68067. scene.enablePhysics(physicsGravity, physicsPlugin);
  68068. }
  68069. // Metadata
  68070. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68071. scene.metadata = parsedData.metadata;
  68072. }
  68073. //collisions, if defined. otherwise, default is true
  68074. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68075. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68076. }
  68077. scene.workerCollisions = !!parsedData.workerCollisions;
  68078. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68079. if (!container) {
  68080. return false;
  68081. }
  68082. if (parsedData.autoAnimate) {
  68083. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68084. }
  68085. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68086. scene.setActiveCameraByID(parsedData.activeCameraID);
  68087. }
  68088. // Environment texture
  68089. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68090. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68091. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68092. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68093. if (parsedData.environmentTextureRotationY) {
  68094. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68095. }
  68096. scene.environmentTexture = hdrTexture;
  68097. }
  68098. else {
  68099. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68100. if (parsedData.environmentTextureRotationY) {
  68101. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68102. }
  68103. scene.environmentTexture = cubeTexture;
  68104. }
  68105. if (parsedData.createDefaultSkybox === true) {
  68106. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68107. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68108. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68109. }
  68110. }
  68111. // Finish
  68112. return true;
  68113. }
  68114. catch (err) {
  68115. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68116. if (onError) {
  68117. onError(msg, err);
  68118. }
  68119. else {
  68120. BABYLON.Tools.Log(msg);
  68121. throw err;
  68122. }
  68123. }
  68124. finally {
  68125. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68126. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68127. }
  68128. }
  68129. return false;
  68130. },
  68131. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68132. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68133. return container;
  68134. }
  68135. });
  68136. })(BABYLON || (BABYLON = {}));
  68137. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68138. var BABYLON;
  68139. (function (BABYLON) {
  68140. var FilesInput = /** @class */ (function () {
  68141. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68142. this.onProcessFileCallback = function () { return true; };
  68143. this._engine = engine;
  68144. this._currentScene = scene;
  68145. this._sceneLoadedCallback = sceneLoadedCallback;
  68146. this._progressCallback = progressCallback;
  68147. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68148. this._textureLoadingCallback = textureLoadingCallback;
  68149. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68150. this._onReloadCallback = onReloadCallback;
  68151. this._errorCallback = errorCallback;
  68152. }
  68153. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68154. var _this = this;
  68155. if (elementToMonitor) {
  68156. this._elementToMonitor = elementToMonitor;
  68157. this._dragEnterHandler = function (e) { _this.drag(e); };
  68158. this._dragOverHandler = function (e) { _this.drag(e); };
  68159. this._dropHandler = function (e) { _this.drop(e); };
  68160. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68161. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68162. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68163. }
  68164. };
  68165. FilesInput.prototype.dispose = function () {
  68166. if (!this._elementToMonitor) {
  68167. return;
  68168. }
  68169. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68170. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68171. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68172. };
  68173. FilesInput.prototype.renderFunction = function () {
  68174. if (this._additionalRenderLoopLogicCallback) {
  68175. this._additionalRenderLoopLogicCallback();
  68176. }
  68177. if (this._currentScene) {
  68178. if (this._textureLoadingCallback) {
  68179. var remaining = this._currentScene.getWaitingItemsCount();
  68180. if (remaining > 0) {
  68181. this._textureLoadingCallback(remaining);
  68182. }
  68183. }
  68184. this._currentScene.render();
  68185. }
  68186. };
  68187. FilesInput.prototype.drag = function (e) {
  68188. e.stopPropagation();
  68189. e.preventDefault();
  68190. };
  68191. FilesInput.prototype.drop = function (eventDrop) {
  68192. eventDrop.stopPropagation();
  68193. eventDrop.preventDefault();
  68194. this.loadFiles(eventDrop);
  68195. };
  68196. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68197. var _this = this;
  68198. var reader = folder.createReader();
  68199. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68200. reader.readEntries(function (entries) {
  68201. remaining.count += entries.length;
  68202. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68203. var entry = entries_1[_i];
  68204. if (entry.isFile) {
  68205. entry.file(function (file) {
  68206. file.correctName = relativePath + file.name;
  68207. files.push(file);
  68208. if (--remaining.count === 0) {
  68209. callback();
  68210. }
  68211. });
  68212. }
  68213. else if (entry.isDirectory) {
  68214. _this._traverseFolder(entry, files, remaining, callback);
  68215. }
  68216. }
  68217. if (--remaining.count) {
  68218. callback();
  68219. }
  68220. });
  68221. };
  68222. FilesInput.prototype._processFiles = function (files) {
  68223. for (var i = 0; i < files.length; i++) {
  68224. var name = files[i].correctName.toLowerCase();
  68225. var extension = name.split('.').pop();
  68226. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68227. continue;
  68228. }
  68229. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68230. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68231. this._sceneFileToLoad = files[i];
  68232. }
  68233. else {
  68234. FilesInput.FilesToLoad[name] = files[i];
  68235. }
  68236. }
  68237. };
  68238. FilesInput.prototype.loadFiles = function (event) {
  68239. var _this = this;
  68240. if (this._startingProcessingFilesCallback)
  68241. this._startingProcessingFilesCallback();
  68242. // Handling data transfer via drag'n'drop
  68243. if (event && event.dataTransfer && event.dataTransfer.files) {
  68244. this._filesToLoad = event.dataTransfer.files;
  68245. }
  68246. // Handling files from input files
  68247. if (event && event.target && event.target.files) {
  68248. this._filesToLoad = event.target.files;
  68249. }
  68250. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68251. var files_1 = new Array();
  68252. var folders = [];
  68253. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68254. for (var i = 0; i < this._filesToLoad.length; i++) {
  68255. var fileToLoad = this._filesToLoad[i];
  68256. var name_1 = fileToLoad.name.toLowerCase();
  68257. var entry = void 0;
  68258. fileToLoad.correctName = name_1;
  68259. if (items) {
  68260. var item = items[i];
  68261. if (item.getAsEntry) {
  68262. entry = item.getAsEntry();
  68263. }
  68264. else if (item.webkitGetAsEntry) {
  68265. entry = item.webkitGetAsEntry();
  68266. }
  68267. }
  68268. if (!entry) {
  68269. files_1.push(fileToLoad);
  68270. }
  68271. else {
  68272. if (entry.isDirectory) {
  68273. folders.push(entry);
  68274. }
  68275. else {
  68276. files_1.push(fileToLoad);
  68277. }
  68278. }
  68279. }
  68280. if (folders.length === 0) {
  68281. this._processFiles(files_1);
  68282. this._processReload();
  68283. }
  68284. else {
  68285. var remaining = { count: folders.length };
  68286. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68287. var folder = folders_1[_i];
  68288. this._traverseFolder(folder, files_1, remaining, function () {
  68289. _this._processFiles(files_1);
  68290. if (remaining.count === 0) {
  68291. _this._processReload();
  68292. }
  68293. });
  68294. }
  68295. }
  68296. }
  68297. };
  68298. FilesInput.prototype._processReload = function () {
  68299. if (this._onReloadCallback) {
  68300. this._onReloadCallback(this._sceneFileToLoad);
  68301. }
  68302. else {
  68303. this.reload();
  68304. }
  68305. };
  68306. FilesInput.prototype.reload = function () {
  68307. var _this = this;
  68308. // If a scene file has been provided
  68309. if (this._sceneFileToLoad) {
  68310. if (this._currentScene) {
  68311. if (BABYLON.Tools.errorsCount > 0) {
  68312. BABYLON.Tools.ClearLogCache();
  68313. }
  68314. this._engine.stopRenderLoop();
  68315. this._currentScene.dispose();
  68316. }
  68317. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68318. if (_this._progressCallback) {
  68319. _this._progressCallback(progress);
  68320. }
  68321. }).then(function (scene) {
  68322. _this._currentScene = scene;
  68323. if (_this._sceneLoadedCallback) {
  68324. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68325. }
  68326. // Wait for textures and shaders to be ready
  68327. _this._currentScene.executeWhenReady(function () {
  68328. _this._engine.runRenderLoop(function () {
  68329. _this.renderFunction();
  68330. });
  68331. });
  68332. }).catch(function (error) {
  68333. if (_this._errorCallback) {
  68334. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68335. }
  68336. });
  68337. }
  68338. else {
  68339. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68340. }
  68341. };
  68342. FilesInput.FilesToLoad = {};
  68343. return FilesInput;
  68344. }());
  68345. BABYLON.FilesInput = FilesInput;
  68346. })(BABYLON || (BABYLON = {}));
  68347. //# sourceMappingURL=babylon.filesInput.js.map
  68348. var BABYLON;
  68349. (function (BABYLON) {
  68350. /**
  68351. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68352. * The underlying implementation relies on an associative array to ensure the best performances.
  68353. * The value can be anything including 'null' but except 'undefined'
  68354. */
  68355. var StringDictionary = /** @class */ (function () {
  68356. function StringDictionary() {
  68357. this._count = 0;
  68358. this._data = {};
  68359. }
  68360. /**
  68361. * This will clear this dictionary and copy the content from the 'source' one.
  68362. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68363. * @param source the dictionary to take the content from and copy to this dictionary
  68364. */
  68365. StringDictionary.prototype.copyFrom = function (source) {
  68366. var _this = this;
  68367. this.clear();
  68368. source.forEach(function (t, v) { return _this.add(t, v); });
  68369. };
  68370. /**
  68371. * Get a value based from its key
  68372. * @param key the given key to get the matching value from
  68373. * @return the value if found, otherwise undefined is returned
  68374. */
  68375. StringDictionary.prototype.get = function (key) {
  68376. var val = this._data[key];
  68377. if (val !== undefined) {
  68378. return val;
  68379. }
  68380. return undefined;
  68381. };
  68382. /**
  68383. * Get a value from its key or add it if it doesn't exist.
  68384. * This method will ensure you that a given key/data will be present in the dictionary.
  68385. * @param key the given key to get the matching value from
  68386. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68387. * The factory will only be invoked if there's no data for the given key.
  68388. * @return the value corresponding to the key.
  68389. */
  68390. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68391. var val = this.get(key);
  68392. if (val !== undefined) {
  68393. return val;
  68394. }
  68395. val = factory(key);
  68396. if (val) {
  68397. this.add(key, val);
  68398. }
  68399. return val;
  68400. };
  68401. /**
  68402. * Get a value from its key if present in the dictionary otherwise add it
  68403. * @param key the key to get the value from
  68404. * @param val if there's no such key/value pair in the dictionary add it with this value
  68405. * @return the value corresponding to the key
  68406. */
  68407. StringDictionary.prototype.getOrAdd = function (key, val) {
  68408. var curVal = this.get(key);
  68409. if (curVal !== undefined) {
  68410. return curVal;
  68411. }
  68412. this.add(key, val);
  68413. return val;
  68414. };
  68415. /**
  68416. * Check if there's a given key in the dictionary
  68417. * @param key the key to check for
  68418. * @return true if the key is present, false otherwise
  68419. */
  68420. StringDictionary.prototype.contains = function (key) {
  68421. return this._data[key] !== undefined;
  68422. };
  68423. /**
  68424. * Add a new key and its corresponding value
  68425. * @param key the key to add
  68426. * @param value the value corresponding to the key
  68427. * @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
  68428. */
  68429. StringDictionary.prototype.add = function (key, value) {
  68430. if (this._data[key] !== undefined) {
  68431. return false;
  68432. }
  68433. this._data[key] = value;
  68434. ++this._count;
  68435. return true;
  68436. };
  68437. StringDictionary.prototype.set = function (key, value) {
  68438. if (this._data[key] === undefined) {
  68439. return false;
  68440. }
  68441. this._data[key] = value;
  68442. return true;
  68443. };
  68444. /**
  68445. * Get the element of the given key and remove it from the dictionary
  68446. * @param key
  68447. */
  68448. StringDictionary.prototype.getAndRemove = function (key) {
  68449. var val = this.get(key);
  68450. if (val !== undefined) {
  68451. delete this._data[key];
  68452. --this._count;
  68453. return val;
  68454. }
  68455. return null;
  68456. };
  68457. /**
  68458. * Remove a key/value from the dictionary.
  68459. * @param key the key to remove
  68460. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68461. */
  68462. StringDictionary.prototype.remove = function (key) {
  68463. if (this.contains(key)) {
  68464. delete this._data[key];
  68465. --this._count;
  68466. return true;
  68467. }
  68468. return false;
  68469. };
  68470. /**
  68471. * Clear the whole content of the dictionary
  68472. */
  68473. StringDictionary.prototype.clear = function () {
  68474. this._data = {};
  68475. this._count = 0;
  68476. };
  68477. Object.defineProperty(StringDictionary.prototype, "count", {
  68478. get: function () {
  68479. return this._count;
  68480. },
  68481. enumerable: true,
  68482. configurable: true
  68483. });
  68484. /**
  68485. * Execute a callback on each key/val of the dictionary.
  68486. * Note that you can remove any element in this dictionary in the callback implementation
  68487. * @param callback the callback to execute on a given key/value pair
  68488. */
  68489. StringDictionary.prototype.forEach = function (callback) {
  68490. for (var cur in this._data) {
  68491. var val = this._data[cur];
  68492. callback(cur, val);
  68493. }
  68494. };
  68495. /**
  68496. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68497. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68498. * Note that you can remove any element in this dictionary in the callback implementation
  68499. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68500. */
  68501. StringDictionary.prototype.first = function (callback) {
  68502. for (var cur in this._data) {
  68503. var val = this._data[cur];
  68504. var res = callback(cur, val);
  68505. if (res) {
  68506. return res;
  68507. }
  68508. }
  68509. return null;
  68510. };
  68511. return StringDictionary;
  68512. }());
  68513. BABYLON.StringDictionary = StringDictionary;
  68514. })(BABYLON || (BABYLON = {}));
  68515. //# sourceMappingURL=babylon.stringDictionary.js.map
  68516. var BABYLON;
  68517. (function (BABYLON) {
  68518. var Tags = /** @class */ (function () {
  68519. function Tags() {
  68520. }
  68521. Tags.EnableFor = function (obj) {
  68522. obj._tags = obj._tags || {};
  68523. obj.hasTags = function () {
  68524. return Tags.HasTags(obj);
  68525. };
  68526. obj.addTags = function (tagsString) {
  68527. return Tags.AddTagsTo(obj, tagsString);
  68528. };
  68529. obj.removeTags = function (tagsString) {
  68530. return Tags.RemoveTagsFrom(obj, tagsString);
  68531. };
  68532. obj.matchesTagsQuery = function (tagsQuery) {
  68533. return Tags.MatchesQuery(obj, tagsQuery);
  68534. };
  68535. };
  68536. Tags.DisableFor = function (obj) {
  68537. delete obj._tags;
  68538. delete obj.hasTags;
  68539. delete obj.addTags;
  68540. delete obj.removeTags;
  68541. delete obj.matchesTagsQuery;
  68542. };
  68543. Tags.HasTags = function (obj) {
  68544. if (!obj._tags) {
  68545. return false;
  68546. }
  68547. return !BABYLON.Tools.IsEmpty(obj._tags);
  68548. };
  68549. Tags.GetTags = function (obj, asString) {
  68550. if (asString === void 0) { asString = true; }
  68551. if (!obj._tags) {
  68552. return null;
  68553. }
  68554. if (asString) {
  68555. var tagsArray = [];
  68556. for (var tag in obj._tags) {
  68557. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68558. tagsArray.push(tag);
  68559. }
  68560. }
  68561. return tagsArray.join(" ");
  68562. }
  68563. else {
  68564. return obj._tags;
  68565. }
  68566. };
  68567. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68568. // a tag cannot start with '||', '&&', and '!'
  68569. // it cannot contain whitespaces
  68570. Tags.AddTagsTo = function (obj, tagsString) {
  68571. if (!tagsString) {
  68572. return;
  68573. }
  68574. if (typeof tagsString !== "string") {
  68575. return;
  68576. }
  68577. var tags = tagsString.split(" ");
  68578. tags.forEach(function (tag, index, array) {
  68579. Tags._AddTagTo(obj, tag);
  68580. });
  68581. };
  68582. Tags._AddTagTo = function (obj, tag) {
  68583. tag = tag.trim();
  68584. if (tag === "" || tag === "true" || tag === "false") {
  68585. return;
  68586. }
  68587. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68588. return;
  68589. }
  68590. Tags.EnableFor(obj);
  68591. obj._tags[tag] = true;
  68592. };
  68593. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68594. if (!Tags.HasTags(obj)) {
  68595. return;
  68596. }
  68597. var tags = tagsString.split(" ");
  68598. for (var t in tags) {
  68599. Tags._RemoveTagFrom(obj, tags[t]);
  68600. }
  68601. };
  68602. Tags._RemoveTagFrom = function (obj, tag) {
  68603. delete obj._tags[tag];
  68604. };
  68605. Tags.MatchesQuery = function (obj, tagsQuery) {
  68606. if (tagsQuery === undefined) {
  68607. return true;
  68608. }
  68609. if (tagsQuery === "") {
  68610. return Tags.HasTags(obj);
  68611. }
  68612. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68613. };
  68614. return Tags;
  68615. }());
  68616. BABYLON.Tags = Tags;
  68617. })(BABYLON || (BABYLON = {}));
  68618. //# sourceMappingURL=babylon.tags.js.map
  68619. var BABYLON;
  68620. (function (BABYLON) {
  68621. /**
  68622. * Class used to evalaute queries containing `and` and `or` operators
  68623. */
  68624. var AndOrNotEvaluator = /** @class */ (function () {
  68625. function AndOrNotEvaluator() {
  68626. }
  68627. /**
  68628. * Evaluate a query
  68629. * @param query defines the query to evaluate
  68630. * @param evaluateCallback defines the callback used to filter result
  68631. * @returns true if the query matches
  68632. */
  68633. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68634. if (!query.match(/\([^\(\)]*\)/g)) {
  68635. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68636. }
  68637. else {
  68638. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68639. // remove parenthesis
  68640. r = r.slice(1, r.length - 1);
  68641. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68642. });
  68643. }
  68644. if (query === "true") {
  68645. return true;
  68646. }
  68647. if (query === "false") {
  68648. return false;
  68649. }
  68650. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68651. };
  68652. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68653. evaluateCallback = evaluateCallback || (function (r) {
  68654. return r === "true" ? true : false;
  68655. });
  68656. var result;
  68657. var or = parenthesisContent.split("||");
  68658. for (var i in or) {
  68659. if (or.hasOwnProperty(i)) {
  68660. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68661. var and = ori.split("&&");
  68662. if (and.length > 1) {
  68663. for (var j = 0; j < and.length; ++j) {
  68664. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68665. if (andj !== "true" && andj !== "false") {
  68666. if (andj[0] === "!") {
  68667. result = !evaluateCallback(andj.substring(1));
  68668. }
  68669. else {
  68670. result = evaluateCallback(andj);
  68671. }
  68672. }
  68673. else {
  68674. result = andj === "true" ? true : false;
  68675. }
  68676. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68677. ori = "false";
  68678. break;
  68679. }
  68680. }
  68681. }
  68682. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68683. result = true;
  68684. break;
  68685. }
  68686. // result equals false (or undefined)
  68687. if (ori !== "true" && ori !== "false") {
  68688. if (ori[0] === "!") {
  68689. result = !evaluateCallback(ori.substring(1));
  68690. }
  68691. else {
  68692. result = evaluateCallback(ori);
  68693. }
  68694. }
  68695. else {
  68696. result = ori === "true" ? true : false;
  68697. }
  68698. }
  68699. }
  68700. // the whole parenthesis scope is replaced by 'true' or 'false'
  68701. return result ? "true" : "false";
  68702. };
  68703. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68704. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68705. // remove whitespaces
  68706. r = r.replace(/[\s]/g, function () { return ""; });
  68707. return r.length % 2 ? "!" : "";
  68708. });
  68709. booleanString = booleanString.trim();
  68710. if (booleanString === "!true") {
  68711. booleanString = "false";
  68712. }
  68713. else if (booleanString === "!false") {
  68714. booleanString = "true";
  68715. }
  68716. return booleanString;
  68717. };
  68718. return AndOrNotEvaluator;
  68719. }());
  68720. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68721. })(BABYLON || (BABYLON = {}));
  68722. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68723. var BABYLON;
  68724. (function (BABYLON) {
  68725. /**
  68726. * Class used to enable access to IndexedDB
  68727. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68728. */
  68729. var Database = /** @class */ (function () {
  68730. /**
  68731. * Creates a new Database
  68732. * @param urlToScene defines the url to load the scene
  68733. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68734. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68735. */
  68736. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68737. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68738. var _this = this;
  68739. // Handling various flavors of prefixed version of IndexedDB
  68740. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68741. this.callbackManifestChecked = callbackManifestChecked;
  68742. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68743. this.db = null;
  68744. this._enableSceneOffline = false;
  68745. this._enableTexturesOffline = false;
  68746. this.manifestVersionFound = 0;
  68747. this.mustUpdateRessources = false;
  68748. this.hasReachedQuota = false;
  68749. if (!Database.IDBStorageEnabled) {
  68750. this.callbackManifestChecked(true);
  68751. }
  68752. else {
  68753. if (disableManifestCheck) {
  68754. this._enableSceneOffline = true;
  68755. this._enableTexturesOffline = true;
  68756. this.manifestVersionFound = 1;
  68757. BABYLON.Tools.SetImmediate(function () {
  68758. _this.callbackManifestChecked(true);
  68759. });
  68760. }
  68761. else {
  68762. this._checkManifestFile();
  68763. }
  68764. }
  68765. }
  68766. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68767. /**
  68768. * Gets a boolean indicating if scene must be saved in the database
  68769. */
  68770. get: function () {
  68771. return this._enableSceneOffline;
  68772. },
  68773. enumerable: true,
  68774. configurable: true
  68775. });
  68776. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68777. /**
  68778. * Gets a boolean indicating if textures must be saved in the database
  68779. */
  68780. get: function () {
  68781. return this._enableTexturesOffline;
  68782. },
  68783. enumerable: true,
  68784. configurable: true
  68785. });
  68786. Database.prototype._checkManifestFile = function () {
  68787. var _this = this;
  68788. var noManifestFile = function () {
  68789. _this._enableSceneOffline = false;
  68790. _this._enableTexturesOffline = false;
  68791. _this.callbackManifestChecked(false);
  68792. };
  68793. var timeStampUsed = false;
  68794. var manifestURL = this.currentSceneUrl + ".manifest";
  68795. var xhr = new XMLHttpRequest();
  68796. if (navigator.onLine) {
  68797. // Adding a timestamp to by-pass browsers' cache
  68798. timeStampUsed = true;
  68799. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68800. }
  68801. xhr.open("GET", manifestURL, true);
  68802. xhr.addEventListener("load", function () {
  68803. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68804. try {
  68805. var manifestFile = JSON.parse(xhr.response);
  68806. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68807. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68808. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68809. _this.manifestVersionFound = manifestFile.version;
  68810. }
  68811. if (_this.callbackManifestChecked) {
  68812. _this.callbackManifestChecked(true);
  68813. }
  68814. }
  68815. catch (ex) {
  68816. noManifestFile();
  68817. }
  68818. }
  68819. else {
  68820. noManifestFile();
  68821. }
  68822. }, false);
  68823. xhr.addEventListener("error", function (event) {
  68824. if (timeStampUsed) {
  68825. timeStampUsed = false;
  68826. // Let's retry without the timeStamp
  68827. // It could fail when coupled with HTML5 Offline API
  68828. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68829. xhr.open("GET", retryManifestURL, true);
  68830. xhr.send();
  68831. }
  68832. else {
  68833. noManifestFile();
  68834. }
  68835. }, false);
  68836. try {
  68837. xhr.send();
  68838. }
  68839. catch (ex) {
  68840. BABYLON.Tools.Error("Error on XHR send request.");
  68841. this.callbackManifestChecked(false);
  68842. }
  68843. };
  68844. /**
  68845. * Open the database and make it available
  68846. * @param successCallback defines the callback to call on success
  68847. * @param errorCallback defines the callback to call on error
  68848. */
  68849. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68850. var _this = this;
  68851. var handleError = function () {
  68852. _this.isSupported = false;
  68853. if (errorCallback)
  68854. errorCallback();
  68855. };
  68856. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68857. // Your browser doesn't support IndexedDB
  68858. this.isSupported = false;
  68859. if (errorCallback)
  68860. errorCallback();
  68861. }
  68862. else {
  68863. // If the DB hasn't been opened or created yet
  68864. if (!this.db) {
  68865. this.hasReachedQuota = false;
  68866. this.isSupported = true;
  68867. var request = this.idbFactory.open("babylonjs", 1);
  68868. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68869. request.onerror = function (event) {
  68870. handleError();
  68871. };
  68872. // executes when a version change transaction cannot complete due to other active transactions
  68873. request.onblocked = function (event) {
  68874. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68875. handleError();
  68876. };
  68877. // DB has been opened successfully
  68878. request.onsuccess = function (event) {
  68879. _this.db = request.result;
  68880. successCallback();
  68881. };
  68882. // Initialization of the DB. Creating Scenes & Textures stores
  68883. request.onupgradeneeded = function (event) {
  68884. _this.db = (event.target).result;
  68885. if (_this.db) {
  68886. try {
  68887. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68888. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68889. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68890. }
  68891. catch (ex) {
  68892. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68893. handleError();
  68894. }
  68895. }
  68896. };
  68897. }
  68898. // DB has already been created and opened
  68899. else {
  68900. if (successCallback)
  68901. successCallback();
  68902. }
  68903. }
  68904. };
  68905. /**
  68906. * Loads an image from the database
  68907. * @param url defines the url to load from
  68908. * @param image defines the target DOM image
  68909. */
  68910. Database.prototype.loadImageFromDB = function (url, image) {
  68911. var _this = this;
  68912. var completeURL = Database._ReturnFullUrlLocation(url);
  68913. var saveAndLoadImage = function () {
  68914. if (!_this.hasReachedQuota && _this.db !== null) {
  68915. // the texture is not yet in the DB, let's try to save it
  68916. _this._saveImageIntoDBAsync(completeURL, image);
  68917. }
  68918. // If the texture is not in the DB and we've reached the DB quota limit
  68919. // let's load it directly from the web
  68920. else {
  68921. image.src = url;
  68922. }
  68923. };
  68924. if (!this.mustUpdateRessources) {
  68925. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68926. }
  68927. // First time we're download the images or update requested in the manifest file by a version change
  68928. else {
  68929. saveAndLoadImage();
  68930. }
  68931. };
  68932. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68933. if (this.isSupported && this.db !== null) {
  68934. var texture;
  68935. var transaction = this.db.transaction(["textures"]);
  68936. transaction.onabort = function (event) {
  68937. image.src = url;
  68938. };
  68939. transaction.oncomplete = function (event) {
  68940. var blobTextureURL;
  68941. if (texture) {
  68942. var URL = window.URL || window.webkitURL;
  68943. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68944. image.onerror = function () {
  68945. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68946. image.src = url;
  68947. };
  68948. image.src = blobTextureURL;
  68949. }
  68950. else {
  68951. notInDBCallback();
  68952. }
  68953. };
  68954. var getRequest = transaction.objectStore("textures").get(url);
  68955. getRequest.onsuccess = function (event) {
  68956. texture = (event.target).result;
  68957. };
  68958. getRequest.onerror = function (event) {
  68959. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68960. image.src = url;
  68961. };
  68962. }
  68963. else {
  68964. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68965. image.src = url;
  68966. }
  68967. };
  68968. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68969. var _this = this;
  68970. if (this.isSupported) {
  68971. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68972. var generateBlobUrl = function () {
  68973. var blobTextureURL;
  68974. if (blob) {
  68975. var URL = window.URL || window.webkitURL;
  68976. try {
  68977. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68978. }
  68979. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68980. catch (ex) {
  68981. blobTextureURL = URL.createObjectURL(blob);
  68982. }
  68983. }
  68984. if (blobTextureURL) {
  68985. image.src = blobTextureURL;
  68986. }
  68987. };
  68988. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68989. var xhr = new XMLHttpRequest(), blob;
  68990. xhr.open("GET", url, true);
  68991. xhr.responseType = "blob";
  68992. xhr.addEventListener("load", function () {
  68993. if (xhr.status === 200 && _this.db) {
  68994. // Blob as response (XHR2)
  68995. blob = xhr.response;
  68996. var transaction = _this.db.transaction(["textures"], "readwrite");
  68997. // the transaction could abort because of a QuotaExceededError error
  68998. transaction.onabort = function (event) {
  68999. try {
  69000. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69001. var srcElement = (event.srcElement || event.target);
  69002. var error = srcElement.error;
  69003. if (error && error.name === "QuotaExceededError") {
  69004. _this.hasReachedQuota = true;
  69005. }
  69006. }
  69007. catch (ex) { }
  69008. generateBlobUrl();
  69009. };
  69010. transaction.oncomplete = function (event) {
  69011. generateBlobUrl();
  69012. };
  69013. var newTexture = { textureUrl: url, data: blob };
  69014. try {
  69015. // Put the blob into the dabase
  69016. var addRequest = transaction.objectStore("textures").put(newTexture);
  69017. addRequest.onsuccess = function (event) {
  69018. };
  69019. addRequest.onerror = function (event) {
  69020. generateBlobUrl();
  69021. };
  69022. }
  69023. catch (ex) {
  69024. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69025. if (ex.code === 25) {
  69026. Database.IsUASupportingBlobStorage = false;
  69027. }
  69028. image.src = url;
  69029. }
  69030. }
  69031. else {
  69032. image.src = url;
  69033. }
  69034. }, false);
  69035. xhr.addEventListener("error", function (event) {
  69036. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69037. image.src = url;
  69038. }, false);
  69039. xhr.send();
  69040. }
  69041. else {
  69042. image.src = url;
  69043. }
  69044. }
  69045. else {
  69046. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69047. image.src = url;
  69048. }
  69049. };
  69050. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69051. var _this = this;
  69052. var updateVersion = function () {
  69053. // the version is not yet in the DB or we need to update it
  69054. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69055. };
  69056. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69057. };
  69058. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69059. var _this = this;
  69060. if (this.isSupported && this.db) {
  69061. var version;
  69062. try {
  69063. var transaction = this.db.transaction(["versions"]);
  69064. transaction.oncomplete = function (event) {
  69065. if (version) {
  69066. // If the version in the JSON file is different from the version in DB
  69067. if (_this.manifestVersionFound !== version.data) {
  69068. _this.mustUpdateRessources = true;
  69069. updateInDBCallback();
  69070. }
  69071. else {
  69072. callback(version.data);
  69073. }
  69074. }
  69075. // version was not found in DB
  69076. else {
  69077. _this.mustUpdateRessources = true;
  69078. updateInDBCallback();
  69079. }
  69080. };
  69081. transaction.onabort = function (event) {
  69082. callback(-1);
  69083. };
  69084. var getRequest = transaction.objectStore("versions").get(url);
  69085. getRequest.onsuccess = function (event) {
  69086. version = (event.target).result;
  69087. };
  69088. getRequest.onerror = function (event) {
  69089. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69090. callback(-1);
  69091. };
  69092. }
  69093. catch (ex) {
  69094. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69095. callback(-1);
  69096. }
  69097. }
  69098. else {
  69099. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69100. callback(-1);
  69101. }
  69102. };
  69103. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69104. var _this = this;
  69105. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69106. try {
  69107. // Open a transaction to the database
  69108. var transaction = this.db.transaction(["versions"], "readwrite");
  69109. // the transaction could abort because of a QuotaExceededError error
  69110. transaction.onabort = function (event) {
  69111. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69112. var error = event.srcElement['error'];
  69113. if (error && error.name === "QuotaExceededError") {
  69114. _this.hasReachedQuota = true;
  69115. }
  69116. }
  69117. catch (ex) { }
  69118. callback(-1);
  69119. };
  69120. transaction.oncomplete = function (event) {
  69121. callback(_this.manifestVersionFound);
  69122. };
  69123. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69124. // Put the scene into the database
  69125. var addRequest = transaction.objectStore("versions").put(newVersion);
  69126. addRequest.onsuccess = function (event) {
  69127. };
  69128. addRequest.onerror = function (event) {
  69129. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69130. };
  69131. }
  69132. catch (ex) {
  69133. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69134. callback(-1);
  69135. }
  69136. }
  69137. else {
  69138. callback(-1);
  69139. }
  69140. };
  69141. /**
  69142. * Loads a file from database
  69143. * @param url defines the URL to load from
  69144. * @param sceneLoaded defines a callback to call on success
  69145. * @param progressCallBack defines a callback to call when progress changed
  69146. * @param errorCallback defines a callback to call on error
  69147. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69148. */
  69149. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69150. var _this = this;
  69151. var completeUrl = Database._ReturnFullUrlLocation(url);
  69152. var saveAndLoadFile = function () {
  69153. // the scene is not yet in the DB, let's try to save it
  69154. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69155. };
  69156. this._checkVersionFromDB(completeUrl, function (version) {
  69157. if (version !== -1) {
  69158. if (!_this.mustUpdateRessources) {
  69159. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69160. }
  69161. else {
  69162. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69163. }
  69164. }
  69165. else {
  69166. if (errorCallback) {
  69167. errorCallback();
  69168. }
  69169. }
  69170. });
  69171. };
  69172. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69173. if (this.isSupported && this.db) {
  69174. var targetStore;
  69175. if (url.indexOf(".babylon") !== -1) {
  69176. targetStore = "scenes";
  69177. }
  69178. else {
  69179. targetStore = "textures";
  69180. }
  69181. var file;
  69182. var transaction = this.db.transaction([targetStore]);
  69183. transaction.oncomplete = function (event) {
  69184. if (file) {
  69185. callback(file.data);
  69186. }
  69187. // file was not found in DB
  69188. else {
  69189. notInDBCallback();
  69190. }
  69191. };
  69192. transaction.onabort = function (event) {
  69193. notInDBCallback();
  69194. };
  69195. var getRequest = transaction.objectStore(targetStore).get(url);
  69196. getRequest.onsuccess = function (event) {
  69197. file = (event.target).result;
  69198. };
  69199. getRequest.onerror = function (event) {
  69200. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69201. notInDBCallback();
  69202. };
  69203. }
  69204. else {
  69205. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69206. callback();
  69207. }
  69208. };
  69209. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69210. var _this = this;
  69211. if (this.isSupported) {
  69212. var targetStore;
  69213. if (url.indexOf(".babylon") !== -1) {
  69214. targetStore = "scenes";
  69215. }
  69216. else {
  69217. targetStore = "textures";
  69218. }
  69219. // Create XHR
  69220. var xhr = new XMLHttpRequest();
  69221. var fileData;
  69222. xhr.open("GET", url, true);
  69223. if (useArrayBuffer) {
  69224. xhr.responseType = "arraybuffer";
  69225. }
  69226. if (progressCallback) {
  69227. xhr.onprogress = progressCallback;
  69228. }
  69229. xhr.addEventListener("load", function () {
  69230. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69231. // Blob as response (XHR2)
  69232. //fileData = xhr.responseText;
  69233. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69234. if (!_this.hasReachedQuota && _this.db) {
  69235. // Open a transaction to the database
  69236. var transaction = _this.db.transaction([targetStore], "readwrite");
  69237. // the transaction could abort because of a QuotaExceededError error
  69238. transaction.onabort = function (event) {
  69239. try {
  69240. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69241. var error = event.srcElement['error'];
  69242. if (error && error.name === "QuotaExceededError") {
  69243. _this.hasReachedQuota = true;
  69244. }
  69245. }
  69246. catch (ex) { }
  69247. callback(fileData);
  69248. };
  69249. transaction.oncomplete = function (event) {
  69250. callback(fileData);
  69251. };
  69252. var newFile;
  69253. if (targetStore === "scenes") {
  69254. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69255. }
  69256. else {
  69257. newFile = { textureUrl: url, data: fileData };
  69258. }
  69259. try {
  69260. // Put the scene into the database
  69261. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69262. addRequest.onsuccess = function (event) {
  69263. };
  69264. addRequest.onerror = function (event) {
  69265. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69266. };
  69267. }
  69268. catch (ex) {
  69269. callback(fileData);
  69270. }
  69271. }
  69272. else {
  69273. callback(fileData);
  69274. }
  69275. }
  69276. else {
  69277. callback();
  69278. }
  69279. }, false);
  69280. xhr.addEventListener("error", function (event) {
  69281. BABYLON.Tools.Error("error on XHR request.");
  69282. callback();
  69283. }, false);
  69284. xhr.send();
  69285. }
  69286. else {
  69287. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69288. callback();
  69289. }
  69290. };
  69291. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69292. Database.IsUASupportingBlobStorage = true;
  69293. /** Gets a boolean indicating if Database storate is enabled */
  69294. Database.IDBStorageEnabled = true;
  69295. Database._ParseURL = function (url) {
  69296. var a = document.createElement('a');
  69297. a.href = url;
  69298. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69299. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69300. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69301. return absLocation;
  69302. };
  69303. Database._ReturnFullUrlLocation = function (url) {
  69304. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69305. return (Database._ParseURL(window.location.href) + url);
  69306. }
  69307. else {
  69308. return url;
  69309. }
  69310. };
  69311. return Database;
  69312. }());
  69313. BABYLON.Database = Database;
  69314. })(BABYLON || (BABYLON = {}));
  69315. //# sourceMappingURL=babylon.database.js.map
  69316. var BABYLON;
  69317. (function (BABYLON) {
  69318. var FresnelParameters = /** @class */ (function () {
  69319. function FresnelParameters() {
  69320. this._isEnabled = true;
  69321. this.leftColor = BABYLON.Color3.White();
  69322. this.rightColor = BABYLON.Color3.Black();
  69323. this.bias = 0;
  69324. this.power = 1;
  69325. }
  69326. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69327. get: function () {
  69328. return this._isEnabled;
  69329. },
  69330. set: function (value) {
  69331. if (this._isEnabled === value) {
  69332. return;
  69333. }
  69334. this._isEnabled = value;
  69335. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69336. },
  69337. enumerable: true,
  69338. configurable: true
  69339. });
  69340. FresnelParameters.prototype.clone = function () {
  69341. var newFresnelParameters = new FresnelParameters();
  69342. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69343. return newFresnelParameters;
  69344. };
  69345. FresnelParameters.prototype.serialize = function () {
  69346. var serializationObject = {};
  69347. serializationObject.isEnabled = this.isEnabled;
  69348. serializationObject.leftColor = this.leftColor.asArray();
  69349. serializationObject.rightColor = this.rightColor.asArray();
  69350. serializationObject.bias = this.bias;
  69351. serializationObject.power = this.power;
  69352. return serializationObject;
  69353. };
  69354. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69355. var fresnelParameters = new FresnelParameters();
  69356. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69357. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69358. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69359. fresnelParameters.bias = parsedFresnelParameters.bias;
  69360. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69361. return fresnelParameters;
  69362. };
  69363. return FresnelParameters;
  69364. }());
  69365. BABYLON.FresnelParameters = FresnelParameters;
  69366. })(BABYLON || (BABYLON = {}));
  69367. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69368. var BABYLON;
  69369. (function (BABYLON) {
  69370. var MultiMaterial = /** @class */ (function (_super) {
  69371. __extends(MultiMaterial, _super);
  69372. function MultiMaterial(name, scene) {
  69373. var _this = _super.call(this, name, scene, true) || this;
  69374. scene.multiMaterials.push(_this);
  69375. _this.subMaterials = new Array();
  69376. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69377. return _this;
  69378. }
  69379. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69380. get: function () {
  69381. return this._subMaterials;
  69382. },
  69383. set: function (value) {
  69384. this._subMaterials = value;
  69385. this._hookArray(value);
  69386. },
  69387. enumerable: true,
  69388. configurable: true
  69389. });
  69390. MultiMaterial.prototype._hookArray = function (array) {
  69391. var _this = this;
  69392. var oldPush = array.push;
  69393. array.push = function () {
  69394. var items = [];
  69395. for (var _i = 0; _i < arguments.length; _i++) {
  69396. items[_i] = arguments[_i];
  69397. }
  69398. var result = oldPush.apply(array, items);
  69399. _this._markAllSubMeshesAsTexturesDirty();
  69400. return result;
  69401. };
  69402. var oldSplice = array.splice;
  69403. array.splice = function (index, deleteCount) {
  69404. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69405. _this._markAllSubMeshesAsTexturesDirty();
  69406. return deleted;
  69407. };
  69408. };
  69409. // Properties
  69410. MultiMaterial.prototype.getSubMaterial = function (index) {
  69411. if (index < 0 || index >= this.subMaterials.length) {
  69412. return this.getScene().defaultMaterial;
  69413. }
  69414. return this.subMaterials[index];
  69415. };
  69416. MultiMaterial.prototype.getActiveTextures = function () {
  69417. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69418. if (subMaterial) {
  69419. return subMaterial.getActiveTextures();
  69420. }
  69421. else {
  69422. return [];
  69423. }
  69424. }));
  69425. var _a;
  69426. };
  69427. // Methods
  69428. MultiMaterial.prototype.getClassName = function () {
  69429. return "MultiMaterial";
  69430. };
  69431. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69432. for (var index = 0; index < this.subMaterials.length; index++) {
  69433. var subMaterial = this.subMaterials[index];
  69434. if (subMaterial) {
  69435. if (subMaterial.storeEffectOnSubMeshes) {
  69436. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69437. return false;
  69438. }
  69439. continue;
  69440. }
  69441. if (!subMaterial.isReady(mesh)) {
  69442. return false;
  69443. }
  69444. }
  69445. }
  69446. return true;
  69447. };
  69448. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69449. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69450. for (var index = 0; index < this.subMaterials.length; index++) {
  69451. var subMaterial = null;
  69452. var current = this.subMaterials[index];
  69453. if (cloneChildren && current) {
  69454. subMaterial = current.clone(name + "-" + current.name);
  69455. }
  69456. else {
  69457. subMaterial = this.subMaterials[index];
  69458. }
  69459. newMultiMaterial.subMaterials.push(subMaterial);
  69460. }
  69461. return newMultiMaterial;
  69462. };
  69463. MultiMaterial.prototype.serialize = function () {
  69464. var serializationObject = {};
  69465. serializationObject.name = this.name;
  69466. serializationObject.id = this.id;
  69467. if (BABYLON.Tags) {
  69468. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69469. }
  69470. serializationObject.materials = [];
  69471. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69472. var subMat = this.subMaterials[matIndex];
  69473. if (subMat) {
  69474. serializationObject.materials.push(subMat.id);
  69475. }
  69476. else {
  69477. serializationObject.materials.push(null);
  69478. }
  69479. }
  69480. return serializationObject;
  69481. };
  69482. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69483. var scene = this.getScene();
  69484. if (!scene) {
  69485. return;
  69486. }
  69487. var index = scene.multiMaterials.indexOf(this);
  69488. if (index >= 0) {
  69489. scene.multiMaterials.splice(index, 1);
  69490. }
  69491. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69492. };
  69493. return MultiMaterial;
  69494. }(BABYLON.Material));
  69495. BABYLON.MultiMaterial = MultiMaterial;
  69496. })(BABYLON || (BABYLON = {}));
  69497. //# sourceMappingURL=babylon.multiMaterial.js.map
  69498. var BABYLON;
  69499. (function (BABYLON) {
  69500. var FreeCameraTouchInput = /** @class */ (function () {
  69501. function FreeCameraTouchInput() {
  69502. this._offsetX = null;
  69503. this._offsetY = null;
  69504. this._pointerPressed = new Array();
  69505. this.touchAngularSensibility = 200000.0;
  69506. this.touchMoveSensibility = 250.0;
  69507. }
  69508. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69509. var _this = this;
  69510. var previousPosition = null;
  69511. if (this._pointerInput === undefined) {
  69512. this._onLostFocus = function (evt) {
  69513. _this._offsetX = null;
  69514. _this._offsetY = null;
  69515. };
  69516. this._pointerInput = function (p, s) {
  69517. var evt = p.event;
  69518. if (evt.pointerType === "mouse") {
  69519. return;
  69520. }
  69521. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69522. if (!noPreventDefault) {
  69523. evt.preventDefault();
  69524. }
  69525. _this._pointerPressed.push(evt.pointerId);
  69526. if (_this._pointerPressed.length !== 1) {
  69527. return;
  69528. }
  69529. previousPosition = {
  69530. x: evt.clientX,
  69531. y: evt.clientY
  69532. };
  69533. }
  69534. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69535. if (!noPreventDefault) {
  69536. evt.preventDefault();
  69537. }
  69538. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69539. if (index === -1) {
  69540. return;
  69541. }
  69542. _this._pointerPressed.splice(index, 1);
  69543. if (index != 0) {
  69544. return;
  69545. }
  69546. previousPosition = null;
  69547. _this._offsetX = null;
  69548. _this._offsetY = null;
  69549. }
  69550. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69551. if (!noPreventDefault) {
  69552. evt.preventDefault();
  69553. }
  69554. if (!previousPosition) {
  69555. return;
  69556. }
  69557. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69558. if (index != 0) {
  69559. return;
  69560. }
  69561. _this._offsetX = evt.clientX - previousPosition.x;
  69562. _this._offsetY = -(evt.clientY - previousPosition.y);
  69563. }
  69564. };
  69565. }
  69566. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69567. if (this._onLostFocus) {
  69568. element.addEventListener("blur", this._onLostFocus);
  69569. }
  69570. };
  69571. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69572. if (this._pointerInput && element) {
  69573. if (this._observer) {
  69574. this.camera.getScene().onPointerObservable.remove(this._observer);
  69575. this._observer = null;
  69576. }
  69577. if (this._onLostFocus) {
  69578. element.removeEventListener("blur", this._onLostFocus);
  69579. this._onLostFocus = null;
  69580. }
  69581. this._pointerPressed = [];
  69582. this._offsetX = null;
  69583. this._offsetY = null;
  69584. }
  69585. };
  69586. FreeCameraTouchInput.prototype.checkInputs = function () {
  69587. if (this._offsetX && this._offsetY) {
  69588. var camera = this.camera;
  69589. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69590. if (this._pointerPressed.length > 1) {
  69591. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69592. }
  69593. else {
  69594. var speed = camera._computeLocalCameraSpeed();
  69595. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69596. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69597. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69598. }
  69599. }
  69600. };
  69601. FreeCameraTouchInput.prototype.getClassName = function () {
  69602. return "FreeCameraTouchInput";
  69603. };
  69604. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69605. return "touch";
  69606. };
  69607. __decorate([
  69608. BABYLON.serialize()
  69609. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69610. __decorate([
  69611. BABYLON.serialize()
  69612. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69613. return FreeCameraTouchInput;
  69614. }());
  69615. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69616. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69617. })(BABYLON || (BABYLON = {}));
  69618. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69619. var BABYLON;
  69620. (function (BABYLON) {
  69621. // We're mainly based on the logic defined into the FreeCamera code
  69622. var TouchCamera = /** @class */ (function (_super) {
  69623. __extends(TouchCamera, _super);
  69624. //-- end properties for backward compatibility for inputs
  69625. function TouchCamera(name, position, scene) {
  69626. var _this = _super.call(this, name, position, scene) || this;
  69627. _this.inputs.addTouch();
  69628. _this._setupInputs();
  69629. return _this;
  69630. }
  69631. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69632. //-- Begin properties for backward compatibility for inputs
  69633. get: function () {
  69634. var touch = this.inputs.attached["touch"];
  69635. if (touch)
  69636. return touch.touchAngularSensibility;
  69637. return 0;
  69638. },
  69639. set: function (value) {
  69640. var touch = this.inputs.attached["touch"];
  69641. if (touch)
  69642. touch.touchAngularSensibility = value;
  69643. },
  69644. enumerable: true,
  69645. configurable: true
  69646. });
  69647. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69648. get: function () {
  69649. var touch = this.inputs.attached["touch"];
  69650. if (touch)
  69651. return touch.touchMoveSensibility;
  69652. return 0;
  69653. },
  69654. set: function (value) {
  69655. var touch = this.inputs.attached["touch"];
  69656. if (touch)
  69657. touch.touchMoveSensibility = value;
  69658. },
  69659. enumerable: true,
  69660. configurable: true
  69661. });
  69662. TouchCamera.prototype.getClassName = function () {
  69663. return "TouchCamera";
  69664. };
  69665. TouchCamera.prototype._setupInputs = function () {
  69666. var mouse = this.inputs.attached["mouse"];
  69667. if (mouse) {
  69668. mouse.touchEnabled = false;
  69669. }
  69670. };
  69671. return TouchCamera;
  69672. }(BABYLON.FreeCamera));
  69673. BABYLON.TouchCamera = TouchCamera;
  69674. })(BABYLON || (BABYLON = {}));
  69675. //# sourceMappingURL=babylon.touchCamera.js.map
  69676. var BABYLON;
  69677. (function (BABYLON) {
  69678. var ProceduralTexture = /** @class */ (function (_super) {
  69679. __extends(ProceduralTexture, _super);
  69680. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69681. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69682. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69683. if (isCube === void 0) { isCube = false; }
  69684. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69685. _this.isCube = isCube;
  69686. _this.isEnabled = true;
  69687. _this._currentRefreshId = -1;
  69688. _this._refreshRate = 1;
  69689. _this._vertexBuffers = {};
  69690. _this._uniforms = new Array();
  69691. _this._samplers = new Array();
  69692. _this._textures = {};
  69693. _this._floats = {};
  69694. _this._floatsArrays = {};
  69695. _this._colors3 = {};
  69696. _this._colors4 = {};
  69697. _this._vectors2 = {};
  69698. _this._vectors3 = {};
  69699. _this._matrices = {};
  69700. _this._fallbackTextureUsed = false;
  69701. scene.proceduralTextures.push(_this);
  69702. _this._engine = scene.getEngine();
  69703. _this.name = name;
  69704. _this.isRenderTarget = true;
  69705. _this._size = size;
  69706. _this._generateMipMaps = generateMipMaps;
  69707. _this.setFragment(fragment);
  69708. _this._fallbackTexture = fallbackTexture;
  69709. if (isCube) {
  69710. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69711. _this.setFloat("face", 0);
  69712. }
  69713. else {
  69714. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69715. }
  69716. // VBO
  69717. var vertices = [];
  69718. vertices.push(1, 1);
  69719. vertices.push(-1, 1);
  69720. vertices.push(-1, -1);
  69721. vertices.push(1, -1);
  69722. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69723. _this._createIndexBuffer();
  69724. return _this;
  69725. }
  69726. ProceduralTexture.prototype._createIndexBuffer = function () {
  69727. var engine = this._engine;
  69728. // Indices
  69729. var indices = [];
  69730. indices.push(0);
  69731. indices.push(1);
  69732. indices.push(2);
  69733. indices.push(0);
  69734. indices.push(2);
  69735. indices.push(3);
  69736. this._indexBuffer = engine.createIndexBuffer(indices);
  69737. };
  69738. ProceduralTexture.prototype._rebuild = function () {
  69739. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69740. if (vb) {
  69741. vb._rebuild();
  69742. }
  69743. this._createIndexBuffer();
  69744. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69745. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69746. }
  69747. };
  69748. ProceduralTexture.prototype.reset = function () {
  69749. if (this._effect === undefined) {
  69750. return;
  69751. }
  69752. var engine = this._engine;
  69753. engine._releaseEffect(this._effect);
  69754. };
  69755. ProceduralTexture.prototype.isReady = function () {
  69756. var _this = this;
  69757. var engine = this._engine;
  69758. var shaders;
  69759. if (!this._fragment) {
  69760. return false;
  69761. }
  69762. if (this._fallbackTextureUsed) {
  69763. return true;
  69764. }
  69765. if (this._fragment.fragmentElement !== undefined) {
  69766. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69767. }
  69768. else {
  69769. shaders = { vertex: "procedural", fragment: this._fragment };
  69770. }
  69771. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69772. _this.releaseInternalTexture();
  69773. if (_this._fallbackTexture) {
  69774. _this._texture = _this._fallbackTexture._texture;
  69775. if (_this._texture) {
  69776. _this._texture.incrementReferences();
  69777. }
  69778. }
  69779. _this._fallbackTextureUsed = true;
  69780. });
  69781. return this._effect.isReady();
  69782. };
  69783. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69784. this._currentRefreshId = -1;
  69785. };
  69786. ProceduralTexture.prototype.setFragment = function (fragment) {
  69787. this._fragment = fragment;
  69788. };
  69789. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69790. get: function () {
  69791. return this._refreshRate;
  69792. },
  69793. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69794. set: function (value) {
  69795. this._refreshRate = value;
  69796. this.resetRefreshCounter();
  69797. },
  69798. enumerable: true,
  69799. configurable: true
  69800. });
  69801. ProceduralTexture.prototype._shouldRender = function () {
  69802. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69803. return false;
  69804. }
  69805. if (this._fallbackTextureUsed) {
  69806. return false;
  69807. }
  69808. if (this._currentRefreshId === -1) { // At least render once
  69809. this._currentRefreshId = 1;
  69810. return true;
  69811. }
  69812. if (this.refreshRate === this._currentRefreshId) {
  69813. this._currentRefreshId = 1;
  69814. return true;
  69815. }
  69816. this._currentRefreshId++;
  69817. return false;
  69818. };
  69819. ProceduralTexture.prototype.getRenderSize = function () {
  69820. return this._size;
  69821. };
  69822. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69823. if (this._fallbackTextureUsed) {
  69824. return;
  69825. }
  69826. this.releaseInternalTexture();
  69827. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69828. };
  69829. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69830. if (this._uniforms.indexOf(uniformName) === -1) {
  69831. this._uniforms.push(uniformName);
  69832. }
  69833. };
  69834. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69835. if (this._samplers.indexOf(name) === -1) {
  69836. this._samplers.push(name);
  69837. }
  69838. this._textures[name] = texture;
  69839. return this;
  69840. };
  69841. ProceduralTexture.prototype.setFloat = function (name, value) {
  69842. this._checkUniform(name);
  69843. this._floats[name] = value;
  69844. return this;
  69845. };
  69846. ProceduralTexture.prototype.setFloats = function (name, value) {
  69847. this._checkUniform(name);
  69848. this._floatsArrays[name] = value;
  69849. return this;
  69850. };
  69851. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69852. this._checkUniform(name);
  69853. this._colors3[name] = value;
  69854. return this;
  69855. };
  69856. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69857. this._checkUniform(name);
  69858. this._colors4[name] = value;
  69859. return this;
  69860. };
  69861. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69862. this._checkUniform(name);
  69863. this._vectors2[name] = value;
  69864. return this;
  69865. };
  69866. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69867. this._checkUniform(name);
  69868. this._vectors3[name] = value;
  69869. return this;
  69870. };
  69871. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69872. this._checkUniform(name);
  69873. this._matrices[name] = value;
  69874. return this;
  69875. };
  69876. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69877. var scene = this.getScene();
  69878. if (!scene) {
  69879. return;
  69880. }
  69881. var engine = this._engine;
  69882. // Render
  69883. engine.enableEffect(this._effect);
  69884. engine.setState(false);
  69885. // Texture
  69886. for (var name in this._textures) {
  69887. this._effect.setTexture(name, this._textures[name]);
  69888. }
  69889. // Float
  69890. for (name in this._floats) {
  69891. this._effect.setFloat(name, this._floats[name]);
  69892. }
  69893. // Floats
  69894. for (name in this._floatsArrays) {
  69895. this._effect.setArray(name, this._floatsArrays[name]);
  69896. }
  69897. // Color3
  69898. for (name in this._colors3) {
  69899. this._effect.setColor3(name, this._colors3[name]);
  69900. }
  69901. // Color4
  69902. for (name in this._colors4) {
  69903. var color = this._colors4[name];
  69904. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69905. }
  69906. // Vector2
  69907. for (name in this._vectors2) {
  69908. this._effect.setVector2(name, this._vectors2[name]);
  69909. }
  69910. // Vector3
  69911. for (name in this._vectors3) {
  69912. this._effect.setVector3(name, this._vectors3[name]);
  69913. }
  69914. // Matrix
  69915. for (name in this._matrices) {
  69916. this._effect.setMatrix(name, this._matrices[name]);
  69917. }
  69918. if (!this._texture) {
  69919. return;
  69920. }
  69921. if (this.isCube) {
  69922. for (var face = 0; face < 6; face++) {
  69923. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69924. // VBOs
  69925. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69926. this._effect.setFloat("face", face);
  69927. // Clear
  69928. engine.clear(scene.clearColor, true, true, true);
  69929. // Draw order
  69930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69931. // Mipmaps
  69932. if (face === 5) {
  69933. engine.generateMipMapsForCubemap(this._texture);
  69934. }
  69935. }
  69936. }
  69937. else {
  69938. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69939. // VBOs
  69940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69941. // Clear
  69942. engine.clear(scene.clearColor, true, true, true);
  69943. // Draw order
  69944. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69945. }
  69946. // Unbind
  69947. engine.unBindFramebuffer(this._texture, this.isCube);
  69948. if (this.onGenerated) {
  69949. this.onGenerated();
  69950. }
  69951. };
  69952. ProceduralTexture.prototype.clone = function () {
  69953. var textureSize = this.getSize();
  69954. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69955. // Base texture
  69956. newTexture.hasAlpha = this.hasAlpha;
  69957. newTexture.level = this.level;
  69958. // RenderTarget Texture
  69959. newTexture.coordinatesMode = this.coordinatesMode;
  69960. return newTexture;
  69961. };
  69962. ProceduralTexture.prototype.dispose = function () {
  69963. var scene = this.getScene();
  69964. if (!scene) {
  69965. return;
  69966. }
  69967. var index = scene.proceduralTextures.indexOf(this);
  69968. if (index >= 0) {
  69969. scene.proceduralTextures.splice(index, 1);
  69970. }
  69971. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69972. if (vertexBuffer) {
  69973. vertexBuffer.dispose();
  69974. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69975. }
  69976. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69977. this._indexBuffer = null;
  69978. }
  69979. _super.prototype.dispose.call(this);
  69980. };
  69981. return ProceduralTexture;
  69982. }(BABYLON.Texture));
  69983. BABYLON.ProceduralTexture = ProceduralTexture;
  69984. })(BABYLON || (BABYLON = {}));
  69985. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69986. var BABYLON;
  69987. (function (BABYLON) {
  69988. var CustomProceduralTexture = /** @class */ (function (_super) {
  69989. __extends(CustomProceduralTexture, _super);
  69990. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69991. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69992. _this._animate = true;
  69993. _this._time = 0;
  69994. _this._texturePath = texturePath;
  69995. //Try to load json
  69996. _this.loadJson(texturePath);
  69997. _this.refreshRate = 1;
  69998. return _this;
  69999. }
  70000. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70001. var _this = this;
  70002. var noConfigFile = function () {
  70003. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70004. try {
  70005. _this.setFragment(_this._texturePath);
  70006. }
  70007. catch (ex) {
  70008. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70009. }
  70010. };
  70011. var configFileUrl = jsonUrl + "/config.json";
  70012. var xhr = new XMLHttpRequest();
  70013. xhr.open("GET", configFileUrl, true);
  70014. xhr.addEventListener("load", function () {
  70015. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70016. try {
  70017. _this._config = JSON.parse(xhr.response);
  70018. _this.updateShaderUniforms();
  70019. _this.updateTextures();
  70020. _this.setFragment(_this._texturePath + "/custom");
  70021. _this._animate = _this._config.animate;
  70022. _this.refreshRate = _this._config.refreshrate;
  70023. }
  70024. catch (ex) {
  70025. noConfigFile();
  70026. }
  70027. }
  70028. else {
  70029. noConfigFile();
  70030. }
  70031. }, false);
  70032. xhr.addEventListener("error", function () {
  70033. noConfigFile();
  70034. }, false);
  70035. try {
  70036. xhr.send();
  70037. }
  70038. catch (ex) {
  70039. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70040. }
  70041. };
  70042. CustomProceduralTexture.prototype.isReady = function () {
  70043. if (!_super.prototype.isReady.call(this)) {
  70044. return false;
  70045. }
  70046. for (var name in this._textures) {
  70047. var texture = this._textures[name];
  70048. if (!texture.isReady()) {
  70049. return false;
  70050. }
  70051. }
  70052. return true;
  70053. };
  70054. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70055. var scene = this.getScene();
  70056. if (this._animate && scene) {
  70057. this._time += scene.getAnimationRatio() * 0.03;
  70058. this.updateShaderUniforms();
  70059. }
  70060. _super.prototype.render.call(this, useCameraPostProcess);
  70061. };
  70062. CustomProceduralTexture.prototype.updateTextures = function () {
  70063. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70064. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70065. }
  70066. };
  70067. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70068. if (this._config) {
  70069. for (var j = 0; j < this._config.uniforms.length; j++) {
  70070. var uniform = this._config.uniforms[j];
  70071. switch (uniform.type) {
  70072. case "float":
  70073. this.setFloat(uniform.name, uniform.value);
  70074. break;
  70075. case "color3":
  70076. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70077. break;
  70078. case "color4":
  70079. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70080. break;
  70081. case "vector2":
  70082. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70083. break;
  70084. case "vector3":
  70085. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70086. break;
  70087. }
  70088. }
  70089. }
  70090. this.setFloat("time", this._time);
  70091. };
  70092. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70093. get: function () {
  70094. return this._animate;
  70095. },
  70096. set: function (value) {
  70097. this._animate = value;
  70098. },
  70099. enumerable: true,
  70100. configurable: true
  70101. });
  70102. return CustomProceduralTexture;
  70103. }(BABYLON.ProceduralTexture));
  70104. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70105. })(BABYLON || (BABYLON = {}));
  70106. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70107. var BABYLON;
  70108. (function (BABYLON) {
  70109. var FreeCameraGamepadInput = /** @class */ (function () {
  70110. function FreeCameraGamepadInput() {
  70111. this.gamepadAngularSensibility = 200;
  70112. this.gamepadMoveSensibility = 40;
  70113. // private members
  70114. this._cameraTransform = BABYLON.Matrix.Identity();
  70115. this._deltaTransform = BABYLON.Vector3.Zero();
  70116. this._vector3 = BABYLON.Vector3.Zero();
  70117. this._vector2 = BABYLON.Vector2.Zero();
  70118. }
  70119. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70120. var _this = this;
  70121. var manager = this.camera.getScene().gamepadManager;
  70122. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70123. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70124. // prioritize XBOX gamepads.
  70125. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70126. _this.gamepad = gamepad;
  70127. }
  70128. }
  70129. });
  70130. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70131. if (_this.gamepad === gamepad) {
  70132. _this.gamepad = null;
  70133. }
  70134. });
  70135. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70136. };
  70137. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70138. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70139. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70140. this.gamepad = null;
  70141. };
  70142. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70143. if (this.gamepad && this.gamepad.leftStick) {
  70144. var camera = this.camera;
  70145. var LSValues = this.gamepad.leftStick;
  70146. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70147. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70148. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70149. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70150. var RSValues = this.gamepad.rightStick;
  70151. if (RSValues) {
  70152. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70153. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70154. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70155. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70156. }
  70157. else {
  70158. RSValues = { x: 0, y: 0 };
  70159. }
  70160. if (!camera.rotationQuaternion) {
  70161. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70162. }
  70163. else {
  70164. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70165. }
  70166. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70167. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70168. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70169. camera.cameraDirection.addInPlace(this._deltaTransform);
  70170. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70171. camera.cameraRotation.addInPlace(this._vector2);
  70172. }
  70173. };
  70174. FreeCameraGamepadInput.prototype.getClassName = function () {
  70175. return "FreeCameraGamepadInput";
  70176. };
  70177. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70178. return "gamepad";
  70179. };
  70180. __decorate([
  70181. BABYLON.serialize()
  70182. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70183. __decorate([
  70184. BABYLON.serialize()
  70185. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70186. return FreeCameraGamepadInput;
  70187. }());
  70188. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70189. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70190. })(BABYLON || (BABYLON = {}));
  70191. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70192. var BABYLON;
  70193. (function (BABYLON) {
  70194. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70195. function ArcRotateCameraGamepadInput() {
  70196. this.gamepadRotationSensibility = 80;
  70197. this.gamepadMoveSensibility = 40;
  70198. }
  70199. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70200. var _this = this;
  70201. var manager = this.camera.getScene().gamepadManager;
  70202. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70203. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70204. // prioritize XBOX gamepads.
  70205. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70206. _this.gamepad = gamepad;
  70207. }
  70208. }
  70209. });
  70210. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70211. if (_this.gamepad === gamepad) {
  70212. _this.gamepad = null;
  70213. }
  70214. });
  70215. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70216. };
  70217. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70218. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70219. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70220. this.gamepad = null;
  70221. };
  70222. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70223. if (this.gamepad) {
  70224. var camera = this.camera;
  70225. var RSValues = this.gamepad.rightStick;
  70226. if (RSValues) {
  70227. if (RSValues.x != 0) {
  70228. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70229. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70230. camera.inertialAlphaOffset += normalizedRX;
  70231. }
  70232. }
  70233. if (RSValues.y != 0) {
  70234. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70235. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70236. camera.inertialBetaOffset += normalizedRY;
  70237. }
  70238. }
  70239. }
  70240. var LSValues = this.gamepad.leftStick;
  70241. if (LSValues && LSValues.y != 0) {
  70242. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70243. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70244. this.camera.inertialRadiusOffset -= normalizedLY;
  70245. }
  70246. }
  70247. }
  70248. };
  70249. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70250. return "ArcRotateCameraGamepadInput";
  70251. };
  70252. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70253. return "gamepad";
  70254. };
  70255. __decorate([
  70256. BABYLON.serialize()
  70257. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70258. __decorate([
  70259. BABYLON.serialize()
  70260. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70261. return ArcRotateCameraGamepadInput;
  70262. }());
  70263. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70264. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70265. })(BABYLON || (BABYLON = {}));
  70266. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70267. var BABYLON;
  70268. (function (BABYLON) {
  70269. var GamepadManager = /** @class */ (function () {
  70270. function GamepadManager(_scene) {
  70271. var _this = this;
  70272. this._scene = _scene;
  70273. this._babylonGamepads = [];
  70274. this._oneGamepadConnected = false;
  70275. this._isMonitoring = false;
  70276. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70277. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70278. this._gamepadEventSupported = false;
  70279. }
  70280. else {
  70281. this._gamepadEventSupported = 'GamepadEvent' in window;
  70282. this._gamepadSupport = (navigator.getGamepads ||
  70283. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70284. }
  70285. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70286. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70287. for (var i in _this._babylonGamepads) {
  70288. var gamepad = _this._babylonGamepads[i];
  70289. if (gamepad && gamepad._isConnected) {
  70290. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70291. }
  70292. }
  70293. });
  70294. this._onGamepadConnectedEvent = function (evt) {
  70295. var gamepad = evt.gamepad;
  70296. if (gamepad.index in _this._babylonGamepads) {
  70297. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70298. return;
  70299. }
  70300. }
  70301. var newGamepad;
  70302. if (_this._babylonGamepads[gamepad.index]) {
  70303. newGamepad = _this._babylonGamepads[gamepad.index];
  70304. newGamepad.browserGamepad = gamepad;
  70305. newGamepad._isConnected = true;
  70306. }
  70307. else {
  70308. newGamepad = _this._addNewGamepad(gamepad);
  70309. }
  70310. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70311. _this._startMonitoringGamepads();
  70312. };
  70313. this._onGamepadDisconnectedEvent = function (evt) {
  70314. var gamepad = evt.gamepad;
  70315. // Remove the gamepad from the list of gamepads to monitor.
  70316. for (var i in _this._babylonGamepads) {
  70317. if (_this._babylonGamepads[i].index === gamepad.index) {
  70318. var disconnectedGamepad = _this._babylonGamepads[i];
  70319. disconnectedGamepad._isConnected = false;
  70320. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70321. break;
  70322. }
  70323. }
  70324. };
  70325. if (this._gamepadSupport) {
  70326. //first add already-connected gamepads
  70327. this._updateGamepadObjects();
  70328. if (this._babylonGamepads.length) {
  70329. this._startMonitoringGamepads();
  70330. }
  70331. // Checking if the gamepad connected event is supported (like in Firefox)
  70332. if (this._gamepadEventSupported) {
  70333. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70334. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70335. }
  70336. else {
  70337. this._startMonitoringGamepads();
  70338. }
  70339. }
  70340. }
  70341. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70342. get: function () {
  70343. return this._babylonGamepads;
  70344. },
  70345. enumerable: true,
  70346. configurable: true
  70347. });
  70348. GamepadManager.prototype.getGamepadByType = function (type) {
  70349. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70350. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70351. var gamepad = _a[_i];
  70352. if (gamepad && gamepad.type === type) {
  70353. return gamepad;
  70354. }
  70355. }
  70356. return null;
  70357. };
  70358. GamepadManager.prototype.dispose = function () {
  70359. if (this._gamepadEventSupported) {
  70360. if (this._onGamepadConnectedEvent) {
  70361. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70362. }
  70363. if (this._onGamepadDisconnectedEvent) {
  70364. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70365. }
  70366. this._onGamepadConnectedEvent = null;
  70367. this._onGamepadDisconnectedEvent = null;
  70368. }
  70369. this._babylonGamepads.forEach(function (gamepad) {
  70370. gamepad.dispose();
  70371. });
  70372. this.onGamepadConnectedObservable.clear();
  70373. this.onGamepadDisconnectedObservable.clear();
  70374. this._oneGamepadConnected = false;
  70375. this._stopMonitoringGamepads();
  70376. this._babylonGamepads = [];
  70377. };
  70378. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70379. if (!this._oneGamepadConnected) {
  70380. this._oneGamepadConnected = true;
  70381. }
  70382. var newGamepad;
  70383. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70384. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70385. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70386. }
  70387. // if pose is supported, use the (WebVR) pose enabled controller
  70388. else if (gamepad.pose) {
  70389. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70390. }
  70391. else {
  70392. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70393. }
  70394. this._babylonGamepads[newGamepad.index] = newGamepad;
  70395. return newGamepad;
  70396. };
  70397. GamepadManager.prototype._startMonitoringGamepads = function () {
  70398. if (!this._isMonitoring) {
  70399. this._isMonitoring = true;
  70400. //back-comp
  70401. if (!this._scene) {
  70402. this._checkGamepadsStatus();
  70403. }
  70404. }
  70405. };
  70406. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70407. this._isMonitoring = false;
  70408. };
  70409. GamepadManager.prototype._checkGamepadsStatus = function () {
  70410. var _this = this;
  70411. // Hack to be compatible Chrome
  70412. this._updateGamepadObjects();
  70413. for (var i in this._babylonGamepads) {
  70414. var gamepad = this._babylonGamepads[i];
  70415. if (!gamepad || !gamepad.isConnected) {
  70416. continue;
  70417. }
  70418. gamepad.update();
  70419. }
  70420. if (this._isMonitoring && !this._scene) {
  70421. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70422. }
  70423. };
  70424. // This function is called only on Chrome, which does not properly support
  70425. // connection/disconnection events and forces you to recopy again the gamepad object
  70426. GamepadManager.prototype._updateGamepadObjects = function () {
  70427. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70428. for (var i = 0; i < gamepads.length; i++) {
  70429. var gamepad = gamepads[i];
  70430. if (gamepad) {
  70431. if (!this._babylonGamepads[gamepad.index]) {
  70432. var newGamepad = this._addNewGamepad(gamepad);
  70433. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70434. }
  70435. else {
  70436. // Forced to copy again this object for Chrome for unknown reason
  70437. this._babylonGamepads[i].browserGamepad = gamepad;
  70438. if (!this._babylonGamepads[i].isConnected) {
  70439. this._babylonGamepads[i]._isConnected = true;
  70440. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70441. }
  70442. }
  70443. }
  70444. }
  70445. };
  70446. return GamepadManager;
  70447. }());
  70448. BABYLON.GamepadManager = GamepadManager;
  70449. })(BABYLON || (BABYLON = {}));
  70450. //# sourceMappingURL=babylon.gamepadManager.js.map
  70451. var BABYLON;
  70452. (function (BABYLON) {
  70453. var StickValues = /** @class */ (function () {
  70454. function StickValues(x, y) {
  70455. this.x = x;
  70456. this.y = y;
  70457. }
  70458. return StickValues;
  70459. }());
  70460. BABYLON.StickValues = StickValues;
  70461. var Gamepad = /** @class */ (function () {
  70462. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70463. if (leftStickX === void 0) { leftStickX = 0; }
  70464. if (leftStickY === void 0) { leftStickY = 1; }
  70465. if (rightStickX === void 0) { rightStickX = 2; }
  70466. if (rightStickY === void 0) { rightStickY = 3; }
  70467. this.id = id;
  70468. this.index = index;
  70469. this.browserGamepad = browserGamepad;
  70470. this._isConnected = true;
  70471. this._invertLeftStickY = false;
  70472. this.type = Gamepad.GAMEPAD;
  70473. this._leftStickAxisX = leftStickX;
  70474. this._leftStickAxisY = leftStickY;
  70475. this._rightStickAxisX = rightStickX;
  70476. this._rightStickAxisY = rightStickY;
  70477. if (this.browserGamepad.axes.length >= 2) {
  70478. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70479. }
  70480. if (this.browserGamepad.axes.length >= 4) {
  70481. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70482. }
  70483. }
  70484. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70485. get: function () {
  70486. return this._isConnected;
  70487. },
  70488. enumerable: true,
  70489. configurable: true
  70490. });
  70491. Gamepad.prototype.onleftstickchanged = function (callback) {
  70492. this._onleftstickchanged = callback;
  70493. };
  70494. Gamepad.prototype.onrightstickchanged = function (callback) {
  70495. this._onrightstickchanged = callback;
  70496. };
  70497. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70498. get: function () {
  70499. return this._leftStick;
  70500. },
  70501. set: function (newValues) {
  70502. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70503. this._onleftstickchanged(newValues);
  70504. }
  70505. this._leftStick = newValues;
  70506. },
  70507. enumerable: true,
  70508. configurable: true
  70509. });
  70510. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70511. get: function () {
  70512. return this._rightStick;
  70513. },
  70514. set: function (newValues) {
  70515. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70516. this._onrightstickchanged(newValues);
  70517. }
  70518. this._rightStick = newValues;
  70519. },
  70520. enumerable: true,
  70521. configurable: true
  70522. });
  70523. Gamepad.prototype.update = function () {
  70524. if (this._leftStick) {
  70525. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70526. if (this._invertLeftStickY) {
  70527. this.leftStick.y *= -1;
  70528. }
  70529. }
  70530. if (this._rightStick) {
  70531. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70532. }
  70533. };
  70534. Gamepad.prototype.dispose = function () {
  70535. };
  70536. Gamepad.GAMEPAD = 0;
  70537. Gamepad.GENERIC = 1;
  70538. Gamepad.XBOX = 2;
  70539. Gamepad.POSE_ENABLED = 3;
  70540. return Gamepad;
  70541. }());
  70542. BABYLON.Gamepad = Gamepad;
  70543. var GenericPad = /** @class */ (function (_super) {
  70544. __extends(GenericPad, _super);
  70545. function GenericPad(id, index, browserGamepad) {
  70546. var _this = _super.call(this, id, index, browserGamepad) || this;
  70547. _this.onButtonDownObservable = new BABYLON.Observable();
  70548. _this.onButtonUpObservable = new BABYLON.Observable();
  70549. _this.type = Gamepad.GENERIC;
  70550. _this._buttons = new Array(browserGamepad.buttons.length);
  70551. return _this;
  70552. }
  70553. GenericPad.prototype.onbuttondown = function (callback) {
  70554. this._onbuttondown = callback;
  70555. };
  70556. GenericPad.prototype.onbuttonup = function (callback) {
  70557. this._onbuttonup = callback;
  70558. };
  70559. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70560. if (newValue !== currentValue) {
  70561. if (newValue === 1) {
  70562. if (this._onbuttondown) {
  70563. this._onbuttondown(buttonIndex);
  70564. }
  70565. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70566. }
  70567. if (newValue === 0) {
  70568. if (this._onbuttonup) {
  70569. this._onbuttonup(buttonIndex);
  70570. }
  70571. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70572. }
  70573. }
  70574. return newValue;
  70575. };
  70576. GenericPad.prototype.update = function () {
  70577. _super.prototype.update.call(this);
  70578. for (var index = 0; index < this._buttons.length; index++) {
  70579. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70580. }
  70581. };
  70582. GenericPad.prototype.dispose = function () {
  70583. _super.prototype.dispose.call(this);
  70584. this.onButtonDownObservable.clear();
  70585. this.onButtonUpObservable.clear();
  70586. };
  70587. return GenericPad;
  70588. }(Gamepad));
  70589. BABYLON.GenericPad = GenericPad;
  70590. })(BABYLON || (BABYLON = {}));
  70591. //# sourceMappingURL=babylon.gamepad.js.map
  70592. var BABYLON;
  70593. (function (BABYLON) {
  70594. /**
  70595. * Defines supported buttons for XBox360 compatible gamepads
  70596. */
  70597. var Xbox360Button;
  70598. (function (Xbox360Button) {
  70599. /** A */
  70600. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70601. /** B */
  70602. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70603. /** X */
  70604. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70605. /** Y */
  70606. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70607. /** Start */
  70608. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70609. /** Back */
  70610. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70611. /** Left button */
  70612. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70613. /** Right button */
  70614. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70615. /** Left stick */
  70616. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70617. /** Right stick */
  70618. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70619. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70620. /** Defines values for XBox360 DPad */
  70621. var Xbox360Dpad;
  70622. (function (Xbox360Dpad) {
  70623. /** Up */
  70624. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70625. /** Down */
  70626. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70627. /** Left */
  70628. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70629. /** Right */
  70630. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70631. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70632. /**
  70633. * Defines a XBox360 gamepad
  70634. */
  70635. var Xbox360Pad = /** @class */ (function (_super) {
  70636. __extends(Xbox360Pad, _super);
  70637. /**
  70638. * Creates a new XBox360 gamepad object
  70639. * @param id defines the id of this gamepad
  70640. * @param index defines its index
  70641. * @param gamepad defines the internal HTML gamepad object
  70642. * @param xboxOne defines if it is a XBox One gamepad
  70643. */
  70644. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70645. if (xboxOne === void 0) { xboxOne = false; }
  70646. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70647. _this._leftTrigger = 0;
  70648. _this._rightTrigger = 0;
  70649. /** Observable raised when a button is pressed */
  70650. _this.onButtonDownObservable = new BABYLON.Observable();
  70651. /** Observable raised when a button is released */
  70652. _this.onButtonUpObservable = new BABYLON.Observable();
  70653. /** Observable raised when a pad is pressed */
  70654. _this.onPadDownObservable = new BABYLON.Observable();
  70655. /** Observable raised when a pad is released */
  70656. _this.onPadUpObservable = new BABYLON.Observable();
  70657. _this._buttonA = 0;
  70658. _this._buttonB = 0;
  70659. _this._buttonX = 0;
  70660. _this._buttonY = 0;
  70661. _this._buttonBack = 0;
  70662. _this._buttonStart = 0;
  70663. _this._buttonLB = 0;
  70664. _this._buttonRB = 0;
  70665. _this._buttonLeftStick = 0;
  70666. _this._buttonRightStick = 0;
  70667. _this._dPadUp = 0;
  70668. _this._dPadDown = 0;
  70669. _this._dPadLeft = 0;
  70670. _this._dPadRight = 0;
  70671. _this._isXboxOnePad = false;
  70672. _this.type = BABYLON.Gamepad.XBOX;
  70673. _this._isXboxOnePad = xboxOne;
  70674. return _this;
  70675. }
  70676. /**
  70677. * Defines the callback to call when left trigger is pressed
  70678. * @param callback defines the callback to use
  70679. */
  70680. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70681. this._onlefttriggerchanged = callback;
  70682. };
  70683. /**
  70684. * Defines the callback to call when right trigger is pressed
  70685. * @param callback defines the callback to use
  70686. */
  70687. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70688. this._onrighttriggerchanged = callback;
  70689. };
  70690. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70691. /**
  70692. * Gets or sets left trigger value
  70693. */
  70694. get: function () {
  70695. return this._leftTrigger;
  70696. },
  70697. set: function (newValue) {
  70698. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70699. this._onlefttriggerchanged(newValue);
  70700. }
  70701. this._leftTrigger = newValue;
  70702. },
  70703. enumerable: true,
  70704. configurable: true
  70705. });
  70706. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70707. /**
  70708. * Gets or sets right trigger value
  70709. */
  70710. get: function () {
  70711. return this._rightTrigger;
  70712. },
  70713. set: function (newValue) {
  70714. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70715. this._onrighttriggerchanged(newValue);
  70716. }
  70717. this._rightTrigger = newValue;
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. /**
  70723. * Defines the callback to call when a button is pressed
  70724. * @param callback defines the callback to use
  70725. */
  70726. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70727. this._onbuttondown = callback;
  70728. };
  70729. /**
  70730. * Defines the callback to call when a button is released
  70731. * @param callback defines the callback to use
  70732. */
  70733. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70734. this._onbuttonup = callback;
  70735. };
  70736. /**
  70737. * Defines the callback to call when a pad is pressed
  70738. * @param callback defines the callback to use
  70739. */
  70740. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70741. this._ondpaddown = callback;
  70742. };
  70743. /**
  70744. * Defines the callback to call when a pad is released
  70745. * @param callback defines the callback to use
  70746. */
  70747. Xbox360Pad.prototype.ondpadup = function (callback) {
  70748. this._ondpadup = callback;
  70749. };
  70750. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70751. if (newValue !== currentValue) {
  70752. if (newValue === 1) {
  70753. if (this._onbuttondown) {
  70754. this._onbuttondown(buttonType);
  70755. }
  70756. this.onButtonDownObservable.notifyObservers(buttonType);
  70757. }
  70758. if (newValue === 0) {
  70759. if (this._onbuttonup) {
  70760. this._onbuttonup(buttonType);
  70761. }
  70762. this.onButtonUpObservable.notifyObservers(buttonType);
  70763. }
  70764. }
  70765. return newValue;
  70766. };
  70767. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70768. if (newValue !== currentValue) {
  70769. if (newValue === 1) {
  70770. if (this._ondpaddown) {
  70771. this._ondpaddown(buttonType);
  70772. }
  70773. this.onPadDownObservable.notifyObservers(buttonType);
  70774. }
  70775. if (newValue === 0) {
  70776. if (this._ondpadup) {
  70777. this._ondpadup(buttonType);
  70778. }
  70779. this.onPadUpObservable.notifyObservers(buttonType);
  70780. }
  70781. }
  70782. return newValue;
  70783. };
  70784. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70785. /** Gets or sets value of A button */
  70786. get: function () {
  70787. return this._buttonA;
  70788. },
  70789. set: function (value) {
  70790. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70791. },
  70792. enumerable: true,
  70793. configurable: true
  70794. });
  70795. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70796. /** Gets or sets value of B button */
  70797. get: function () {
  70798. return this._buttonB;
  70799. },
  70800. set: function (value) {
  70801. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70807. /** Gets or sets value of X button */
  70808. get: function () {
  70809. return this._buttonX;
  70810. },
  70811. set: function (value) {
  70812. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70813. },
  70814. enumerable: true,
  70815. configurable: true
  70816. });
  70817. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70818. /** Gets or sets value of Y button */
  70819. get: function () {
  70820. return this._buttonY;
  70821. },
  70822. set: function (value) {
  70823. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70824. },
  70825. enumerable: true,
  70826. configurable: true
  70827. });
  70828. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70829. /** Gets or sets value of Start button */
  70830. get: function () {
  70831. return this._buttonStart;
  70832. },
  70833. set: function (value) {
  70834. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70835. },
  70836. enumerable: true,
  70837. configurable: true
  70838. });
  70839. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70840. /** Gets or sets value of Back button */
  70841. get: function () {
  70842. return this._buttonBack;
  70843. },
  70844. set: function (value) {
  70845. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70846. },
  70847. enumerable: true,
  70848. configurable: true
  70849. });
  70850. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70851. /** Gets or sets value of Left button */
  70852. get: function () {
  70853. return this._buttonLB;
  70854. },
  70855. set: function (value) {
  70856. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70857. },
  70858. enumerable: true,
  70859. configurable: true
  70860. });
  70861. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70862. /** Gets or sets value of Right button */
  70863. get: function () {
  70864. return this._buttonRB;
  70865. },
  70866. set: function (value) {
  70867. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70868. },
  70869. enumerable: true,
  70870. configurable: true
  70871. });
  70872. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70873. /** Gets or sets value of left stick */
  70874. get: function () {
  70875. return this._buttonLeftStick;
  70876. },
  70877. set: function (value) {
  70878. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70879. },
  70880. enumerable: true,
  70881. configurable: true
  70882. });
  70883. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70884. /** Gets or sets value of right stick */
  70885. get: function () {
  70886. return this._buttonRightStick;
  70887. },
  70888. set: function (value) {
  70889. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70890. },
  70891. enumerable: true,
  70892. configurable: true
  70893. });
  70894. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70895. /** Gets or sets value of DPad up */
  70896. get: function () {
  70897. return this._dPadUp;
  70898. },
  70899. set: function (value) {
  70900. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70901. },
  70902. enumerable: true,
  70903. configurable: true
  70904. });
  70905. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70906. /** Gets or sets value of DPad down */
  70907. get: function () {
  70908. return this._dPadDown;
  70909. },
  70910. set: function (value) {
  70911. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70917. /** Gets or sets value of DPad left */
  70918. get: function () {
  70919. return this._dPadLeft;
  70920. },
  70921. set: function (value) {
  70922. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70923. },
  70924. enumerable: true,
  70925. configurable: true
  70926. });
  70927. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70928. /** Gets or sets value of DPad right */
  70929. get: function () {
  70930. return this._dPadRight;
  70931. },
  70932. set: function (value) {
  70933. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70934. },
  70935. enumerable: true,
  70936. configurable: true
  70937. });
  70938. /**
  70939. * Force the gamepad to synchronize with device values
  70940. */
  70941. Xbox360Pad.prototype.update = function () {
  70942. _super.prototype.update.call(this);
  70943. if (this._isXboxOnePad) {
  70944. this.buttonA = this.browserGamepad.buttons[0].value;
  70945. this.buttonB = this.browserGamepad.buttons[1].value;
  70946. this.buttonX = this.browserGamepad.buttons[2].value;
  70947. this.buttonY = this.browserGamepad.buttons[3].value;
  70948. this.buttonLB = this.browserGamepad.buttons[4].value;
  70949. this.buttonRB = this.browserGamepad.buttons[5].value;
  70950. this.leftTrigger = this.browserGamepad.axes[2];
  70951. this.rightTrigger = this.browserGamepad.axes[5];
  70952. this.buttonBack = this.browserGamepad.buttons[9].value;
  70953. this.buttonStart = this.browserGamepad.buttons[8].value;
  70954. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70955. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70956. this.dPadUp = this.browserGamepad.buttons[11].value;
  70957. this.dPadDown = this.browserGamepad.buttons[12].value;
  70958. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70959. this.dPadRight = this.browserGamepad.buttons[14].value;
  70960. }
  70961. else {
  70962. this.buttonA = this.browserGamepad.buttons[0].value;
  70963. this.buttonB = this.browserGamepad.buttons[1].value;
  70964. this.buttonX = this.browserGamepad.buttons[2].value;
  70965. this.buttonY = this.browserGamepad.buttons[3].value;
  70966. this.buttonLB = this.browserGamepad.buttons[4].value;
  70967. this.buttonRB = this.browserGamepad.buttons[5].value;
  70968. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70969. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70970. this.buttonBack = this.browserGamepad.buttons[8].value;
  70971. this.buttonStart = this.browserGamepad.buttons[9].value;
  70972. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70973. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70974. this.dPadUp = this.browserGamepad.buttons[12].value;
  70975. this.dPadDown = this.browserGamepad.buttons[13].value;
  70976. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70977. this.dPadRight = this.browserGamepad.buttons[15].value;
  70978. }
  70979. };
  70980. Xbox360Pad.prototype.dispose = function () {
  70981. _super.prototype.dispose.call(this);
  70982. this.onButtonDownObservable.clear();
  70983. this.onButtonUpObservable.clear();
  70984. this.onPadDownObservable.clear();
  70985. this.onPadUpObservable.clear();
  70986. };
  70987. return Xbox360Pad;
  70988. }(BABYLON.Gamepad));
  70989. BABYLON.Xbox360Pad = Xbox360Pad;
  70990. })(BABYLON || (BABYLON = {}));
  70991. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70992. var BABYLON;
  70993. (function (BABYLON) {
  70994. /**
  70995. * Defines the types of pose enabled controllers that are supported
  70996. */
  70997. var PoseEnabledControllerType;
  70998. (function (PoseEnabledControllerType) {
  70999. /**
  71000. * HTC Vive
  71001. */
  71002. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71003. /**
  71004. * Oculus Rift
  71005. */
  71006. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71007. /**
  71008. * Windows mixed reality
  71009. */
  71010. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71011. /**
  71012. * Samsung gear VR
  71013. */
  71014. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71015. /**
  71016. * Google Daydream
  71017. */
  71018. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71019. /**
  71020. * Generic
  71021. */
  71022. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71023. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71024. /**
  71025. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71026. */
  71027. var PoseEnabledControllerHelper = /** @class */ (function () {
  71028. function PoseEnabledControllerHelper() {
  71029. }
  71030. /**
  71031. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71032. * @param vrGamepad the gamepad to initialized
  71033. * @returns a vr controller of the type the gamepad identified as
  71034. */
  71035. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71036. // Oculus Touch
  71037. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71038. return new BABYLON.OculusTouchController(vrGamepad);
  71039. }
  71040. // Windows Mixed Reality controllers
  71041. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71042. return new BABYLON.WindowsMotionController(vrGamepad);
  71043. }
  71044. // HTC Vive
  71045. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71046. return new BABYLON.ViveController(vrGamepad);
  71047. }
  71048. // Samsung/Oculus Gear VR
  71049. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  71050. return new BABYLON.GearVRController(vrGamepad);
  71051. }
  71052. // Google Daydream
  71053. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71054. return new BABYLON.DaydreamController(vrGamepad);
  71055. }
  71056. // Generic
  71057. else {
  71058. return new BABYLON.GenericController(vrGamepad);
  71059. }
  71060. };
  71061. return PoseEnabledControllerHelper;
  71062. }());
  71063. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71064. /**
  71065. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71066. */
  71067. var PoseEnabledController = /** @class */ (function (_super) {
  71068. __extends(PoseEnabledController, _super);
  71069. /**
  71070. * Creates a new PoseEnabledController from a gamepad
  71071. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71072. */
  71073. function PoseEnabledController(browserGamepad) {
  71074. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71075. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71076. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71077. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71078. /**
  71079. * The device position in babylon space
  71080. */
  71081. _this.devicePosition = BABYLON.Vector3.Zero();
  71082. /**
  71083. * The device rotation in babylon space
  71084. */
  71085. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71086. /**
  71087. * The scale factor of the device in babylon space
  71088. */
  71089. _this.deviceScaleFactor = 1;
  71090. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71091. /**
  71092. * Internal, matrix used to convert room space to babylon space
  71093. */
  71094. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71095. /**
  71096. * Node to be used when casting a ray from the controller
  71097. */
  71098. _this._pointingPoseNode = null;
  71099. _this._workingMatrix = BABYLON.Matrix.Identity();
  71100. /**
  71101. * @hidden
  71102. */
  71103. _this._meshAttachedObservable = new BABYLON.Observable();
  71104. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71105. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71106. _this.position = BABYLON.Vector3.Zero();
  71107. _this.rotationQuaternion = new BABYLON.Quaternion();
  71108. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71109. _this._calculatedRotation = new BABYLON.Quaternion();
  71110. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71111. return _this;
  71112. }
  71113. /**
  71114. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71115. */
  71116. PoseEnabledController.prototype.update = function () {
  71117. _super.prototype.update.call(this);
  71118. var pose = this.browserGamepad.pose;
  71119. this.updateFromDevice(pose);
  71120. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71121. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71122. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71123. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71124. if (this._mesh) {
  71125. this._mesh.position.copyFrom(this.devicePosition);
  71126. if (this._mesh.rotationQuaternion) {
  71127. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71128. }
  71129. }
  71130. };
  71131. /**
  71132. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71133. * @param poseData raw pose fromthe device
  71134. */
  71135. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71136. if (poseData) {
  71137. this.rawPose = poseData;
  71138. if (poseData.position) {
  71139. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71140. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71141. this._deviceRoomPosition.z *= -1;
  71142. }
  71143. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71144. this._calculatedPosition.addInPlace(this.position);
  71145. }
  71146. var pose = this.rawPose;
  71147. if (poseData.orientation && pose.orientation) {
  71148. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71149. if (this._mesh) {
  71150. if (this._mesh.getScene().useRightHandedSystem) {
  71151. this._deviceRoomRotationQuaternion.z *= -1;
  71152. this._deviceRoomRotationQuaternion.w *= -1;
  71153. }
  71154. else {
  71155. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71156. }
  71157. }
  71158. // if the camera is set, rotate to the camera's rotation
  71159. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71160. }
  71161. }
  71162. };
  71163. /**
  71164. * Attaches a mesh to the controller
  71165. * @param mesh the mesh to be attached
  71166. */
  71167. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71168. if (this._mesh) {
  71169. this._mesh.parent = null;
  71170. }
  71171. this._mesh = mesh;
  71172. if (this._poseControlledCamera) {
  71173. this._mesh.parent = this._poseControlledCamera;
  71174. }
  71175. if (!this._mesh.rotationQuaternion) {
  71176. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71177. }
  71178. this._meshAttachedObservable.notifyObservers(mesh);
  71179. };
  71180. /**
  71181. * Attaches the controllers mesh to a camera
  71182. * @param camera the camera the mesh should be attached to
  71183. */
  71184. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71185. this._poseControlledCamera = camera;
  71186. if (this._mesh) {
  71187. this._mesh.parent = this._poseControlledCamera;
  71188. }
  71189. };
  71190. /**
  71191. * Disposes of the controller
  71192. */
  71193. PoseEnabledController.prototype.dispose = function () {
  71194. if (this._mesh) {
  71195. this._mesh.dispose();
  71196. }
  71197. this._mesh = null;
  71198. _super.prototype.dispose.call(this);
  71199. };
  71200. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71201. /**
  71202. * The mesh that is attached to the controller
  71203. */
  71204. get: function () {
  71205. return this._mesh;
  71206. },
  71207. enumerable: true,
  71208. configurable: true
  71209. });
  71210. /**
  71211. * Gets the ray of the controller in the direction the controller is pointing
  71212. * @param length the length the resulting ray should be
  71213. * @returns a ray in the direction the controller is pointing
  71214. */
  71215. PoseEnabledController.prototype.getForwardRay = function (length) {
  71216. if (length === void 0) { length = 100; }
  71217. if (!this.mesh) {
  71218. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71219. }
  71220. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71221. var origin = m.getTranslation();
  71222. var forward = new BABYLON.Vector3(0, 0, -1);
  71223. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71224. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71225. return new BABYLON.Ray(origin, direction, length);
  71226. };
  71227. /**
  71228. * Name of the child mesh that can be used to cast a ray from the controller
  71229. */
  71230. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71231. return PoseEnabledController;
  71232. }(BABYLON.Gamepad));
  71233. BABYLON.PoseEnabledController = PoseEnabledController;
  71234. })(BABYLON || (BABYLON = {}));
  71235. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71236. var BABYLON;
  71237. (function (BABYLON) {
  71238. /**
  71239. * Defines the WebVRController object that represents controllers tracked in 3D space
  71240. */
  71241. var WebVRController = /** @class */ (function (_super) {
  71242. __extends(WebVRController, _super);
  71243. /**
  71244. * Creates a new WebVRController from a gamepad
  71245. * @param vrGamepad the gamepad that the WebVRController should be created from
  71246. */
  71247. function WebVRController(vrGamepad) {
  71248. var _this = _super.call(this, vrGamepad) || this;
  71249. // Observables
  71250. /**
  71251. * Fired when the trigger state has changed
  71252. */
  71253. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71254. /**
  71255. * Fired when the main button state has changed
  71256. */
  71257. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71258. /**
  71259. * Fired when the secondary button state has changed
  71260. */
  71261. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71262. /**
  71263. * Fired when the pad state has changed
  71264. */
  71265. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71266. /**
  71267. * Fired when controllers stick values have changed
  71268. */
  71269. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71270. /**
  71271. * X and Y axis corrisponding to the controllers joystick
  71272. */
  71273. _this.pad = { x: 0, y: 0 };
  71274. // avoid GC, store state in a tmp object
  71275. _this._changes = {
  71276. pressChanged: false,
  71277. touchChanged: false,
  71278. valueChanged: false,
  71279. changed: false
  71280. };
  71281. _this._buttons = new Array(vrGamepad.buttons.length);
  71282. _this.hand = vrGamepad.hand;
  71283. return _this;
  71284. }
  71285. /**
  71286. * Fired when a controller button's state has changed
  71287. * @param callback the callback containing the button that was modified
  71288. */
  71289. WebVRController.prototype.onButtonStateChange = function (callback) {
  71290. this._onButtonStateChange = callback;
  71291. };
  71292. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71293. /**
  71294. * The default controller model for the controller
  71295. */
  71296. get: function () {
  71297. return this._defaultModel;
  71298. },
  71299. enumerable: true,
  71300. configurable: true
  71301. });
  71302. /**
  71303. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71304. */
  71305. WebVRController.prototype.update = function () {
  71306. _super.prototype.update.call(this);
  71307. for (var index = 0; index < this._buttons.length; index++) {
  71308. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71309. }
  71310. ;
  71311. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71312. this.pad.x = this.leftStick.x;
  71313. this.pad.y = this.leftStick.y;
  71314. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71315. }
  71316. };
  71317. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71318. if (!newState) {
  71319. newState = {
  71320. pressed: false,
  71321. touched: false,
  71322. value: 0
  71323. };
  71324. }
  71325. if (!currentState) {
  71326. this._buttons[buttonIndex] = {
  71327. pressed: newState.pressed,
  71328. touched: newState.touched,
  71329. value: newState.value
  71330. };
  71331. return;
  71332. }
  71333. this._checkChanges(newState, currentState);
  71334. if (this._changes.changed) {
  71335. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71336. this._handleButtonChange(buttonIndex, newState, this._changes);
  71337. }
  71338. this._buttons[buttonIndex].pressed = newState.pressed;
  71339. this._buttons[buttonIndex].touched = newState.touched;
  71340. // oculus triggers are never 0, thou not touched.
  71341. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71342. };
  71343. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71344. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71345. this._changes.touchChanged = newState.touched !== currentState.touched;
  71346. this._changes.valueChanged = newState.value !== currentState.value;
  71347. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71348. return this._changes;
  71349. };
  71350. /**
  71351. * Disposes of th webVRCOntroller
  71352. */
  71353. WebVRController.prototype.dispose = function () {
  71354. _super.prototype.dispose.call(this);
  71355. this.onTriggerStateChangedObservable.clear();
  71356. this.onMainButtonStateChangedObservable.clear();
  71357. this.onSecondaryButtonStateChangedObservable.clear();
  71358. this.onPadStateChangedObservable.clear();
  71359. this.onPadValuesChangedObservable.clear();
  71360. };
  71361. return WebVRController;
  71362. }(BABYLON.PoseEnabledController));
  71363. BABYLON.WebVRController = WebVRController;
  71364. })(BABYLON || (BABYLON = {}));
  71365. //# sourceMappingURL=babylon.webVRController.js.map
  71366. var BABYLON;
  71367. (function (BABYLON) {
  71368. /**
  71369. * Oculus Touch Controller
  71370. */
  71371. var OculusTouchController = /** @class */ (function (_super) {
  71372. __extends(OculusTouchController, _super);
  71373. /**
  71374. * Creates a new OculusTouchController from a gamepad
  71375. * @param vrGamepad the gamepad that the controller should be created from
  71376. */
  71377. function OculusTouchController(vrGamepad) {
  71378. var _this = _super.call(this, vrGamepad) || this;
  71379. /**
  71380. * Fired when the secondary trigger on this controller is modified
  71381. */
  71382. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71383. /**
  71384. * Fired when the thumb rest on this controller is modified
  71385. */
  71386. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71387. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71388. return _this;
  71389. }
  71390. /**
  71391. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71392. * @param scene scene in which to add meshes
  71393. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71394. */
  71395. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71396. var _this = this;
  71397. var meshName;
  71398. // Hand
  71399. if (this.hand === 'left') {
  71400. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71401. }
  71402. else { // Right is the default if no hand is specified
  71403. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71404. }
  71405. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71406. /*
  71407. Parent Mesh name: oculus_touch_left
  71408. - body
  71409. - trigger
  71410. - thumbstick
  71411. - grip
  71412. - button_y
  71413. - button_x
  71414. - button_enter
  71415. */
  71416. _this._defaultModel = newMeshes[1];
  71417. _this.attachToMesh(_this._defaultModel);
  71418. if (meshLoaded) {
  71419. meshLoaded(_this._defaultModel);
  71420. }
  71421. });
  71422. };
  71423. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71424. /**
  71425. * Fired when the A button on this controller is modified
  71426. */
  71427. get: function () {
  71428. if (this.hand === 'right') {
  71429. return this.onMainButtonStateChangedObservable;
  71430. }
  71431. else {
  71432. throw new Error('No A button on left hand');
  71433. }
  71434. },
  71435. enumerable: true,
  71436. configurable: true
  71437. });
  71438. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71439. /**
  71440. * Fired when the B button on this controller is modified
  71441. */
  71442. get: function () {
  71443. if (this.hand === 'right') {
  71444. return this.onSecondaryButtonStateChangedObservable;
  71445. }
  71446. else {
  71447. throw new Error('No B button on left hand');
  71448. }
  71449. },
  71450. enumerable: true,
  71451. configurable: true
  71452. });
  71453. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71454. /**
  71455. * Fired when the X button on this controller is modified
  71456. */
  71457. get: function () {
  71458. if (this.hand === 'left') {
  71459. return this.onMainButtonStateChangedObservable;
  71460. }
  71461. else {
  71462. throw new Error('No X button on right hand');
  71463. }
  71464. },
  71465. enumerable: true,
  71466. configurable: true
  71467. });
  71468. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71469. /**
  71470. * Fired when the Y button on this controller is modified
  71471. */
  71472. get: function () {
  71473. if (this.hand === 'left') {
  71474. return this.onSecondaryButtonStateChangedObservable;
  71475. }
  71476. else {
  71477. throw new Error('No Y button on right hand');
  71478. }
  71479. },
  71480. enumerable: true,
  71481. configurable: true
  71482. });
  71483. /**
  71484. * Called once for each button that changed state since the last frame
  71485. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71486. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71487. * 2) secondary trigger (same)
  71488. * 3) A (right) X (left), touch, pressed = value
  71489. * 4) B / Y
  71490. * 5) thumb rest
  71491. * @param buttonIdx Which button index changed
  71492. * @param state New state of the button
  71493. * @param changes Which properties on the state changed since last frame
  71494. */
  71495. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71496. var notifyObject = state; //{ state: state, changes: changes };
  71497. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71498. switch (buttonIdx) {
  71499. case 0:
  71500. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71501. return;
  71502. case 1: // index trigger
  71503. if (this._defaultModel) {
  71504. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71505. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71506. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71507. }
  71508. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71509. return;
  71510. case 2: // secondary trigger
  71511. if (this._defaultModel) {
  71512. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71513. }
  71514. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71515. return;
  71516. case 3:
  71517. if (this._defaultModel) {
  71518. if (notifyObject.pressed) {
  71519. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71520. }
  71521. else {
  71522. (this._defaultModel.getChildren()[1]).position.y = 0;
  71523. }
  71524. }
  71525. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71526. return;
  71527. case 4:
  71528. if (this._defaultModel) {
  71529. if (notifyObject.pressed) {
  71530. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71531. }
  71532. else {
  71533. (this._defaultModel.getChildren()[2]).position.y = 0;
  71534. }
  71535. }
  71536. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71537. return;
  71538. case 5:
  71539. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71540. return;
  71541. }
  71542. };
  71543. /**
  71544. * Base Url for the controller model.
  71545. */
  71546. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71547. /**
  71548. * File name for the left controller model.
  71549. */
  71550. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71551. /**
  71552. * File name for the right controller model.
  71553. */
  71554. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71555. return OculusTouchController;
  71556. }(BABYLON.WebVRController));
  71557. BABYLON.OculusTouchController = OculusTouchController;
  71558. })(BABYLON || (BABYLON = {}));
  71559. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71560. var BABYLON;
  71561. (function (BABYLON) {
  71562. /**
  71563. * Vive Controller
  71564. */
  71565. var ViveController = /** @class */ (function (_super) {
  71566. __extends(ViveController, _super);
  71567. /**
  71568. * Creates a new ViveController from a gamepad
  71569. * @param vrGamepad the gamepad that the controller should be created from
  71570. */
  71571. function ViveController(vrGamepad) {
  71572. var _this = _super.call(this, vrGamepad) || this;
  71573. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71574. _this._invertLeftStickY = true;
  71575. return _this;
  71576. }
  71577. /**
  71578. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71579. * @param scene scene in which to add meshes
  71580. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71581. */
  71582. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71583. var _this = this;
  71584. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71585. /*
  71586. Parent Mesh name: ViveWand
  71587. - body
  71588. - r_gripper
  71589. - l_gripper
  71590. - menu_button
  71591. - system_button
  71592. - trackpad
  71593. - trigger
  71594. - LED
  71595. */
  71596. _this._defaultModel = newMeshes[1];
  71597. _this.attachToMesh(_this._defaultModel);
  71598. if (meshLoaded) {
  71599. meshLoaded(_this._defaultModel);
  71600. }
  71601. });
  71602. };
  71603. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71604. /**
  71605. * Fired when the left button on this controller is modified
  71606. */
  71607. get: function () {
  71608. return this.onMainButtonStateChangedObservable;
  71609. },
  71610. enumerable: true,
  71611. configurable: true
  71612. });
  71613. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71614. /**
  71615. * Fired when the right button on this controller is modified
  71616. */
  71617. get: function () {
  71618. return this.onMainButtonStateChangedObservable;
  71619. },
  71620. enumerable: true,
  71621. configurable: true
  71622. });
  71623. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71624. /**
  71625. * Fired when the menu button on this controller is modified
  71626. */
  71627. get: function () {
  71628. return this.onSecondaryButtonStateChangedObservable;
  71629. },
  71630. enumerable: true,
  71631. configurable: true
  71632. });
  71633. /**
  71634. * Called once for each button that changed state since the last frame
  71635. * Vive mapping:
  71636. * 0: touchpad
  71637. * 1: trigger
  71638. * 2: left AND right buttons
  71639. * 3: menu button
  71640. * @param buttonIdx Which button index changed
  71641. * @param state New state of the button
  71642. * @param changes Which properties on the state changed since last frame
  71643. */
  71644. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71645. var notifyObject = state; //{ state: state, changes: changes };
  71646. switch (buttonIdx) {
  71647. case 0:
  71648. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71649. return;
  71650. case 1: // index trigger
  71651. if (this._defaultModel) {
  71652. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71653. }
  71654. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71655. return;
  71656. case 2: // left AND right button
  71657. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71658. return;
  71659. case 3:
  71660. if (this._defaultModel) {
  71661. if (notifyObject.pressed) {
  71662. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71663. }
  71664. else {
  71665. (this._defaultModel.getChildren()[2]).position.y = 0;
  71666. }
  71667. }
  71668. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71669. return;
  71670. }
  71671. };
  71672. /**
  71673. * Base Url for the controller model.
  71674. */
  71675. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71676. /**
  71677. * File name for the controller model.
  71678. */
  71679. ViveController.MODEL_FILENAME = 'wand.babylon';
  71680. return ViveController;
  71681. }(BABYLON.WebVRController));
  71682. BABYLON.ViveController = ViveController;
  71683. })(BABYLON || (BABYLON = {}));
  71684. //# sourceMappingURL=babylon.viveController.js.map
  71685. var BABYLON;
  71686. (function (BABYLON) {
  71687. /**
  71688. * Generic Controller
  71689. */
  71690. var GenericController = /** @class */ (function (_super) {
  71691. __extends(GenericController, _super);
  71692. /**
  71693. * Creates a new GenericController from a gamepad
  71694. * @param vrGamepad the gamepad that the controller should be created from
  71695. */
  71696. function GenericController(vrGamepad) {
  71697. return _super.call(this, vrGamepad) || this;
  71698. }
  71699. /**
  71700. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71701. * @param scene scene in which to add meshes
  71702. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71703. */
  71704. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71705. var _this = this;
  71706. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71707. _this._defaultModel = newMeshes[1];
  71708. _this.attachToMesh(_this._defaultModel);
  71709. if (meshLoaded) {
  71710. meshLoaded(_this._defaultModel);
  71711. }
  71712. });
  71713. };
  71714. /**
  71715. * Called once for each button that changed state since the last frame
  71716. * @param buttonIdx Which button index changed
  71717. * @param state New state of the button
  71718. * @param changes Which properties on the state changed since last frame
  71719. */
  71720. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71721. console.log("Button id: " + buttonIdx + "state: ");
  71722. console.dir(state);
  71723. };
  71724. /**
  71725. * Base Url for the controller model.
  71726. */
  71727. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71728. /**
  71729. * File name for the controller model.
  71730. */
  71731. GenericController.MODEL_FILENAME = 'generic.babylon';
  71732. return GenericController;
  71733. }(BABYLON.WebVRController));
  71734. BABYLON.GenericController = GenericController;
  71735. })(BABYLON || (BABYLON = {}));
  71736. //# sourceMappingURL=babylon.genericController.js.map
  71737. var BABYLON;
  71738. (function (BABYLON) {
  71739. /**
  71740. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71741. */
  71742. var LoadedMeshInfo = /** @class */ (function () {
  71743. function LoadedMeshInfo() {
  71744. /**
  71745. * Map of the button meshes contained in the controller
  71746. */
  71747. this.buttonMeshes = {};
  71748. /**
  71749. * Map of the axis meshes contained in the controller
  71750. */
  71751. this.axisMeshes = {};
  71752. }
  71753. return LoadedMeshInfo;
  71754. }());
  71755. /**
  71756. * Defines the WindowsMotionController object that the state of the windows motion controller
  71757. */
  71758. var WindowsMotionController = /** @class */ (function (_super) {
  71759. __extends(WindowsMotionController, _super);
  71760. /**
  71761. * Creates a new WindowsMotionController from a gamepad
  71762. * @param vrGamepad the gamepad that the controller should be created from
  71763. */
  71764. function WindowsMotionController(vrGamepad) {
  71765. var _this = _super.call(this, vrGamepad) || this;
  71766. _this._mapping = {
  71767. // Semantic button names
  71768. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71769. // A mapping of the button name to glTF model node name
  71770. // that should be transformed by button value.
  71771. buttonMeshNames: {
  71772. 'trigger': 'SELECT',
  71773. 'menu': 'MENU',
  71774. 'grip': 'GRASP',
  71775. 'thumbstick': 'THUMBSTICK_PRESS',
  71776. 'trackpad': 'TOUCHPAD_PRESS'
  71777. },
  71778. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71779. buttonObservableNames: {
  71780. 'trigger': 'onTriggerStateChangedObservable',
  71781. 'menu': 'onSecondaryButtonStateChangedObservable',
  71782. 'grip': 'onMainButtonStateChangedObservable',
  71783. 'thumbstick': 'onPadStateChangedObservable',
  71784. 'trackpad': 'onTrackpadChangedObservable'
  71785. },
  71786. // A mapping of the axis name to glTF model node name
  71787. // that should be transformed by axis value.
  71788. // This array mirrors the browserGamepad.axes array, such that
  71789. // the mesh corresponding to axis 0 is in this array index 0.
  71790. axisMeshNames: [
  71791. 'THUMBSTICK_X',
  71792. 'THUMBSTICK_Y',
  71793. 'TOUCHPAD_TOUCH_X',
  71794. 'TOUCHPAD_TOUCH_Y'
  71795. ],
  71796. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71797. };
  71798. /**
  71799. * Fired when the trackpad on this controller is clicked
  71800. */
  71801. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71802. /**
  71803. * Fired when the trackpad on this controller is modified
  71804. */
  71805. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71806. /**
  71807. * The current x and y values of this controller's trackpad
  71808. */
  71809. _this.trackpad = { x: 0, y: 0 };
  71810. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71811. _this._loadedMeshInfo = null;
  71812. return _this;
  71813. }
  71814. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71815. /**
  71816. * Fired when the trigger on this controller is modified
  71817. */
  71818. get: function () {
  71819. return this.onTriggerStateChangedObservable;
  71820. },
  71821. enumerable: true,
  71822. configurable: true
  71823. });
  71824. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71825. /**
  71826. * Fired when the menu button on this controller is modified
  71827. */
  71828. get: function () {
  71829. return this.onSecondaryButtonStateChangedObservable;
  71830. },
  71831. enumerable: true,
  71832. configurable: true
  71833. });
  71834. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71835. /**
  71836. * Fired when the grip button on this controller is modified
  71837. */
  71838. get: function () {
  71839. return this.onMainButtonStateChangedObservable;
  71840. },
  71841. enumerable: true,
  71842. configurable: true
  71843. });
  71844. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71845. /**
  71846. * Fired when the thumbstick button on this controller is modified
  71847. */
  71848. get: function () {
  71849. return this.onPadStateChangedObservable;
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71855. /**
  71856. * Fired when the touchpad button on this controller is modified
  71857. */
  71858. get: function () {
  71859. return this.onTrackpadChangedObservable;
  71860. },
  71861. enumerable: true,
  71862. configurable: true
  71863. });
  71864. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71865. /**
  71866. * Fired when the touchpad values on this controller are modified
  71867. */
  71868. get: function () {
  71869. return this.onTrackpadValuesChangedObservable;
  71870. },
  71871. enumerable: true,
  71872. configurable: true
  71873. });
  71874. /**
  71875. * Called once per frame by the engine.
  71876. */
  71877. WindowsMotionController.prototype.update = function () {
  71878. _super.prototype.update.call(this);
  71879. if (this.browserGamepad.axes) {
  71880. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71881. this.trackpad.x = this.browserGamepad["axes"][2];
  71882. this.trackpad.y = this.browserGamepad["axes"][3];
  71883. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71884. }
  71885. // Only need to animate axes if there is a loaded mesh
  71886. if (this._loadedMeshInfo) {
  71887. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71888. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71889. }
  71890. }
  71891. }
  71892. };
  71893. /**
  71894. * Called once for each button that changed state since the last frame
  71895. * @param buttonIdx Which button index changed
  71896. * @param state New state of the button
  71897. * @param changes Which properties on the state changed since last frame
  71898. */
  71899. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71900. var buttonName = this._mapping.buttons[buttonIdx];
  71901. if (!buttonName) {
  71902. return;
  71903. }
  71904. // Only emit events for buttons that we know how to map from index to name
  71905. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71906. if (observable) {
  71907. observable.notifyObservers(state);
  71908. }
  71909. this._lerpButtonTransform(buttonName, state.value);
  71910. };
  71911. /**
  71912. * Moves the buttons on the controller mesh based on their current state
  71913. * @param buttonName the name of the button to move
  71914. * @param buttonValue the value of the button which determines the buttons new position
  71915. */
  71916. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71917. // If there is no loaded mesh, there is nothing to transform.
  71918. if (!this._loadedMeshInfo) {
  71919. return;
  71920. }
  71921. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71922. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71923. return;
  71924. }
  71925. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71926. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71927. };
  71928. /**
  71929. * Moves the axis on the controller mesh based on its current state
  71930. * @param axis the index of the axis
  71931. * @param axisValue the value of the axis which determines the meshes new position
  71932. * @hidden
  71933. */
  71934. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71935. if (!this._loadedMeshInfo) {
  71936. return;
  71937. }
  71938. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71939. if (!meshInfo) {
  71940. return;
  71941. }
  71942. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71943. return;
  71944. }
  71945. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71946. var lerpValue = axisValue * 0.5 + 0.5;
  71947. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71948. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71949. };
  71950. /**
  71951. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71952. * @param scene scene in which to add meshes
  71953. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71954. */
  71955. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71956. var _this = this;
  71957. if (forceDefault === void 0) { forceDefault = false; }
  71958. var path;
  71959. var filename;
  71960. // Checking if GLB loader is present
  71961. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71962. // Determine the device specific folder based on the ID suffix
  71963. var device = 'default';
  71964. if (this.id && !forceDefault) {
  71965. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71966. device = ((match && match[0]) || device);
  71967. }
  71968. // Hand
  71969. if (this.hand === 'left') {
  71970. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71971. }
  71972. else { // Right is the default if no hand is specified
  71973. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71974. }
  71975. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71976. }
  71977. else {
  71978. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71979. path = BABYLON.GenericController.MODEL_BASE_URL;
  71980. filename = BABYLON.GenericController.MODEL_FILENAME;
  71981. }
  71982. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71983. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71984. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71985. if (!_this._loadedMeshInfo) {
  71986. return;
  71987. }
  71988. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71989. _this.attachToMesh(_this._defaultModel);
  71990. if (meshLoaded) {
  71991. meshLoaded(_this._defaultModel);
  71992. }
  71993. }, null, function (scene, message) {
  71994. BABYLON.Tools.Log(message);
  71995. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71996. if (!forceDefault) {
  71997. _this.initControllerMesh(scene, meshLoaded, true);
  71998. }
  71999. });
  72000. };
  72001. /**
  72002. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72003. * can be transformed by button presses and axes values, based on this._mapping.
  72004. *
  72005. * @param scene scene in which the meshes exist
  72006. * @param meshes list of meshes that make up the controller model to process
  72007. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72008. */
  72009. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72010. var loadedMeshInfo = null;
  72011. // Create a new mesh to contain the glTF hierarchy
  72012. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72013. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72014. var childMesh = null;
  72015. for (var i = 0; i < meshes.length; i++) {
  72016. var mesh = meshes[i];
  72017. if (!mesh.parent) {
  72018. // Exclude controller meshes from picking results
  72019. mesh.isPickable = false;
  72020. // Handle root node, attach to the new parentMesh
  72021. childMesh = mesh;
  72022. break;
  72023. }
  72024. }
  72025. if (childMesh) {
  72026. childMesh.setParent(parentMesh);
  72027. // Create our mesh info. Note that this method will always return non-null.
  72028. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72029. }
  72030. else {
  72031. BABYLON.Tools.Warn('Could not find root node in model file.');
  72032. }
  72033. return loadedMeshInfo;
  72034. };
  72035. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72036. var loadedMeshInfo = new LoadedMeshInfo();
  72037. var i;
  72038. loadedMeshInfo.rootNode = rootNode;
  72039. // Reset the caches
  72040. loadedMeshInfo.buttonMeshes = {};
  72041. loadedMeshInfo.axisMeshes = {};
  72042. // Button Meshes
  72043. for (i = 0; i < this._mapping.buttons.length; i++) {
  72044. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72045. if (!buttonMeshName) {
  72046. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72047. continue;
  72048. }
  72049. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72050. if (!buttonMesh) {
  72051. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72052. continue;
  72053. }
  72054. var buttonMeshInfo = {
  72055. index: i,
  72056. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72057. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72058. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72059. };
  72060. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72061. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72062. }
  72063. else {
  72064. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72065. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72066. '(VALUE: ' + !!buttonMeshInfo.value +
  72067. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72068. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72069. ')');
  72070. }
  72071. }
  72072. // Axis Meshes
  72073. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72074. var axisMeshName = this._mapping.axisMeshNames[i];
  72075. if (!axisMeshName) {
  72076. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72077. continue;
  72078. }
  72079. var axisMesh = getChildByName(rootNode, axisMeshName);
  72080. if (!axisMesh) {
  72081. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72082. continue;
  72083. }
  72084. var axisMeshInfo = {
  72085. index: i,
  72086. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72087. min: getImmediateChildByName(axisMesh, 'MIN'),
  72088. max: getImmediateChildByName(axisMesh, 'MAX')
  72089. };
  72090. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72091. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72092. }
  72093. else {
  72094. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72095. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72096. '(VALUE: ' + !!axisMeshInfo.value +
  72097. ', MIN: ' + !!axisMeshInfo.min +
  72098. ', MAX:' + !!axisMeshInfo.max +
  72099. ')');
  72100. }
  72101. }
  72102. // Pointing Ray
  72103. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72104. if (!loadedMeshInfo.pointingPoseNode) {
  72105. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72106. }
  72107. return loadedMeshInfo;
  72108. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72109. function getChildByName(node, name) {
  72110. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72111. }
  72112. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72113. function getImmediateChildByName(node, name) {
  72114. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72115. }
  72116. };
  72117. /**
  72118. * Gets the ray of the controller in the direction the controller is pointing
  72119. * @param length the length the resulting ray should be
  72120. * @returns a ray in the direction the controller is pointing
  72121. */
  72122. WindowsMotionController.prototype.getForwardRay = function (length) {
  72123. if (length === void 0) { length = 100; }
  72124. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72125. return _super.prototype.getForwardRay.call(this, length);
  72126. }
  72127. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72128. var origin = m.getTranslation();
  72129. var forward = new BABYLON.Vector3(0, 0, -1);
  72130. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72131. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72132. return new BABYLON.Ray(origin, direction, length);
  72133. };
  72134. /**
  72135. * Disposes of the controller
  72136. */
  72137. WindowsMotionController.prototype.dispose = function () {
  72138. _super.prototype.dispose.call(this);
  72139. this.onTrackpadChangedObservable.clear();
  72140. };
  72141. /**
  72142. * The base url used to load the left and right controller models
  72143. */
  72144. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72145. /**
  72146. * The name of the left controller model file
  72147. */
  72148. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72149. /**
  72150. * The name of the right controller model file
  72151. */
  72152. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72153. /**
  72154. * The controller name prefix for this controller type
  72155. */
  72156. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72157. /**
  72158. * The controller id pattern for this controller type
  72159. */
  72160. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72161. return WindowsMotionController;
  72162. }(BABYLON.WebVRController));
  72163. BABYLON.WindowsMotionController = WindowsMotionController;
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72166. var BABYLON;
  72167. (function (BABYLON) {
  72168. /**
  72169. * Gear VR Controller
  72170. */
  72171. var GearVRController = /** @class */ (function (_super) {
  72172. __extends(GearVRController, _super);
  72173. /**
  72174. * Creates a new GearVRController from a gamepad
  72175. * @param vrGamepad the gamepad that the controller should be created from
  72176. */
  72177. function GearVRController(vrGamepad) {
  72178. var _this = _super.call(this, vrGamepad) || this;
  72179. _this._buttonIndexToObservableNameMap = [
  72180. 'onTrackpadChangedObservable',
  72181. 'onTriggerStateChangedObservable' // Trigger
  72182. ];
  72183. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72184. return _this;
  72185. }
  72186. /**
  72187. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72188. * @param scene scene in which to add meshes
  72189. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72190. */
  72191. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72192. var _this = this;
  72193. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72194. _this._defaultModel = newMeshes[1];
  72195. _this.attachToMesh(_this._defaultModel);
  72196. if (meshLoaded) {
  72197. meshLoaded(_this._defaultModel);
  72198. }
  72199. });
  72200. };
  72201. /**
  72202. * Called once for each button that changed state since the last frame
  72203. * @param buttonIdx Which button index changed
  72204. * @param state New state of the button
  72205. * @param changes Which properties on the state changed since last frame
  72206. */
  72207. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72208. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72209. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72210. // Only emit events for buttons that we know how to map from index to observable
  72211. var observable = this[observableName];
  72212. if (observable) {
  72213. observable.notifyObservers(state);
  72214. }
  72215. }
  72216. };
  72217. /**
  72218. * Base Url for the controller model.
  72219. */
  72220. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72221. /**
  72222. * File name for the controller model.
  72223. */
  72224. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72225. /**
  72226. * Gamepad Id prefix used to identify this controller.
  72227. */
  72228. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72229. return GearVRController;
  72230. }(BABYLON.WebVRController));
  72231. BABYLON.GearVRController = GearVRController;
  72232. })(BABYLON || (BABYLON = {}));
  72233. //# sourceMappingURL=babylon.gearVRController.js.map
  72234. var BABYLON;
  72235. (function (BABYLON) {
  72236. /**
  72237. * Google Daydream controller
  72238. */
  72239. var DaydreamController = /** @class */ (function (_super) {
  72240. __extends(DaydreamController, _super);
  72241. /**
  72242. * Creates a new DaydreamController from a gamepad
  72243. * @param vrGamepad the gamepad that the controller should be created from
  72244. */
  72245. function DaydreamController(vrGamepad) {
  72246. var _this = _super.call(this, vrGamepad) || this;
  72247. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72248. return _this;
  72249. }
  72250. /**
  72251. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72252. * @param scene scene in which to add meshes
  72253. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72254. */
  72255. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72256. var _this = this;
  72257. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72258. _this._defaultModel = newMeshes[1];
  72259. _this.attachToMesh(_this._defaultModel);
  72260. if (meshLoaded) {
  72261. meshLoaded(_this._defaultModel);
  72262. }
  72263. });
  72264. };
  72265. /**
  72266. * Called once for each button that changed state since the last frame
  72267. * @param buttonIdx Which button index changed
  72268. * @param state New state of the button
  72269. * @param changes Which properties on the state changed since last frame
  72270. */
  72271. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72272. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72273. if (buttonIdx === 0) {
  72274. var observable = this.onTriggerStateChangedObservable;
  72275. if (observable) {
  72276. observable.notifyObservers(state);
  72277. }
  72278. }
  72279. else {
  72280. // If the app or home buttons are ever made available
  72281. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72282. }
  72283. };
  72284. /**
  72285. * Base Url for the controller model.
  72286. */
  72287. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72288. /**
  72289. * File name for the controller model.
  72290. */
  72291. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72292. /**
  72293. * Gamepad Id prefix used to identify Daydream Controller.
  72294. */
  72295. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72296. return DaydreamController;
  72297. }(BABYLON.WebVRController));
  72298. BABYLON.DaydreamController = DaydreamController;
  72299. })(BABYLON || (BABYLON = {}));
  72300. //# sourceMappingURL=babylon.daydreamController.js.map
  72301. var BABYLON;
  72302. (function (BABYLON) {
  72303. var FollowCamera = /** @class */ (function (_super) {
  72304. __extends(FollowCamera, _super);
  72305. function FollowCamera(name, position, scene, lockedTarget) {
  72306. if (lockedTarget === void 0) { lockedTarget = null; }
  72307. var _this = _super.call(this, name, position, scene) || this;
  72308. _this.radius = 12;
  72309. _this.rotationOffset = 0;
  72310. _this.heightOffset = 4;
  72311. _this.cameraAcceleration = 0.05;
  72312. _this.maxCameraSpeed = 20;
  72313. _this.lockedTarget = lockedTarget;
  72314. return _this;
  72315. }
  72316. FollowCamera.prototype.getRadians = function (degrees) {
  72317. return degrees * Math.PI / 180;
  72318. };
  72319. FollowCamera.prototype.follow = function (cameraTarget) {
  72320. if (!cameraTarget)
  72321. return;
  72322. var yRotation;
  72323. if (cameraTarget.rotationQuaternion) {
  72324. var rotMatrix = new BABYLON.Matrix();
  72325. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72326. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72327. }
  72328. else {
  72329. yRotation = cameraTarget.rotation.y;
  72330. }
  72331. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72332. var targetPosition = cameraTarget.getAbsolutePosition();
  72333. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72334. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72335. var dx = targetX - this.position.x;
  72336. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72337. var dz = (targetZ) - this.position.z;
  72338. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72339. var vy = dy * this.cameraAcceleration;
  72340. var vz = dz * this.cameraAcceleration * 2;
  72341. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72342. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72343. }
  72344. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72345. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72346. }
  72347. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72348. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72349. }
  72350. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72351. this.setTarget(targetPosition);
  72352. };
  72353. FollowCamera.prototype._checkInputs = function () {
  72354. _super.prototype._checkInputs.call(this);
  72355. if (this.lockedTarget) {
  72356. this.follow(this.lockedTarget);
  72357. }
  72358. };
  72359. FollowCamera.prototype.getClassName = function () {
  72360. return "FollowCamera";
  72361. };
  72362. __decorate([
  72363. BABYLON.serialize()
  72364. ], FollowCamera.prototype, "radius", void 0);
  72365. __decorate([
  72366. BABYLON.serialize()
  72367. ], FollowCamera.prototype, "rotationOffset", void 0);
  72368. __decorate([
  72369. BABYLON.serialize()
  72370. ], FollowCamera.prototype, "heightOffset", void 0);
  72371. __decorate([
  72372. BABYLON.serialize()
  72373. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72374. __decorate([
  72375. BABYLON.serialize()
  72376. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72377. __decorate([
  72378. BABYLON.serializeAsMeshReference("lockedTargetId")
  72379. ], FollowCamera.prototype, "lockedTarget", void 0);
  72380. return FollowCamera;
  72381. }(BABYLON.TargetCamera));
  72382. BABYLON.FollowCamera = FollowCamera;
  72383. var ArcFollowCamera = /** @class */ (function (_super) {
  72384. __extends(ArcFollowCamera, _super);
  72385. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72386. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72387. _this.alpha = alpha;
  72388. _this.beta = beta;
  72389. _this.radius = radius;
  72390. _this.target = target;
  72391. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72392. _this.follow();
  72393. return _this;
  72394. }
  72395. ArcFollowCamera.prototype.follow = function () {
  72396. if (!this.target) {
  72397. return;
  72398. }
  72399. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72400. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72401. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72402. var targetPosition = this.target.getAbsolutePosition();
  72403. this.position = targetPosition.add(this._cartesianCoordinates);
  72404. this.setTarget(targetPosition);
  72405. };
  72406. ArcFollowCamera.prototype._checkInputs = function () {
  72407. _super.prototype._checkInputs.call(this);
  72408. this.follow();
  72409. };
  72410. ArcFollowCamera.prototype.getClassName = function () {
  72411. return "ArcFollowCamera";
  72412. };
  72413. return ArcFollowCamera;
  72414. }(BABYLON.TargetCamera));
  72415. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72416. })(BABYLON || (BABYLON = {}));
  72417. //# sourceMappingURL=babylon.followCamera.js.map
  72418. var BABYLON;
  72419. (function (BABYLON) {
  72420. // We're mainly based on the logic defined into the FreeCamera code
  72421. var UniversalCamera = /** @class */ (function (_super) {
  72422. __extends(UniversalCamera, _super);
  72423. //-- end properties for backward compatibility for inputs
  72424. function UniversalCamera(name, position, scene) {
  72425. var _this = _super.call(this, name, position, scene) || this;
  72426. _this.inputs.addGamepad();
  72427. return _this;
  72428. }
  72429. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72430. //-- Begin properties for backward compatibility for inputs
  72431. get: function () {
  72432. var gamepad = this.inputs.attached["gamepad"];
  72433. if (gamepad)
  72434. return gamepad.gamepadAngularSensibility;
  72435. return 0;
  72436. },
  72437. set: function (value) {
  72438. var gamepad = this.inputs.attached["gamepad"];
  72439. if (gamepad)
  72440. gamepad.gamepadAngularSensibility = value;
  72441. },
  72442. enumerable: true,
  72443. configurable: true
  72444. });
  72445. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72446. get: function () {
  72447. var gamepad = this.inputs.attached["gamepad"];
  72448. if (gamepad)
  72449. return gamepad.gamepadMoveSensibility;
  72450. return 0;
  72451. },
  72452. set: function (value) {
  72453. var gamepad = this.inputs.attached["gamepad"];
  72454. if (gamepad)
  72455. gamepad.gamepadMoveSensibility = value;
  72456. },
  72457. enumerable: true,
  72458. configurable: true
  72459. });
  72460. UniversalCamera.prototype.getClassName = function () {
  72461. return "UniversalCamera";
  72462. };
  72463. return UniversalCamera;
  72464. }(BABYLON.TouchCamera));
  72465. BABYLON.UniversalCamera = UniversalCamera;
  72466. })(BABYLON || (BABYLON = {}));
  72467. //# sourceMappingURL=babylon.universalCamera.js.map
  72468. var BABYLON;
  72469. (function (BABYLON) {
  72470. // We're mainly based on the logic defined into the FreeCamera code
  72471. var GamepadCamera = /** @class */ (function (_super) {
  72472. __extends(GamepadCamera, _super);
  72473. //-- end properties for backward compatibility for inputs
  72474. function GamepadCamera(name, position, scene) {
  72475. return _super.call(this, name, position, scene) || this;
  72476. }
  72477. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72478. //-- Begin properties for backward compatibility for inputs
  72479. get: function () {
  72480. var gamepad = this.inputs.attached["gamepad"];
  72481. if (gamepad)
  72482. return gamepad.gamepadAngularSensibility;
  72483. return 0;
  72484. },
  72485. set: function (value) {
  72486. var gamepad = this.inputs.attached["gamepad"];
  72487. if (gamepad)
  72488. gamepad.gamepadAngularSensibility = value;
  72489. },
  72490. enumerable: true,
  72491. configurable: true
  72492. });
  72493. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72494. get: function () {
  72495. var gamepad = this.inputs.attached["gamepad"];
  72496. if (gamepad)
  72497. return gamepad.gamepadMoveSensibility;
  72498. return 0;
  72499. },
  72500. set: function (value) {
  72501. var gamepad = this.inputs.attached["gamepad"];
  72502. if (gamepad)
  72503. gamepad.gamepadMoveSensibility = value;
  72504. },
  72505. enumerable: true,
  72506. configurable: true
  72507. });
  72508. GamepadCamera.prototype.getClassName = function () {
  72509. return "GamepadCamera";
  72510. };
  72511. return GamepadCamera;
  72512. }(BABYLON.UniversalCamera));
  72513. BABYLON.GamepadCamera = GamepadCamera;
  72514. })(BABYLON || (BABYLON = {}));
  72515. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72516. var BABYLON;
  72517. (function (BABYLON) {
  72518. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72519. function PostProcessRenderPipelineManager() {
  72520. this._renderPipelines = {};
  72521. }
  72522. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72523. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72524. };
  72525. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72526. if (unique === void 0) { unique = false; }
  72527. var renderPipeline = this._renderPipelines[renderPipelineName];
  72528. if (!renderPipeline) {
  72529. return;
  72530. }
  72531. renderPipeline._attachCameras(cameras, unique);
  72532. };
  72533. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72534. var renderPipeline = this._renderPipelines[renderPipelineName];
  72535. if (!renderPipeline) {
  72536. return;
  72537. }
  72538. renderPipeline._detachCameras(cameras);
  72539. };
  72540. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72541. var renderPipeline = this._renderPipelines[renderPipelineName];
  72542. if (!renderPipeline) {
  72543. return;
  72544. }
  72545. renderPipeline._enableEffect(renderEffectName, cameras);
  72546. };
  72547. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72548. var renderPipeline = this._renderPipelines[renderPipelineName];
  72549. if (!renderPipeline) {
  72550. return;
  72551. }
  72552. renderPipeline._disableEffect(renderEffectName, cameras);
  72553. };
  72554. PostProcessRenderPipelineManager.prototype.update = function () {
  72555. for (var renderPipelineName in this._renderPipelines) {
  72556. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72557. var pipeline = this._renderPipelines[renderPipelineName];
  72558. if (!pipeline.isSupported) {
  72559. pipeline.dispose();
  72560. delete this._renderPipelines[renderPipelineName];
  72561. }
  72562. else {
  72563. pipeline._update();
  72564. }
  72565. }
  72566. }
  72567. };
  72568. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72569. for (var renderPipelineName in this._renderPipelines) {
  72570. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72571. var pipeline = this._renderPipelines[renderPipelineName];
  72572. pipeline._rebuild();
  72573. }
  72574. }
  72575. };
  72576. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72577. for (var renderPipelineName in this._renderPipelines) {
  72578. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72579. var pipeline = this._renderPipelines[renderPipelineName];
  72580. pipeline.dispose();
  72581. }
  72582. }
  72583. };
  72584. return PostProcessRenderPipelineManager;
  72585. }());
  72586. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72587. })(BABYLON || (BABYLON = {}));
  72588. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72589. var BABYLON;
  72590. (function (BABYLON) {
  72591. /**
  72592. * This represents a set of one or more post processes in Babylon.
  72593. * A post process can be used to apply a shader to a texture after it is rendered.
  72594. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72595. */
  72596. var PostProcessRenderEffect = /** @class */ (function () {
  72597. /**
  72598. * Instantiates a post process render effect.
  72599. * A post process can be used to apply a shader to a texture after it is rendered.
  72600. * @param engine The engine the effect is tied to
  72601. * @param name The name of the effect
  72602. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72603. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72604. */
  72605. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72606. this._name = name;
  72607. this._singleInstance = singleInstance || true;
  72608. this._getPostProcesses = getPostProcesses;
  72609. this._cameras = {};
  72610. this._indicesForCamera = {};
  72611. this._postProcesses = {};
  72612. }
  72613. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72614. /**
  72615. * Checks if all the post processes in the effect are supported.
  72616. */
  72617. get: function () {
  72618. for (var index in this._postProcesses) {
  72619. if (this._postProcesses.hasOwnProperty(index)) {
  72620. var pps = this._postProcesses[index];
  72621. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72622. if (!pps[ppIndex].isSupported) {
  72623. return false;
  72624. }
  72625. }
  72626. }
  72627. }
  72628. return true;
  72629. },
  72630. enumerable: true,
  72631. configurable: true
  72632. });
  72633. /**
  72634. * Updates the current state of the effect
  72635. */
  72636. PostProcessRenderEffect.prototype._update = function () {
  72637. };
  72638. /**
  72639. * Attaches the effect on cameras
  72640. * @param cameras The camera to attach to.
  72641. */
  72642. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72643. var _this = this;
  72644. var cameraKey;
  72645. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72646. if (!cams) {
  72647. return;
  72648. }
  72649. for (var i = 0; i < cams.length; i++) {
  72650. var camera = cams[i];
  72651. var cameraName = camera.name;
  72652. if (this._singleInstance) {
  72653. cameraKey = 0;
  72654. }
  72655. else {
  72656. cameraKey = cameraName;
  72657. }
  72658. if (!this._postProcesses[cameraKey]) {
  72659. var postProcess = this._getPostProcesses();
  72660. if (postProcess) {
  72661. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72662. }
  72663. }
  72664. if (!this._indicesForCamera[cameraName]) {
  72665. this._indicesForCamera[cameraName] = [];
  72666. }
  72667. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72668. var index = camera.attachPostProcess(postProcess);
  72669. _this._indicesForCamera[cameraName].push(index);
  72670. });
  72671. if (!this._cameras[cameraName]) {
  72672. this._cameras[cameraName] = camera;
  72673. }
  72674. }
  72675. };
  72676. /**
  72677. * Detatches the effect on cameras
  72678. * @param cameras The camera to detatch from.
  72679. */
  72680. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72682. if (!cams) {
  72683. return;
  72684. }
  72685. for (var i = 0; i < cams.length; i++) {
  72686. var camera = cams[i];
  72687. var cameraName = camera.name;
  72688. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72689. camera.detachPostProcess(postProcess);
  72690. });
  72691. if (this._cameras[cameraName]) {
  72692. //this._indicesForCamera.splice(index, 1);
  72693. this._cameras[cameraName] = null;
  72694. }
  72695. }
  72696. };
  72697. /**
  72698. * Enables the effect on given cameras
  72699. * @param cameras The camera to enable.
  72700. */
  72701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72702. var _this = this;
  72703. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72704. if (!cams) {
  72705. return;
  72706. }
  72707. for (var i = 0; i < cams.length; i++) {
  72708. var camera = cams[i];
  72709. var cameraName = camera.name;
  72710. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72711. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72712. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72713. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72714. });
  72715. }
  72716. }
  72717. }
  72718. };
  72719. /**
  72720. * Disables the effect on the given cameras
  72721. * @param cameras The camera to disable.
  72722. */
  72723. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72724. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72725. if (!cams) {
  72726. return;
  72727. }
  72728. for (var i = 0; i < cams.length; i++) {
  72729. var camera = cams[i];
  72730. var cameraName = camera.name;
  72731. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72732. camera.detachPostProcess(postProcess);
  72733. });
  72734. }
  72735. };
  72736. /**
  72737. * Gets a list of the post processes contained in the effect.
  72738. * @param camera The camera to get the post processes on.
  72739. * @returns The list of the post processes in the effect.
  72740. */
  72741. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72742. if (this._singleInstance) {
  72743. return this._postProcesses[0];
  72744. }
  72745. else {
  72746. if (!camera) {
  72747. return null;
  72748. }
  72749. return this._postProcesses[camera.name];
  72750. }
  72751. };
  72752. return PostProcessRenderEffect;
  72753. }());
  72754. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72755. })(BABYLON || (BABYLON = {}));
  72756. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72757. var BABYLON;
  72758. (function (BABYLON) {
  72759. var PostProcessRenderPipeline = /** @class */ (function () {
  72760. function PostProcessRenderPipeline(engine, name) {
  72761. this.engine = engine;
  72762. this._name = name;
  72763. this._renderEffects = {};
  72764. this._renderEffectsForIsolatedPass = new Array();
  72765. this._cameras = [];
  72766. }
  72767. PostProcessRenderPipeline.prototype.getClassName = function () {
  72768. return "PostProcessRenderPipeline";
  72769. };
  72770. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72771. get: function () {
  72772. for (var renderEffectName in this._renderEffects) {
  72773. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72774. if (!this._renderEffects[renderEffectName].isSupported) {
  72775. return false;
  72776. }
  72777. }
  72778. }
  72779. return true;
  72780. },
  72781. enumerable: true,
  72782. configurable: true
  72783. });
  72784. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72785. this._renderEffects[renderEffect._name] = renderEffect;
  72786. };
  72787. // private
  72788. PostProcessRenderPipeline.prototype._rebuild = function () {
  72789. };
  72790. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72791. var renderEffects = this._renderEffects[renderEffectName];
  72792. if (!renderEffects) {
  72793. return;
  72794. }
  72795. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72796. };
  72797. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72798. var renderEffects = this._renderEffects[renderEffectName];
  72799. if (!renderEffects) {
  72800. return;
  72801. }
  72802. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72803. };
  72804. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72805. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72806. if (!cams) {
  72807. return;
  72808. }
  72809. var indicesToDelete = [];
  72810. var i;
  72811. for (i = 0; i < cams.length; i++) {
  72812. var camera = cams[i];
  72813. var cameraName = camera.name;
  72814. if (this._cameras.indexOf(camera) === -1) {
  72815. this._cameras[cameraName] = camera;
  72816. }
  72817. else if (unique) {
  72818. indicesToDelete.push(i);
  72819. }
  72820. }
  72821. for (i = 0; i < indicesToDelete.length; i++) {
  72822. cameras.splice(indicesToDelete[i], 1);
  72823. }
  72824. for (var renderEffectName in this._renderEffects) {
  72825. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72826. this._renderEffects[renderEffectName]._attachCameras(cams);
  72827. }
  72828. }
  72829. };
  72830. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72831. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72832. if (!cams) {
  72833. return;
  72834. }
  72835. for (var renderEffectName in this._renderEffects) {
  72836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72837. this._renderEffects[renderEffectName]._detachCameras(cams);
  72838. }
  72839. }
  72840. for (var i = 0; i < cams.length; i++) {
  72841. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72842. }
  72843. };
  72844. PostProcessRenderPipeline.prototype._update = function () {
  72845. for (var renderEffectName in this._renderEffects) {
  72846. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72847. this._renderEffects[renderEffectName]._update();
  72848. }
  72849. }
  72850. for (var i = 0; i < this._cameras.length; i++) {
  72851. var cameraName = this._cameras[i].name;
  72852. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72853. this._renderEffectsForIsolatedPass[cameraName]._update();
  72854. }
  72855. }
  72856. };
  72857. PostProcessRenderPipeline.prototype._reset = function () {
  72858. this._renderEffects = {};
  72859. this._renderEffectsForIsolatedPass = new Array();
  72860. };
  72861. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72862. // 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)
  72863. var effectKeys = Object.keys(this._renderEffects);
  72864. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72865. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72866. if (postProcesses) {
  72867. postProcesses[0].samples = sampleCount;
  72868. return true;
  72869. }
  72870. }
  72871. return false;
  72872. };
  72873. PostProcessRenderPipeline.prototype.dispose = function () {
  72874. // Must be implemented by children
  72875. };
  72876. __decorate([
  72877. BABYLON.serialize()
  72878. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72879. return PostProcessRenderPipeline;
  72880. }());
  72881. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72882. })(BABYLON || (BABYLON = {}));
  72883. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72884. var BABYLON;
  72885. (function (BABYLON) {
  72886. /**
  72887. * This represents a depth renderer in Babylon.
  72888. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72889. */
  72890. var DepthRenderer = /** @class */ (function () {
  72891. /**
  72892. * Instantiates a depth renderer
  72893. * @param scene The scene the renderer belongs to
  72894. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72895. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72896. */
  72897. function DepthRenderer(scene, type, camera) {
  72898. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72899. if (camera === void 0) { camera = null; }
  72900. var _this = this;
  72901. this._scene = scene;
  72902. this._camera = camera;
  72903. var engine = scene.getEngine();
  72904. // Render target
  72905. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72906. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72907. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72908. this._depthMap.refreshRate = 1;
  72909. this._depthMap.renderParticles = false;
  72910. this._depthMap.renderList = null;
  72911. // Camera to get depth map from to support multiple concurrent cameras
  72912. this._depthMap.activeCamera = this._camera;
  72913. this._depthMap.ignoreCameraViewport = true;
  72914. this._depthMap.useCameraPostProcesses = false;
  72915. // set default depth value to 1.0 (far away)
  72916. this._depthMap.onClearObservable.add(function (engine) {
  72917. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72918. });
  72919. // Custom render function
  72920. var renderSubMesh = function (subMesh) {
  72921. var mesh = subMesh.getRenderingMesh();
  72922. var scene = _this._scene;
  72923. var engine = scene.getEngine();
  72924. var material = subMesh.getMaterial();
  72925. if (!material) {
  72926. return;
  72927. }
  72928. // Culling and reverse (right handed system)
  72929. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72930. // Managing instances
  72931. var batch = mesh._getInstancesRenderList(subMesh._id);
  72932. if (batch.mustReturn) {
  72933. return;
  72934. }
  72935. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72936. var camera = _this._camera || scene.activeCamera;
  72937. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72938. engine.enableEffect(_this._effect);
  72939. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72940. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72941. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72942. // Alpha test
  72943. if (material && material.needAlphaTesting()) {
  72944. var alphaTexture = material.getAlphaTestTexture();
  72945. if (alphaTexture) {
  72946. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72947. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72948. }
  72949. }
  72950. // Bones
  72951. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72952. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72953. }
  72954. // Draw
  72955. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72956. }
  72957. };
  72958. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72959. var index;
  72960. if (depthOnlySubMeshes.length) {
  72961. engine.setColorWrite(false);
  72962. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72963. renderSubMesh(depthOnlySubMeshes.data[index]);
  72964. }
  72965. engine.setColorWrite(true);
  72966. }
  72967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72968. renderSubMesh(opaqueSubMeshes.data[index]);
  72969. }
  72970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72971. renderSubMesh(alphaTestSubMeshes.data[index]);
  72972. }
  72973. };
  72974. }
  72975. /**
  72976. * Creates the depth rendering effect and checks if the effect is ready.
  72977. * @param subMesh The submesh to be used to render the depth map of
  72978. * @param useInstances If multiple world instances should be used
  72979. * @returns if the depth renderer is ready to render the depth map
  72980. */
  72981. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72982. var material = subMesh.getMaterial();
  72983. if (material.disableDepthWrite) {
  72984. return false;
  72985. }
  72986. var defines = [];
  72987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72988. var mesh = subMesh.getMesh();
  72989. // Alpha test
  72990. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72991. defines.push("#define ALPHATEST");
  72992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72993. attribs.push(BABYLON.VertexBuffer.UVKind);
  72994. defines.push("#define UV1");
  72995. }
  72996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72998. defines.push("#define UV2");
  72999. }
  73000. }
  73001. // Bones
  73002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73005. if (mesh.numBoneInfluencers > 4) {
  73006. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73007. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73008. }
  73009. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73010. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73011. }
  73012. else {
  73013. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73014. }
  73015. // Instances
  73016. if (useInstances) {
  73017. defines.push("#define INSTANCES");
  73018. attribs.push("world0");
  73019. attribs.push("world1");
  73020. attribs.push("world2");
  73021. attribs.push("world3");
  73022. }
  73023. // Get correct effect
  73024. var join = defines.join("\n");
  73025. if (this._cachedDefines !== join) {
  73026. this._cachedDefines = join;
  73027. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73028. }
  73029. return this._effect.isReady();
  73030. };
  73031. /**
  73032. * Gets the texture which the depth map will be written to.
  73033. * @returns The depth map texture
  73034. */
  73035. DepthRenderer.prototype.getDepthMap = function () {
  73036. return this._depthMap;
  73037. };
  73038. /**
  73039. * Disposes of the depth renderer.
  73040. */
  73041. DepthRenderer.prototype.dispose = function () {
  73042. this._depthMap.dispose();
  73043. };
  73044. return DepthRenderer;
  73045. }());
  73046. BABYLON.DepthRenderer = DepthRenderer;
  73047. })(BABYLON || (BABYLON = {}));
  73048. //# sourceMappingURL=babylon.depthRenderer.js.map
  73049. var BABYLON;
  73050. (function (BABYLON) {
  73051. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73052. __extends(SSAORenderingPipeline, _super);
  73053. /**
  73054. * @constructor
  73055. * @param {string} name - The rendering pipeline name
  73056. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73057. * @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 }
  73058. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73059. */
  73060. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73061. var _this = _super.call(this, scene.getEngine(), name) || this;
  73062. // Members
  73063. /**
  73064. * The PassPostProcess id in the pipeline that contains the original scene color
  73065. */
  73066. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73067. /**
  73068. * The SSAO PostProcess id in the pipeline
  73069. */
  73070. _this.SSAORenderEffect = "SSAORenderEffect";
  73071. /**
  73072. * The horizontal blur PostProcess id in the pipeline
  73073. */
  73074. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73075. /**
  73076. * The vertical blur PostProcess id in the pipeline
  73077. */
  73078. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73079. /**
  73080. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73081. */
  73082. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73083. /**
  73084. * The output strength of the SSAO post-process. Default value is 1.0.
  73085. */
  73086. _this.totalStrength = 1.0;
  73087. /**
  73088. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73089. */
  73090. _this.radius = 0.0001;
  73091. /**
  73092. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73093. * Must not be equal to fallOff and superior to fallOff.
  73094. * Default value is 0.975
  73095. */
  73096. _this.area = 0.0075;
  73097. /**
  73098. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73099. * Must not be equal to area and inferior to area.
  73100. * Default value is 0.0
  73101. */
  73102. _this.fallOff = 0.000001;
  73103. /**
  73104. * The base color of the SSAO post-process
  73105. * The final result is "base + ssao" between [0, 1]
  73106. */
  73107. _this.base = 0.5;
  73108. _this._firstUpdate = true;
  73109. _this._scene = scene;
  73110. // Set up assets
  73111. _this._createRandomTexture();
  73112. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73113. var ssaoRatio = ratio.ssaoRatio || ratio;
  73114. var combineRatio = ratio.combineRatio || ratio;
  73115. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73116. _this._createSSAOPostProcess(ssaoRatio);
  73117. _this._createBlurPostProcess(ssaoRatio);
  73118. _this._createSSAOCombinePostProcess(combineRatio);
  73119. // Set up pipeline
  73120. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73121. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73125. // Finish
  73126. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73127. if (cameras)
  73128. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73129. return _this;
  73130. }
  73131. // Public Methods
  73132. /**
  73133. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73134. */
  73135. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73136. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73137. for (var i = 0; i < this._scene.cameras.length; i++) {
  73138. var camera = this._scene.cameras[i];
  73139. this._originalColorPostProcess.dispose(camera);
  73140. this._ssaoPostProcess.dispose(camera);
  73141. this._blurHPostProcess.dispose(camera);
  73142. this._blurVPostProcess.dispose(camera);
  73143. this._ssaoCombinePostProcess.dispose(camera);
  73144. }
  73145. this._randomTexture.dispose();
  73146. if (disableDepthRender)
  73147. this._scene.disableDepthRenderer();
  73148. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73149. _super.prototype.dispose.call(this);
  73150. };
  73151. // Private Methods
  73152. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73153. var _this = this;
  73154. var size = 16;
  73155. 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);
  73156. 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);
  73157. this._blurHPostProcess.onActivateObservable.add(function () {
  73158. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73159. _this._blurHPostProcess.kernel = size * dw;
  73160. });
  73161. this._blurVPostProcess.onActivateObservable.add(function () {
  73162. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73163. _this._blurVPostProcess.kernel = size * dw;
  73164. });
  73165. };
  73166. SSAORenderingPipeline.prototype._rebuild = function () {
  73167. this._firstUpdate = true;
  73168. _super.prototype._rebuild.call(this);
  73169. };
  73170. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73171. var _this = this;
  73172. var numSamples = 16;
  73173. var sampleSphere = [
  73174. 0.5381, 0.1856, -0.4319,
  73175. 0.1379, 0.2486, 0.4430,
  73176. 0.3371, 0.5679, -0.0057,
  73177. -0.6999, -0.0451, -0.0019,
  73178. 0.0689, -0.1598, -0.8547,
  73179. 0.0560, 0.0069, -0.1843,
  73180. -0.0146, 0.1402, 0.0762,
  73181. 0.0100, -0.1924, -0.0344,
  73182. -0.3577, -0.5301, -0.4358,
  73183. -0.3169, 0.1063, 0.0158,
  73184. 0.0103, -0.5869, 0.0046,
  73185. -0.0897, -0.4940, 0.3287,
  73186. 0.7119, -0.0154, -0.0918,
  73187. -0.0533, 0.0596, -0.5411,
  73188. 0.0352, -0.0631, 0.5460,
  73189. -0.4776, 0.2847, -0.0271
  73190. ];
  73191. var samplesFactor = 1.0 / numSamples;
  73192. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73193. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73194. "area", "fallOff", "base", "range", "viewport"
  73195. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73196. this._ssaoPostProcess.onApply = function (effect) {
  73197. if (_this._firstUpdate) {
  73198. effect.setArray3("sampleSphere", sampleSphere);
  73199. effect.setFloat("samplesFactor", samplesFactor);
  73200. effect.setFloat("randTextureTiles", 4.0);
  73201. }
  73202. effect.setFloat("totalStrength", _this.totalStrength);
  73203. effect.setFloat("radius", _this.radius);
  73204. effect.setFloat("area", _this.area);
  73205. effect.setFloat("fallOff", _this.fallOff);
  73206. effect.setFloat("base", _this.base);
  73207. effect.setTexture("textureSampler", _this._depthTexture);
  73208. effect.setTexture("randomSampler", _this._randomTexture);
  73209. };
  73210. };
  73211. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73212. var _this = this;
  73213. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73214. this._ssaoCombinePostProcess.onApply = function (effect) {
  73215. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73216. };
  73217. };
  73218. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73219. var size = 512;
  73220. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73221. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73222. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73223. var context = this._randomTexture.getContext();
  73224. var rand = function (min, max) {
  73225. return Math.random() * (max - min) + min;
  73226. };
  73227. var randVector = BABYLON.Vector3.Zero();
  73228. for (var x = 0; x < size; x++) {
  73229. for (var y = 0; y < size; y++) {
  73230. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73231. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73232. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73233. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73234. context.fillRect(x, y, 1, 1);
  73235. }
  73236. }
  73237. this._randomTexture.update(false);
  73238. };
  73239. __decorate([
  73240. BABYLON.serialize()
  73241. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73242. __decorate([
  73243. BABYLON.serialize()
  73244. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73245. __decorate([
  73246. BABYLON.serialize()
  73247. ], SSAORenderingPipeline.prototype, "area", void 0);
  73248. __decorate([
  73249. BABYLON.serialize()
  73250. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73251. __decorate([
  73252. BABYLON.serialize()
  73253. ], SSAORenderingPipeline.prototype, "base", void 0);
  73254. return SSAORenderingPipeline;
  73255. }(BABYLON.PostProcessRenderPipeline));
  73256. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73257. })(BABYLON || (BABYLON = {}));
  73258. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73259. var BABYLON;
  73260. (function (BABYLON) {
  73261. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73262. __extends(SSAO2RenderingPipeline, _super);
  73263. /**
  73264. * @constructor
  73265. * @param {string} name - The rendering pipeline name
  73266. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73267. * @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 }
  73268. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73269. */
  73270. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73271. var _this = _super.call(this, scene.getEngine(), name) || this;
  73272. // Members
  73273. /**
  73274. * The PassPostProcess id in the pipeline that contains the original scene color
  73275. */
  73276. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73277. /**
  73278. * The SSAO PostProcess id in the pipeline
  73279. */
  73280. _this.SSAORenderEffect = "SSAORenderEffect";
  73281. /**
  73282. * The horizontal blur PostProcess id in the pipeline
  73283. */
  73284. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73285. /**
  73286. * The vertical blur PostProcess id in the pipeline
  73287. */
  73288. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73289. /**
  73290. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73291. */
  73292. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73293. /**
  73294. * The output strength of the SSAO post-process. Default value is 1.0.
  73295. */
  73296. _this.totalStrength = 1.0;
  73297. /**
  73298. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73299. */
  73300. _this.maxZ = 100.0;
  73301. /**
  73302. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73303. */
  73304. _this.minZAspect = 0.2;
  73305. /**
  73306. * Number of samples used for the SSAO calculations. Default value is 8
  73307. */
  73308. _this._samples = 8;
  73309. /**
  73310. * Are we using bilateral blur ?
  73311. */
  73312. _this._expensiveBlur = true;
  73313. /**
  73314. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73315. */
  73316. _this.radius = 2.0;
  73317. /**
  73318. * The base color of the SSAO post-process
  73319. * The final result is "base + ssao" between [0, 1]
  73320. */
  73321. _this.base = 0.1;
  73322. _this._firstUpdate = true;
  73323. _this._scene = scene;
  73324. _this._ratio = ratio;
  73325. if (!_this.isSupported) {
  73326. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73327. return _this;
  73328. }
  73329. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73330. var blurRatio = _this._ratio.blurRatio || ratio;
  73331. // Set up assets
  73332. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73333. _this._createRandomTexture();
  73334. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73335. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73336. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73337. _this._createSSAOPostProcess(1.0);
  73338. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73339. _this._createSSAOCombinePostProcess(blurRatio);
  73340. // Set up pipeline
  73341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73346. // Finish
  73347. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73348. if (cameras)
  73349. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73350. return _this;
  73351. }
  73352. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73353. get: function () {
  73354. return this._samples;
  73355. },
  73356. set: function (n) {
  73357. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73358. this._samples = n;
  73359. this._sampleSphere = this._generateHemisphere();
  73360. this._firstUpdate = true;
  73361. },
  73362. enumerable: true,
  73363. configurable: true
  73364. });
  73365. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73366. get: function () {
  73367. return this._expensiveBlur;
  73368. },
  73369. set: function (b) {
  73370. 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"]);
  73371. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73372. this._expensiveBlur = b;
  73373. this._firstUpdate = true;
  73374. },
  73375. enumerable: true,
  73376. configurable: true
  73377. });
  73378. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73379. /**
  73380. * Support test.
  73381. */
  73382. get: function () {
  73383. var engine = BABYLON.Engine.LastCreatedEngine;
  73384. if (!engine) {
  73385. return false;
  73386. }
  73387. return engine.getCaps().drawBuffersExtension;
  73388. },
  73389. enumerable: true,
  73390. configurable: true
  73391. });
  73392. // Public Methods
  73393. /**
  73394. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73395. */
  73396. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73397. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73398. for (var i = 0; i < this._scene.cameras.length; i++) {
  73399. var camera = this._scene.cameras[i];
  73400. this._originalColorPostProcess.dispose(camera);
  73401. this._ssaoPostProcess.dispose(camera);
  73402. this._blurHPostProcess.dispose(camera);
  73403. this._blurVPostProcess.dispose(camera);
  73404. this._ssaoCombinePostProcess.dispose(camera);
  73405. }
  73406. this._randomTexture.dispose();
  73407. if (disableGeometryBufferRenderer)
  73408. this._scene.disableGeometryBufferRenderer();
  73409. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73410. _super.prototype.dispose.call(this);
  73411. };
  73412. // Private Methods
  73413. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73414. var _this = this;
  73415. this._samplerOffsets = [];
  73416. var expensive = this.expensiveBlur;
  73417. for (var i = -8; i < 8; i++) {
  73418. this._samplerOffsets.push(i * 2 + 0.5);
  73419. }
  73420. 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");
  73421. this._blurHPostProcess.onApply = function (effect) {
  73422. if (!_this._scene.activeCamera) {
  73423. return;
  73424. }
  73425. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73426. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73427. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73428. effect.setFloat("radius", _this.radius);
  73429. effect.setTexture("depthSampler", _this._depthTexture);
  73430. if (_this._firstUpdate) {
  73431. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73432. }
  73433. };
  73434. 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");
  73435. this._blurVPostProcess.onApply = function (effect) {
  73436. if (!_this._scene.activeCamera) {
  73437. return;
  73438. }
  73439. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73440. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73441. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73442. effect.setFloat("radius", _this.radius);
  73443. effect.setTexture("depthSampler", _this._depthTexture);
  73444. if (_this._firstUpdate) {
  73445. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73446. _this._firstUpdate = false;
  73447. }
  73448. };
  73449. };
  73450. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73451. this._firstUpdate = true;
  73452. _super.prototype._rebuild.call(this);
  73453. };
  73454. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73455. var numSamples = this.samples;
  73456. var result = [];
  73457. var vector, scale;
  73458. var rand = function (min, max) {
  73459. return Math.random() * (max - min) + min;
  73460. };
  73461. var i = 0;
  73462. while (i < numSamples) {
  73463. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73464. vector.normalize();
  73465. scale = i / numSamples;
  73466. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73467. vector.scaleInPlace(scale);
  73468. result.push(vector.x, vector.y, vector.z);
  73469. i++;
  73470. }
  73471. return result;
  73472. };
  73473. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73474. var _this = this;
  73475. var numSamples = this.samples;
  73476. this._sampleSphere = this._generateHemisphere();
  73477. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73478. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73479. "base", "range", "projection", "near", "far", "texelSize",
  73480. "xViewport", "yViewport", "maxZ", "minZAspect"
  73481. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73482. this._ssaoPostProcess.onApply = function (effect) {
  73483. if (_this._firstUpdate) {
  73484. effect.setArray3("sampleSphere", _this._sampleSphere);
  73485. effect.setFloat("randTextureTiles", 4.0);
  73486. }
  73487. if (!_this._scene.activeCamera) {
  73488. return;
  73489. }
  73490. effect.setFloat("samplesFactor", 1 / _this.samples);
  73491. effect.setFloat("totalStrength", _this.totalStrength);
  73492. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73493. effect.setFloat("radius", _this.radius);
  73494. effect.setFloat("maxZ", _this.maxZ);
  73495. effect.setFloat("minZAspect", _this.minZAspect);
  73496. effect.setFloat("base", _this.base);
  73497. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73498. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73499. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73500. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73501. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73502. effect.setTexture("textureSampler", _this._depthTexture);
  73503. effect.setTexture("normalSampler", _this._normalTexture);
  73504. effect.setTexture("randomSampler", _this._randomTexture);
  73505. };
  73506. };
  73507. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73508. var _this = this;
  73509. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73510. this._ssaoCombinePostProcess.onApply = function (effect) {
  73511. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73512. };
  73513. };
  73514. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73515. var size = 512;
  73516. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73517. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73518. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73519. var context = this._randomTexture.getContext();
  73520. var rand = function (min, max) {
  73521. return Math.random() * (max - min) + min;
  73522. };
  73523. var randVector = BABYLON.Vector3.Zero();
  73524. for (var x = 0; x < size; x++) {
  73525. for (var y = 0; y < size; y++) {
  73526. randVector.x = rand(0.0, 1.0);
  73527. randVector.y = rand(0.0, 1.0);
  73528. randVector.z = 0.0;
  73529. randVector.normalize();
  73530. randVector.scaleInPlace(255);
  73531. randVector.x = Math.floor(randVector.x);
  73532. randVector.y = Math.floor(randVector.y);
  73533. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73534. context.fillRect(x, y, 1, 1);
  73535. }
  73536. }
  73537. this._randomTexture.update(false);
  73538. };
  73539. /**
  73540. * Serialize the rendering pipeline (Used when exporting)
  73541. * @returns the serialized object
  73542. */
  73543. SSAO2RenderingPipeline.prototype.serialize = function () {
  73544. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73545. serializationObject.customType = "SSAO2RenderingPipeline";
  73546. return serializationObject;
  73547. };
  73548. /**
  73549. * Parse the serialized pipeline
  73550. * @param source Source pipeline.
  73551. * @param scene The scene to load the pipeline to.
  73552. * @param rootUrl The URL of the serialized pipeline.
  73553. * @returns An instantiated pipeline from the serialized object.
  73554. */
  73555. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73556. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73557. };
  73558. __decorate([
  73559. BABYLON.serialize()
  73560. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73561. __decorate([
  73562. BABYLON.serialize()
  73563. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73564. __decorate([
  73565. BABYLON.serialize()
  73566. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73567. __decorate([
  73568. BABYLON.serialize("samples")
  73569. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73570. __decorate([
  73571. BABYLON.serialize()
  73572. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73573. __decorate([
  73574. BABYLON.serialize("expensiveBlur")
  73575. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73576. __decorate([
  73577. BABYLON.serialize()
  73578. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73579. __decorate([
  73580. BABYLON.serialize()
  73581. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73582. return SSAO2RenderingPipeline;
  73583. }(BABYLON.PostProcessRenderPipeline));
  73584. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73585. })(BABYLON || (BABYLON = {}));
  73586. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73587. // BABYLON.JS Chromatic Aberration GLSL Shader
  73588. // Author: Olivier Guyot
  73589. // Separates very slightly R, G and B colors on the edges of the screen
  73590. // Inspired by Francois Tarlier & Martins Upitis
  73591. var BABYLON;
  73592. (function (BABYLON) {
  73593. var LensRenderingPipeline = /** @class */ (function (_super) {
  73594. __extends(LensRenderingPipeline, _super);
  73595. /**
  73596. * @constructor
  73597. *
  73598. * Effect parameters are as follow:
  73599. * {
  73600. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73601. * edge_blur: number; // from 0 to x (1 for realism)
  73602. * distortion: number; // from 0 to x (1 for realism)
  73603. * grain_amount: number; // from 0 to 1
  73604. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73605. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73606. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73607. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73608. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73609. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73610. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73611. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73612. * }
  73613. * Note: if an effect parameter is unset, effect is disabled
  73614. *
  73615. * @param {string} name - The rendering pipeline name
  73616. * @param {object} parameters - An object containing all parameters (see above)
  73617. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73618. * @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)
  73619. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73620. */
  73621. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73622. if (ratio === void 0) { ratio = 1.0; }
  73623. var _this = _super.call(this, scene.getEngine(), name) || this;
  73624. // Lens effects can be of the following:
  73625. // - chromatic aberration (slight shift of RGB colors)
  73626. // - blur on the edge of the lens
  73627. // - lens distortion
  73628. // - depth-of-field blur & highlights enhancing
  73629. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73630. // - grain effect (noise or custom texture)
  73631. // Two additional texture samplers are needed:
  73632. // - depth map (for depth-of-field)
  73633. // - grain texture
  73634. /**
  73635. * The chromatic aberration PostProcess id in the pipeline
  73636. */
  73637. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73638. /**
  73639. * The highlights enhancing PostProcess id in the pipeline
  73640. */
  73641. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73642. /**
  73643. * The depth-of-field PostProcess id in the pipeline
  73644. */
  73645. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73646. _this._scene = scene;
  73647. // Fetch texture samplers
  73648. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73649. if (parameters.grain_texture) {
  73650. _this._grainTexture = parameters.grain_texture;
  73651. }
  73652. else {
  73653. _this._createGrainTexture();
  73654. }
  73655. // save parameters
  73656. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73657. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73658. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73659. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73660. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73661. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73662. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73663. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73664. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73665. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73666. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73667. // Create effects
  73668. _this._createChromaticAberrationPostProcess(ratio);
  73669. _this._createHighlightsPostProcess(ratio);
  73670. _this._createDepthOfFieldPostProcess(ratio / 4);
  73671. // Set up pipeline
  73672. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73673. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73674. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73675. if (_this._highlightsGain === -1) {
  73676. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73677. }
  73678. // Finish
  73679. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73680. if (cameras) {
  73681. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73682. }
  73683. return _this;
  73684. }
  73685. // public methods (self explanatory)
  73686. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73687. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73688. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73689. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73690. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73691. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73692. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73693. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73694. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73695. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73696. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73697. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73698. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73699. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73700. };
  73701. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73702. this._highlightsPostProcess.updateEffect();
  73703. };
  73704. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73705. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73706. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73707. this._highlightsGain = amount;
  73708. };
  73709. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73710. if (this._highlightsGain === -1) {
  73711. this._highlightsGain = 1.0;
  73712. }
  73713. this._highlightsThreshold = amount;
  73714. };
  73715. LensRenderingPipeline.prototype.disableHighlights = function () {
  73716. this._highlightsGain = -1;
  73717. };
  73718. /**
  73719. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73720. */
  73721. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73722. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73723. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73724. this._chromaticAberrationPostProcess = null;
  73725. this._highlightsPostProcess = null;
  73726. this._depthOfFieldPostProcess = null;
  73727. this._grainTexture.dispose();
  73728. if (disableDepthRender)
  73729. this._scene.disableDepthRenderer();
  73730. };
  73731. // colors shifting and distortion
  73732. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73733. var _this = this;
  73734. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73735. [], // samplers
  73736. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73737. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73738. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73739. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73740. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73741. effect.setFloat('radialIntensity', 1);
  73742. effect.setFloat2('direction', 17, 17);
  73743. effect.setFloat2('centerPosition', 0.5, 0.5);
  73744. };
  73745. };
  73746. // highlights enhancing
  73747. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73748. var _this = this;
  73749. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73750. [], // samplers
  73751. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73752. this._highlightsPostProcess.onApply = function (effect) {
  73753. effect.setFloat('gain', _this._highlightsGain);
  73754. effect.setFloat('threshold', _this._highlightsThreshold);
  73755. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73758. };
  73759. };
  73760. // colors shifting and distortion
  73761. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73762. var _this = this;
  73763. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73764. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73765. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73766. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73767. this._depthOfFieldPostProcess.onApply = function (effect) {
  73768. effect.setTexture("depthSampler", _this._depthTexture);
  73769. effect.setTexture("grainSampler", _this._grainTexture);
  73770. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73771. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73772. effect.setFloat('grain_amount', _this._grainAmount);
  73773. effect.setBool('blur_noise', _this._blurNoise);
  73774. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73775. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73776. effect.setFloat('distortion', _this._distortion);
  73777. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73778. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73779. effect.setFloat('aperture', _this._dofAperture);
  73780. effect.setFloat('darken', _this._dofDarken);
  73781. effect.setFloat('edge_blur', _this._edgeBlur);
  73782. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73783. if (_this._scene.activeCamera) {
  73784. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73785. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73786. }
  73787. };
  73788. };
  73789. // creates a black and white random noise texture, 512x512
  73790. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73791. var size = 512;
  73792. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73793. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73794. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73795. var context = this._grainTexture.getContext();
  73796. var rand = function (min, max) {
  73797. return Math.random() * (max - min) + min;
  73798. };
  73799. var value;
  73800. for (var x = 0; x < size; x++) {
  73801. for (var y = 0; y < size; y++) {
  73802. value = Math.floor(rand(0.42, 0.58) * 255);
  73803. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73804. context.fillRect(x, y, 1, 1);
  73805. }
  73806. }
  73807. this._grainTexture.update(false);
  73808. };
  73809. return LensRenderingPipeline;
  73810. }(BABYLON.PostProcessRenderPipeline));
  73811. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73812. })(BABYLON || (BABYLON = {}));
  73813. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73814. var BABYLON;
  73815. (function (BABYLON) {
  73816. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73817. __extends(StandardRenderingPipeline, _super);
  73818. /**
  73819. * @constructor
  73820. * @param {string} name - The rendering pipeline name
  73821. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73822. * @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)
  73823. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73824. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73825. */
  73826. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73827. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73828. var _this = _super.call(this, scene.getEngine(), name) || this;
  73829. _this.downSampleX4PostProcess = null;
  73830. _this.brightPassPostProcess = null;
  73831. _this.blurHPostProcesses = [];
  73832. _this.blurVPostProcesses = [];
  73833. _this.textureAdderPostProcess = null;
  73834. _this.volumetricLightPostProcess = null;
  73835. _this.volumetricLightSmoothXPostProcess = null;
  73836. _this.volumetricLightSmoothYPostProcess = null;
  73837. _this.volumetricLightMergePostProces = null;
  73838. _this.volumetricLightFinalPostProcess = null;
  73839. _this.luminancePostProcess = null;
  73840. _this.luminanceDownSamplePostProcesses = [];
  73841. _this.hdrPostProcess = null;
  73842. _this.textureAdderFinalPostProcess = null;
  73843. _this.lensFlareFinalPostProcess = null;
  73844. _this.hdrFinalPostProcess = null;
  73845. _this.lensFlarePostProcess = null;
  73846. _this.lensFlareComposePostProcess = null;
  73847. _this.motionBlurPostProcess = null;
  73848. _this.depthOfFieldPostProcess = null;
  73849. // Values
  73850. _this.brightThreshold = 1.0;
  73851. _this.blurWidth = 512.0;
  73852. _this.horizontalBlur = false;
  73853. _this.exposure = 1.0;
  73854. _this.lensTexture = null;
  73855. _this.volumetricLightCoefficient = 0.2;
  73856. _this.volumetricLightPower = 4.0;
  73857. _this.volumetricLightBlurScale = 64.0;
  73858. _this.sourceLight = null;
  73859. _this.hdrMinimumLuminance = 1.0;
  73860. _this.hdrDecreaseRate = 0.5;
  73861. _this.hdrIncreaseRate = 0.5;
  73862. _this.lensColorTexture = null;
  73863. _this.lensFlareStrength = 20.0;
  73864. _this.lensFlareGhostDispersal = 1.4;
  73865. _this.lensFlareHaloWidth = 0.7;
  73866. _this.lensFlareDistortionStrength = 16.0;
  73867. _this.lensStarTexture = null;
  73868. _this.lensFlareDirtTexture = null;
  73869. _this.depthOfFieldDistance = 10.0;
  73870. _this.depthOfFieldBlurWidth = 64.0;
  73871. _this.motionStrength = 1.0;
  73872. // IAnimatable
  73873. _this.animations = [];
  73874. _this._currentDepthOfFieldSource = null;
  73875. _this._hdrCurrentLuminance = 1.0;
  73876. // Getters and setters
  73877. _this._bloomEnabled = true;
  73878. _this._depthOfFieldEnabled = false;
  73879. _this._vlsEnabled = false;
  73880. _this._lensFlareEnabled = false;
  73881. _this._hdrEnabled = false;
  73882. _this._motionBlurEnabled = false;
  73883. _this._motionBlurSamples = 64.0;
  73884. _this._volumetricLightStepsCount = 50.0;
  73885. _this._cameras = cameras || [];
  73886. // Initialize
  73887. _this._scene = scene;
  73888. _this._basePostProcess = originalPostProcess;
  73889. _this._ratio = ratio;
  73890. // Misc
  73891. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73892. // Finish
  73893. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73894. _this._buildPipeline();
  73895. return _this;
  73896. }
  73897. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73898. get: function () {
  73899. return this._bloomEnabled;
  73900. },
  73901. set: function (enabled) {
  73902. if (this._bloomEnabled === enabled) {
  73903. return;
  73904. }
  73905. this._bloomEnabled = enabled;
  73906. this._buildPipeline();
  73907. },
  73908. enumerable: true,
  73909. configurable: true
  73910. });
  73911. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73912. get: function () {
  73913. return this._depthOfFieldEnabled;
  73914. },
  73915. set: function (enabled) {
  73916. if (this._depthOfFieldEnabled === enabled) {
  73917. return;
  73918. }
  73919. this._depthOfFieldEnabled = enabled;
  73920. this._buildPipeline();
  73921. },
  73922. enumerable: true,
  73923. configurable: true
  73924. });
  73925. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73926. get: function () {
  73927. return this._lensFlareEnabled;
  73928. },
  73929. set: function (enabled) {
  73930. if (this._lensFlareEnabled === enabled) {
  73931. return;
  73932. }
  73933. this._lensFlareEnabled = enabled;
  73934. this._buildPipeline();
  73935. },
  73936. enumerable: true,
  73937. configurable: true
  73938. });
  73939. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73940. get: function () {
  73941. return this._hdrEnabled;
  73942. },
  73943. set: function (enabled) {
  73944. if (this._hdrEnabled === enabled) {
  73945. return;
  73946. }
  73947. this._hdrEnabled = enabled;
  73948. this._buildPipeline();
  73949. },
  73950. enumerable: true,
  73951. configurable: true
  73952. });
  73953. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73954. get: function () {
  73955. return this._vlsEnabled;
  73956. },
  73957. set: function (enabled) {
  73958. if (this._vlsEnabled === enabled) {
  73959. return;
  73960. }
  73961. if (enabled) {
  73962. var geometry = this._scene.enableGeometryBufferRenderer();
  73963. if (!geometry) {
  73964. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73965. return;
  73966. }
  73967. }
  73968. this._vlsEnabled = enabled;
  73969. this._buildPipeline();
  73970. },
  73971. enumerable: true,
  73972. configurable: true
  73973. });
  73974. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73975. get: function () {
  73976. return this._motionBlurEnabled;
  73977. },
  73978. set: function (enabled) {
  73979. if (this._motionBlurEnabled === enabled) {
  73980. return;
  73981. }
  73982. this._motionBlurEnabled = enabled;
  73983. this._buildPipeline();
  73984. },
  73985. enumerable: true,
  73986. configurable: true
  73987. });
  73988. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73989. get: function () {
  73990. return this._volumetricLightStepsCount;
  73991. },
  73992. set: function (count) {
  73993. if (this.volumetricLightPostProcess) {
  73994. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73995. }
  73996. this._volumetricLightStepsCount = count;
  73997. },
  73998. enumerable: true,
  73999. configurable: true
  74000. });
  74001. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74002. get: function () {
  74003. return this._motionBlurSamples;
  74004. },
  74005. set: function (samples) {
  74006. if (this.motionBlurPostProcess) {
  74007. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74008. }
  74009. this._motionBlurSamples = samples;
  74010. },
  74011. enumerable: true,
  74012. configurable: true
  74013. });
  74014. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74015. var _this = this;
  74016. var ratio = this._ratio;
  74017. var scene = this._scene;
  74018. this._disposePostProcesses();
  74019. this._reset();
  74020. // Create pass post-process
  74021. if (!this._basePostProcess) {
  74022. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74023. this.originalPostProcess.onApply = function (effect) {
  74024. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74025. };
  74026. }
  74027. else {
  74028. this.originalPostProcess = this._basePostProcess;
  74029. }
  74030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74031. this._currentDepthOfFieldSource = this.originalPostProcess;
  74032. if (this._bloomEnabled) {
  74033. // Create down sample X4 post-process
  74034. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74035. // Create bright pass post-process
  74036. this._createBrightPassPostProcess(scene, ratio / 2);
  74037. // Create gaussian blur post-processes (down sampling blurs)
  74038. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74039. // Create texture adder post-process
  74040. this._createTextureAdderPostProcess(scene, ratio);
  74041. // Create depth-of-field source post-process
  74042. 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);
  74043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74044. }
  74045. if (this._vlsEnabled) {
  74046. // Create volumetric light
  74047. this._createVolumetricLightPostProcess(scene, ratio);
  74048. // Create volumetric light final post-process
  74049. 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);
  74050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74051. }
  74052. if (this._lensFlareEnabled) {
  74053. // Create lens flare post-process
  74054. this._createLensFlarePostProcess(scene, ratio);
  74055. // Create depth-of-field source post-process post lens-flare and disable it now
  74056. 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);
  74057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74058. }
  74059. if (this._hdrEnabled) {
  74060. // Create luminance
  74061. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74062. // Create HDR
  74063. this._createHdrPostProcess(scene, ratio);
  74064. // Create depth-of-field source post-process post hdr and disable it now
  74065. 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);
  74066. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74067. }
  74068. if (this._depthOfFieldEnabled) {
  74069. // Create gaussian blur used by depth-of-field
  74070. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74071. // Create depth-of-field post-process
  74072. this._createDepthOfFieldPostProcess(scene, ratio);
  74073. }
  74074. if (this._motionBlurEnabled) {
  74075. // Create motion blur post-process
  74076. this._createMotionBlurPostProcess(scene, ratio);
  74077. }
  74078. if (this._cameras !== null) {
  74079. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74080. }
  74081. };
  74082. // Down Sample X4 Post-Processs
  74083. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74084. var _this = this;
  74085. var downSampleX4Offsets = new Array(32);
  74086. 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);
  74087. this.downSampleX4PostProcess.onApply = function (effect) {
  74088. var id = 0;
  74089. var width = _this.downSampleX4PostProcess.width;
  74090. var height = _this.downSampleX4PostProcess.height;
  74091. for (var i = -2; i < 2; i++) {
  74092. for (var j = -2; j < 2; j++) {
  74093. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74094. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74095. id += 2;
  74096. }
  74097. }
  74098. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74099. };
  74100. // Add to pipeline
  74101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74102. };
  74103. // Brightpass Post-Process
  74104. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74105. var _this = this;
  74106. var brightOffsets = new Array(8);
  74107. 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);
  74108. this.brightPassPostProcess.onApply = function (effect) {
  74109. var sU = (1.0 / _this.brightPassPostProcess.width);
  74110. var sV = (1.0 / _this.brightPassPostProcess.height);
  74111. brightOffsets[0] = -0.5 * sU;
  74112. brightOffsets[1] = 0.5 * sV;
  74113. brightOffsets[2] = 0.5 * sU;
  74114. brightOffsets[3] = 0.5 * sV;
  74115. brightOffsets[4] = -0.5 * sU;
  74116. brightOffsets[5] = -0.5 * sV;
  74117. brightOffsets[6] = 0.5 * sU;
  74118. brightOffsets[7] = -0.5 * sV;
  74119. effect.setArray2("dsOffsets", brightOffsets);
  74120. effect.setFloat("brightThreshold", _this.brightThreshold);
  74121. };
  74122. // Add to pipeline
  74123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74124. };
  74125. // Create blur H&V post-processes
  74126. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74127. var _this = this;
  74128. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74129. var engine = scene.getEngine();
  74130. 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);
  74131. 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);
  74132. blurX.onActivateObservable.add(function () {
  74133. var dw = blurX.width / engine.getRenderWidth();
  74134. blurX.kernel = _this[blurWidthKey] * dw;
  74135. });
  74136. blurY.onActivateObservable.add(function () {
  74137. var dw = blurY.height / engine.getRenderHeight();
  74138. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74139. });
  74140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74142. this.blurHPostProcesses.push(blurX);
  74143. this.blurVPostProcesses.push(blurY);
  74144. };
  74145. // Create texture adder post-process
  74146. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74147. var _this = this;
  74148. 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);
  74149. this.textureAdderPostProcess.onApply = function (effect) {
  74150. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74151. effect.setTexture("lensSampler", _this.lensTexture);
  74152. effect.setFloat("exposure", _this.exposure);
  74153. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74154. };
  74155. // Add to pipeline
  74156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74157. };
  74158. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74159. var _this = this;
  74160. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74161. geometryRenderer.enablePosition = true;
  74162. var geometry = geometryRenderer.getGBuffer();
  74163. // Base post-process
  74164. 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));
  74165. var depthValues = BABYLON.Vector2.Zero();
  74166. this.volumetricLightPostProcess.onApply = function (effect) {
  74167. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74168. var generator = _this.sourceLight.getShadowGenerator();
  74169. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74170. effect.setTexture("positionSampler", geometry.textures[2]);
  74171. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74172. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74173. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74174. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74175. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74176. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74177. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74178. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74179. effect.setVector2("depthValues", depthValues);
  74180. }
  74181. };
  74182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74183. // Smooth
  74184. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74185. // Merge
  74186. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74187. this.volumetricLightMergePostProces.onApply = function (effect) {
  74188. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74189. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74190. };
  74191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74192. };
  74193. // Create luminance
  74194. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74195. var _this = this;
  74196. // Create luminance
  74197. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74198. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74199. var offsets = [];
  74200. this.luminancePostProcess.onApply = function (effect) {
  74201. var sU = (1.0 / _this.luminancePostProcess.width);
  74202. var sV = (1.0 / _this.luminancePostProcess.height);
  74203. offsets[0] = -0.5 * sU;
  74204. offsets[1] = 0.5 * sV;
  74205. offsets[2] = 0.5 * sU;
  74206. offsets[3] = 0.5 * sV;
  74207. offsets[4] = -0.5 * sU;
  74208. offsets[5] = -0.5 * sV;
  74209. offsets[6] = 0.5 * sU;
  74210. offsets[7] = -0.5 * sV;
  74211. effect.setArray2("lumOffsets", offsets);
  74212. };
  74213. // Add to pipeline
  74214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74215. // Create down sample luminance
  74216. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74217. var size = Math.pow(3, i);
  74218. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74219. if (i === 0) {
  74220. defines += "#define FINAL_DOWN_SAMPLER";
  74221. }
  74222. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74223. this.luminanceDownSamplePostProcesses.push(postProcess);
  74224. }
  74225. // Create callbacks and add effects
  74226. var lastLuminance = this.luminancePostProcess;
  74227. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74228. var downSampleOffsets = new Array(18);
  74229. pp.onApply = function (effect) {
  74230. if (!lastLuminance) {
  74231. return;
  74232. }
  74233. var id = 0;
  74234. for (var x = -1; x < 2; x++) {
  74235. for (var y = -1; y < 2; y++) {
  74236. downSampleOffsets[id] = x / lastLuminance.width;
  74237. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74238. id += 2;
  74239. }
  74240. }
  74241. effect.setArray2("dsOffsets", downSampleOffsets);
  74242. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74243. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74244. lastLuminance = _this.luminancePostProcess;
  74245. }
  74246. else {
  74247. lastLuminance = pp;
  74248. }
  74249. };
  74250. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74251. pp.onAfterRender = function (effect) {
  74252. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74253. 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);
  74254. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74255. };
  74256. }
  74257. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74258. });
  74259. };
  74260. // Create HDR post-process
  74261. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74262. var _this = this;
  74263. 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);
  74264. var outputLiminance = 1;
  74265. var time = 0;
  74266. var lastTime = 0;
  74267. this.hdrPostProcess.onApply = function (effect) {
  74268. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74269. time += scene.getEngine().getDeltaTime();
  74270. if (outputLiminance < 0) {
  74271. outputLiminance = _this._hdrCurrentLuminance;
  74272. }
  74273. else {
  74274. var dt = (lastTime - time) / 1000.0;
  74275. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74276. outputLiminance += _this.hdrDecreaseRate * dt;
  74277. }
  74278. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74279. outputLiminance -= _this.hdrIncreaseRate * dt;
  74280. }
  74281. else {
  74282. outputLiminance = _this._hdrCurrentLuminance;
  74283. }
  74284. }
  74285. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74286. effect.setFloat("averageLuminance", outputLiminance);
  74287. lastTime = time;
  74288. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74289. };
  74290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74291. };
  74292. // Create lens flare post-process
  74293. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74294. var _this = this;
  74295. 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);
  74296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74297. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74298. 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);
  74299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74300. var resolution = new BABYLON.Vector2(0, 0);
  74301. // Lens flare
  74302. this.lensFlarePostProcess.onApply = function (effect) {
  74303. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74304. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74305. effect.setFloat("strength", _this.lensFlareStrength);
  74306. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74307. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74308. // Shift
  74309. resolution.x = _this.lensFlarePostProcess.width;
  74310. resolution.y = _this.lensFlarePostProcess.height;
  74311. effect.setVector2("resolution", resolution);
  74312. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74313. };
  74314. // Compose
  74315. 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);
  74316. 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);
  74317. this.lensFlareComposePostProcess.onApply = function (effect) {
  74318. if (!_this._scene.activeCamera) {
  74319. return;
  74320. }
  74321. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74322. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74323. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74324. // Lens start rotation matrix
  74325. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74326. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74327. 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));
  74328. camRot *= 4.0;
  74329. 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);
  74330. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74331. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74332. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74333. };
  74334. };
  74335. // Create depth-of-field post-process
  74336. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74337. var _this = this;
  74338. 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);
  74339. this.depthOfFieldPostProcess.onApply = function (effect) {
  74340. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74341. effect.setTexture("depthSampler", _this._getDepthTexture());
  74342. effect.setFloat("distance", _this.depthOfFieldDistance);
  74343. };
  74344. // Add to pipeline
  74345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74346. };
  74347. // Create motion blur post-process
  74348. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74349. var _this = this;
  74350. 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);
  74351. var motionScale = 0;
  74352. var prevViewProjection = BABYLON.Matrix.Identity();
  74353. var invViewProjection = BABYLON.Matrix.Identity();
  74354. var viewProjection = BABYLON.Matrix.Identity();
  74355. var screenSize = BABYLON.Vector2.Zero();
  74356. this.motionBlurPostProcess.onApply = function (effect) {
  74357. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74358. viewProjection.invertToRef(invViewProjection);
  74359. effect.setMatrix("inverseViewProjection", invViewProjection);
  74360. effect.setMatrix("prevViewProjection", prevViewProjection);
  74361. prevViewProjection = viewProjection;
  74362. screenSize.x = _this.motionBlurPostProcess.width;
  74363. screenSize.y = _this.motionBlurPostProcess.height;
  74364. effect.setVector2("screenSize", screenSize);
  74365. motionScale = scene.getEngine().getFps() / 60.0;
  74366. effect.setFloat("motionScale", motionScale);
  74367. effect.setFloat("motionStrength", _this.motionStrength);
  74368. effect.setTexture("depthSampler", _this._getDepthTexture());
  74369. };
  74370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74371. };
  74372. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74373. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74374. var renderer = this._scene.enableGeometryBufferRenderer();
  74375. return renderer.getGBuffer().textures[0];
  74376. }
  74377. return this._scene.enableDepthRenderer().getDepthMap();
  74378. };
  74379. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74380. for (var i = 0; i < this._cameras.length; i++) {
  74381. var camera = this._cameras[i];
  74382. if (this.originalPostProcess) {
  74383. this.originalPostProcess.dispose(camera);
  74384. }
  74385. if (this.downSampleX4PostProcess) {
  74386. this.downSampleX4PostProcess.dispose(camera);
  74387. }
  74388. if (this.brightPassPostProcess) {
  74389. this.brightPassPostProcess.dispose(camera);
  74390. }
  74391. if (this.textureAdderPostProcess) {
  74392. this.textureAdderPostProcess.dispose(camera);
  74393. }
  74394. if (this.textureAdderFinalPostProcess) {
  74395. this.textureAdderFinalPostProcess.dispose(camera);
  74396. }
  74397. if (this.volumetricLightPostProcess) {
  74398. this.volumetricLightPostProcess.dispose(camera);
  74399. }
  74400. if (this.volumetricLightSmoothXPostProcess) {
  74401. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74402. }
  74403. if (this.volumetricLightSmoothYPostProcess) {
  74404. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74405. }
  74406. if (this.volumetricLightMergePostProces) {
  74407. this.volumetricLightMergePostProces.dispose(camera);
  74408. }
  74409. if (this.volumetricLightFinalPostProcess) {
  74410. this.volumetricLightFinalPostProcess.dispose(camera);
  74411. }
  74412. if (this.lensFlarePostProcess) {
  74413. this.lensFlarePostProcess.dispose(camera);
  74414. }
  74415. if (this.lensFlareComposePostProcess) {
  74416. this.lensFlareComposePostProcess.dispose(camera);
  74417. }
  74418. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74419. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74420. }
  74421. if (this.luminancePostProcess) {
  74422. this.luminancePostProcess.dispose(camera);
  74423. }
  74424. if (this.hdrPostProcess) {
  74425. this.hdrPostProcess.dispose(camera);
  74426. }
  74427. if (this.hdrFinalPostProcess) {
  74428. this.hdrFinalPostProcess.dispose(camera);
  74429. }
  74430. if (this.depthOfFieldPostProcess) {
  74431. this.depthOfFieldPostProcess.dispose(camera);
  74432. }
  74433. if (this.motionBlurPostProcess) {
  74434. this.motionBlurPostProcess.dispose(camera);
  74435. }
  74436. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74437. this.blurHPostProcesses[j].dispose(camera);
  74438. }
  74439. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74440. this.blurVPostProcesses[j].dispose(camera);
  74441. }
  74442. }
  74443. this.originalPostProcess = null;
  74444. this.downSampleX4PostProcess = null;
  74445. this.brightPassPostProcess = null;
  74446. this.textureAdderPostProcess = null;
  74447. this.textureAdderFinalPostProcess = null;
  74448. this.volumetricLightPostProcess = null;
  74449. this.volumetricLightSmoothXPostProcess = null;
  74450. this.volumetricLightSmoothYPostProcess = null;
  74451. this.volumetricLightMergePostProces = null;
  74452. this.volumetricLightFinalPostProcess = null;
  74453. this.lensFlarePostProcess = null;
  74454. this.lensFlareComposePostProcess = null;
  74455. this.luminancePostProcess = null;
  74456. this.hdrPostProcess = null;
  74457. this.hdrFinalPostProcess = null;
  74458. this.depthOfFieldPostProcess = null;
  74459. this.motionBlurPostProcess = null;
  74460. this.luminanceDownSamplePostProcesses = [];
  74461. this.blurHPostProcesses = [];
  74462. this.blurVPostProcesses = [];
  74463. };
  74464. /**
  74465. * Dispose of the pipeline and stop all post processes
  74466. */
  74467. StandardRenderingPipeline.prototype.dispose = function () {
  74468. this._disposePostProcesses();
  74469. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74470. _super.prototype.dispose.call(this);
  74471. };
  74472. /**
  74473. * Serialize the rendering pipeline (Used when exporting)
  74474. * @returns the serialized object
  74475. */
  74476. StandardRenderingPipeline.prototype.serialize = function () {
  74477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74478. if (this.sourceLight) {
  74479. serializationObject.sourceLightId = this.sourceLight.id;
  74480. }
  74481. serializationObject.customType = "StandardRenderingPipeline";
  74482. return serializationObject;
  74483. };
  74484. /**
  74485. * Parse the serialized pipeline
  74486. * @param source Source pipeline.
  74487. * @param scene The scene to load the pipeline to.
  74488. * @param rootUrl The URL of the serialized pipeline.
  74489. * @returns An instantiated pipeline from the serialized object.
  74490. */
  74491. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74492. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74493. if (source.sourceLightId) {
  74494. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74495. }
  74496. return p;
  74497. };
  74498. // Luminance steps
  74499. StandardRenderingPipeline.LuminanceSteps = 6;
  74500. __decorate([
  74501. BABYLON.serialize()
  74502. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74503. __decorate([
  74504. BABYLON.serialize()
  74505. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74506. __decorate([
  74507. BABYLON.serialize()
  74508. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74509. __decorate([
  74510. BABYLON.serialize()
  74511. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74512. __decorate([
  74513. BABYLON.serializeAsTexture("lensTexture")
  74514. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74515. __decorate([
  74516. BABYLON.serialize()
  74517. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74518. __decorate([
  74519. BABYLON.serialize()
  74520. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74521. __decorate([
  74522. BABYLON.serialize()
  74523. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74524. __decorate([
  74525. BABYLON.serialize()
  74526. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74527. __decorate([
  74528. BABYLON.serialize()
  74529. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74530. __decorate([
  74531. BABYLON.serialize()
  74532. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74533. __decorate([
  74534. BABYLON.serializeAsTexture("lensColorTexture")
  74535. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74536. __decorate([
  74537. BABYLON.serialize()
  74538. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74539. __decorate([
  74540. BABYLON.serialize()
  74541. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74542. __decorate([
  74543. BABYLON.serialize()
  74544. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74545. __decorate([
  74546. BABYLON.serialize()
  74547. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74548. __decorate([
  74549. BABYLON.serializeAsTexture("lensStarTexture")
  74550. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74551. __decorate([
  74552. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74553. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74554. __decorate([
  74555. BABYLON.serialize()
  74556. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74557. __decorate([
  74558. BABYLON.serialize()
  74559. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74560. __decorate([
  74561. BABYLON.serialize()
  74562. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74563. __decorate([
  74564. BABYLON.serialize()
  74565. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74566. __decorate([
  74567. BABYLON.serialize()
  74568. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74569. __decorate([
  74570. BABYLON.serialize()
  74571. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74572. __decorate([
  74573. BABYLON.serialize()
  74574. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74575. __decorate([
  74576. BABYLON.serialize()
  74577. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74578. __decorate([
  74579. BABYLON.serialize()
  74580. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74581. __decorate([
  74582. BABYLON.serialize()
  74583. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74584. __decorate([
  74585. BABYLON.serialize()
  74586. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74587. __decorate([
  74588. BABYLON.serialize()
  74589. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74590. return StandardRenderingPipeline;
  74591. }(BABYLON.PostProcessRenderPipeline));
  74592. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74593. })(BABYLON || (BABYLON = {}));
  74594. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74595. var BABYLON;
  74596. (function (BABYLON) {
  74597. var FxaaPostProcess = /** @class */ (function (_super) {
  74598. __extends(FxaaPostProcess, _super);
  74599. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74600. if (camera === void 0) { camera = null; }
  74601. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74602. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74603. var defines = _this._getDefines();
  74604. _this.updateEffect(defines);
  74605. _this.onApplyObservable.add(function (effect) {
  74606. var texelSize = _this.texelSize;
  74607. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74608. });
  74609. return _this;
  74610. }
  74611. FxaaPostProcess.prototype._getDefines = function () {
  74612. var engine = this.getEngine();
  74613. if (!engine) {
  74614. return null;
  74615. }
  74616. var glInfo = engine.getGlInfo();
  74617. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74618. return "#define MALI 1\n";
  74619. }
  74620. return null;
  74621. };
  74622. return FxaaPostProcess;
  74623. }(BABYLON.PostProcess));
  74624. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74625. })(BABYLON || (BABYLON = {}));
  74626. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74627. var BABYLON;
  74628. (function (BABYLON) {
  74629. /**
  74630. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74631. */
  74632. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74633. __extends(ChromaticAberrationPostProcess, _super);
  74634. /**
  74635. * Creates a new instance ChromaticAberrationPostProcess
  74636. * @param name The name of the effect.
  74637. * @param screenWidth The width of the screen to apply the effect on.
  74638. * @param screenHeight The height of the screen to apply the effect on.
  74639. * @param options The required width/height ratio to downsize to before computing the render pass.
  74640. * @param camera The camera to apply the render pass to.
  74641. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74642. * @param engine The engine which the post process will be applied. (default: current engine)
  74643. * @param reusable If the post process can be reused on the same frame. (default: false)
  74644. * @param textureType Type of textures used when performing the post process. (default: 0)
  74645. * @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)
  74646. */
  74647. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74648. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74649. if (blockCompilation === void 0) { blockCompilation = false; }
  74650. 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;
  74651. /**
  74652. * The amount of seperation of rgb channels (default: 30)
  74653. */
  74654. _this.aberrationAmount = 30;
  74655. /**
  74656. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74657. */
  74658. _this.radialIntensity = 0;
  74659. /**
  74660. * 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))
  74661. */
  74662. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74663. /**
  74664. * 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))
  74665. */
  74666. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74667. _this.onApplyObservable.add(function (effect) {
  74668. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74669. effect.setFloat('screen_width', screenWidth);
  74670. effect.setFloat('screen_height', screenHeight);
  74671. effect.setFloat('radialIntensity', _this.radialIntensity);
  74672. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74673. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74674. });
  74675. return _this;
  74676. }
  74677. return ChromaticAberrationPostProcess;
  74678. }(BABYLON.PostProcess));
  74679. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74680. })(BABYLON || (BABYLON = {}));
  74681. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74682. var BABYLON;
  74683. (function (BABYLON) {
  74684. /**
  74685. * The GrainPostProcess adds noise to the image at mid luminance levels
  74686. */
  74687. var GrainPostProcess = /** @class */ (function (_super) {
  74688. __extends(GrainPostProcess, _super);
  74689. /**
  74690. * Creates a new instance of @see GrainPostProcess
  74691. * @param name The name of the effect.
  74692. * @param options The required width/height ratio to downsize to before computing the render pass.
  74693. * @param camera The camera to apply the render pass to.
  74694. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74695. * @param engine The engine which the post process will be applied. (default: current engine)
  74696. * @param reusable If the post process can be reused on the same frame. (default: false)
  74697. * @param textureType Type of textures used when performing the post process. (default: 0)
  74698. * @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)
  74699. */
  74700. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74701. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74702. if (blockCompilation === void 0) { blockCompilation = false; }
  74703. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74704. /**
  74705. * The intensity of the grain added (default: 30)
  74706. */
  74707. _this.intensity = 30;
  74708. /**
  74709. * If the grain should be randomized on every frame
  74710. */
  74711. _this.animated = false;
  74712. _this.onApplyObservable.add(function (effect) {
  74713. effect.setFloat('intensity', _this.intensity);
  74714. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74715. });
  74716. return _this;
  74717. }
  74718. return GrainPostProcess;
  74719. }(BABYLON.PostProcess));
  74720. BABYLON.GrainPostProcess = GrainPostProcess;
  74721. })(BABYLON || (BABYLON = {}));
  74722. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74723. var BABYLON;
  74724. (function (BABYLON) {
  74725. /**
  74726. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74727. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74728. */
  74729. var SharpenPostProcess = /** @class */ (function (_super) {
  74730. __extends(SharpenPostProcess, _super);
  74731. /**
  74732. * Creates a new instance ConvolutionPostProcess
  74733. * @param name The name of the effect.
  74734. * @param options The required width/height ratio to downsize to before computing the render pass.
  74735. * @param camera The camera to apply the render pass to.
  74736. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74737. * @param engine The engine which the post process will be applied. (default: current engine)
  74738. * @param reusable If the post process can be reused on the same frame. (default: false)
  74739. * @param textureType Type of textures used when performing the post process. (default: 0)
  74740. * @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)
  74741. */
  74742. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74743. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74744. if (blockCompilation === void 0) { blockCompilation = false; }
  74745. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74746. /**
  74747. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74748. */
  74749. _this.colorAmount = 1.0;
  74750. /**
  74751. * How much sharpness should be applied (default: 0.3)
  74752. */
  74753. _this.edgeAmount = 0.3;
  74754. _this.onApply = function (effect) {
  74755. effect.setFloat2("screenSize", _this.width, _this.height);
  74756. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74757. };
  74758. return _this;
  74759. }
  74760. return SharpenPostProcess;
  74761. }(BABYLON.PostProcess));
  74762. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74763. })(BABYLON || (BABYLON = {}));
  74764. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74765. var BABYLON;
  74766. (function (BABYLON) {
  74767. /**
  74768. * The Blur Post Process which blurs an image based on a kernel and direction.
  74769. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74770. */
  74771. var BlurPostProcess = /** @class */ (function (_super) {
  74772. __extends(BlurPostProcess, _super);
  74773. /**
  74774. * Creates a new instance BlurPostProcess
  74775. * @param name The name of the effect.
  74776. * @param direction The direction in which to blur the image.
  74777. * @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.
  74778. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74779. * @param camera The camera to apply the render pass to.
  74780. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74781. * @param engine The engine which the post process will be applied. (default: current engine)
  74782. * @param reusable If the post process can be reused on the same frame. (default: false)
  74783. * @param textureType Type of textures used when performing the post process. (default: 0)
  74784. * @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)
  74785. */
  74786. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74788. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74789. if (defines === void 0) { defines = ""; }
  74790. if (blockCompilation === void 0) { blockCompilation = false; }
  74791. 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;
  74792. _this.direction = direction;
  74793. _this.blockCompilation = blockCompilation;
  74794. _this._packedFloat = false;
  74795. _this._staticDefines = "";
  74796. _this._staticDefines = defines;
  74797. _this.onApplyObservable.add(function (effect) {
  74798. if (_this._outputTexture) {
  74799. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74800. }
  74801. else {
  74802. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74803. }
  74804. });
  74805. _this.kernel = kernel;
  74806. return _this;
  74807. }
  74808. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74809. /**
  74810. * Gets the length in pixels of the blur sample region
  74811. */
  74812. get: function () {
  74813. return this._idealKernel;
  74814. },
  74815. /**
  74816. * Sets the length in pixels of the blur sample region
  74817. */
  74818. set: function (v) {
  74819. if (this._idealKernel === v) {
  74820. return;
  74821. }
  74822. v = Math.max(v, 1);
  74823. this._idealKernel = v;
  74824. this._kernel = this._nearestBestKernel(v);
  74825. if (!this.blockCompilation) {
  74826. this._updateParameters();
  74827. }
  74828. },
  74829. enumerable: true,
  74830. configurable: true
  74831. });
  74832. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74833. /**
  74834. * Gets wether or not the blur is unpacking/repacking floats
  74835. */
  74836. get: function () {
  74837. return this._packedFloat;
  74838. },
  74839. /**
  74840. * Sets wether or not the blur needs to unpack/repack floats
  74841. */
  74842. set: function (v) {
  74843. if (this._packedFloat === v) {
  74844. return;
  74845. }
  74846. this._packedFloat = v;
  74847. if (!this.blockCompilation) {
  74848. this._updateParameters();
  74849. }
  74850. },
  74851. enumerable: true,
  74852. configurable: true
  74853. });
  74854. /**
  74855. * Updates the effect with the current post process compile time values and recompiles the shader.
  74856. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74857. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74858. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74859. * @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
  74860. * @param onCompiled Called when the shader has been compiled.
  74861. * @param onError Called if there is an error when compiling a shader.
  74862. */
  74863. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74864. if (defines === void 0) { defines = null; }
  74865. if (uniforms === void 0) { uniforms = null; }
  74866. if (samplers === void 0) { samplers = null; }
  74867. this._updateParameters(onCompiled, onError);
  74868. };
  74869. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74870. // Generate sampling offsets and weights
  74871. var N = this._kernel;
  74872. var centerIndex = (N - 1) / 2;
  74873. // Generate Gaussian sampling weights over kernel
  74874. var offsets = [];
  74875. var weights = [];
  74876. var totalWeight = 0;
  74877. for (var i = 0; i < N; i++) {
  74878. var u = i / (N - 1);
  74879. var w = this._gaussianWeight(u * 2.0 - 1);
  74880. offsets[i] = (i - centerIndex);
  74881. weights[i] = w;
  74882. totalWeight += w;
  74883. }
  74884. // Normalize weights
  74885. for (var i = 0; i < weights.length; i++) {
  74886. weights[i] /= totalWeight;
  74887. }
  74888. // Optimize: combine samples to take advantage of hardware linear sampling
  74889. // Walk from left to center, combining pairs (symmetrically)
  74890. var linearSamplingWeights = [];
  74891. var linearSamplingOffsets = [];
  74892. var linearSamplingMap = [];
  74893. for (var i = 0; i <= centerIndex; i += 2) {
  74894. var j = Math.min(i + 1, Math.floor(centerIndex));
  74895. var singleCenterSample = i === j;
  74896. if (singleCenterSample) {
  74897. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74898. }
  74899. else {
  74900. var sharedCell = j === centerIndex;
  74901. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74902. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74903. if (offsetLinear === 0) {
  74904. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74905. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74906. }
  74907. else {
  74908. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74909. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74910. }
  74911. }
  74912. }
  74913. for (var i = 0; i < linearSamplingMap.length; i++) {
  74914. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74915. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74916. }
  74917. // Replace with optimized
  74918. offsets = linearSamplingOffsets;
  74919. weights = linearSamplingWeights;
  74920. // Generate shaders
  74921. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74922. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74923. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74924. var defines = "";
  74925. defines += this._staticDefines;
  74926. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74927. if (this._staticDefines.indexOf("DOF") != -1) {
  74928. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74929. varyingCount--;
  74930. }
  74931. for (var i = 0; i < varyingCount; i++) {
  74932. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74933. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74934. }
  74935. var depCount = 0;
  74936. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74937. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74938. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74939. depCount++;
  74940. }
  74941. if (this.packedFloat) {
  74942. defines += "#define PACKEDFLOAT 1";
  74943. }
  74944. this.blockCompilation = false;
  74945. _super.prototype.updateEffect.call(this, defines, null, null, {
  74946. varyingCount: varyingCount,
  74947. depCount: depCount
  74948. }, onCompiled, onError);
  74949. };
  74950. /**
  74951. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74952. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74953. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74954. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74955. * The gaps between physical kernels are compensated for in the weighting of the samples
  74956. * @param idealKernel Ideal blur kernel.
  74957. * @return Nearest best kernel.
  74958. */
  74959. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74960. var v = Math.round(idealKernel);
  74961. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74962. var k = _a[_i];
  74963. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74964. return Math.max(k, 3);
  74965. }
  74966. }
  74967. return Math.max(v, 3);
  74968. };
  74969. /**
  74970. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74971. * @param x The point on the Gaussian distribution to sample.
  74972. * @return the value of the Gaussian function at x.
  74973. */
  74974. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74975. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74976. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74977. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74978. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74979. // truncated at around 1.3% of peak strength.
  74980. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74981. var sigma = (1 / 3);
  74982. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74983. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74984. var weight = (1.0 / denominator) * Math.exp(exponent);
  74985. return weight;
  74986. };
  74987. /**
  74988. * Generates a string that can be used as a floating point number in GLSL.
  74989. * @param x Value to print.
  74990. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74991. * @return GLSL float string.
  74992. */
  74993. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74994. if (decimalFigures === void 0) { decimalFigures = 8; }
  74995. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74996. };
  74997. return BlurPostProcess;
  74998. }(BABYLON.PostProcess));
  74999. BABYLON.BlurPostProcess = BlurPostProcess;
  75000. })(BABYLON || (BABYLON = {}));
  75001. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75002. var BABYLON;
  75003. (function (BABYLON) {
  75004. /**
  75005. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75006. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75007. * based on samples that have a large difference in distance than the center pixel.
  75008. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75009. */
  75010. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75011. __extends(DepthOfFieldBlurPostProcess, _super);
  75012. /**
  75013. * Creates a new instance CircleOfConfusionPostProcess
  75014. * @param name The name of the effect.
  75015. * @param scene The scene the effect belongs to.
  75016. * @param direction The direction the blur should be applied.
  75017. * @param kernel The size of the kernel used to blur.
  75018. * @param options The required width/height ratio to downsize to before computing the render pass.
  75019. * @param camera The camera to apply the render pass to.
  75020. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75021. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75022. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75023. * @param engine The engine which the post process will be applied. (default: current engine)
  75024. * @param reusable If the post process can be reused on the same frame. (default: false)
  75025. * @param textureType Type of textures used when performing the post process. (default: 0)
  75026. * @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)
  75027. */
  75028. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75029. if (imageToBlur === void 0) { imageToBlur = null; }
  75030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75031. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75032. if (blockCompilation === void 0) { blockCompilation = false; }
  75033. 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;
  75034. _this.direction = direction;
  75035. _this.onApplyObservable.add(function (effect) {
  75036. if (imageToBlur != null) {
  75037. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75038. }
  75039. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75040. if (scene.activeCamera) {
  75041. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75042. }
  75043. });
  75044. return _this;
  75045. }
  75046. return DepthOfFieldBlurPostProcess;
  75047. }(BABYLON.BlurPostProcess));
  75048. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75049. })(BABYLON || (BABYLON = {}));
  75050. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75051. var BABYLON;
  75052. (function (BABYLON) {
  75053. /**
  75054. * Options to be set when merging outputs from the default pipeline.
  75055. */
  75056. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75057. function DepthOfFieldMergePostProcessOptions() {
  75058. }
  75059. return DepthOfFieldMergePostProcessOptions;
  75060. }());
  75061. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75062. /**
  75063. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75064. */
  75065. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75066. __extends(DepthOfFieldMergePostProcess, _super);
  75067. /**
  75068. * Creates a new instance of DepthOfFieldMergePostProcess
  75069. * @param name The name of the effect.
  75070. * @param originalFromInput Post process which's input will be used for the merge.
  75071. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75072. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75073. * @param options The required width/height ratio to downsize to before computing the render pass.
  75074. * @param camera The camera to apply the render pass to.
  75075. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75076. * @param engine The engine which the post process will be applied. (default: current engine)
  75077. * @param reusable If the post process can be reused on the same frame. (default: false)
  75078. * @param textureType Type of textures used when performing the post process. (default: 0)
  75079. * @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)
  75080. */
  75081. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75083. if (blockCompilation === void 0) { blockCompilation = false; }
  75084. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75085. _this.blurSteps = blurSteps;
  75086. _this.onApplyObservable.add(function (effect) {
  75087. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75088. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75089. blurSteps.forEach(function (step, index) {
  75090. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75091. });
  75092. });
  75093. if (!blockCompilation) {
  75094. _this.updateEffect();
  75095. }
  75096. return _this;
  75097. }
  75098. /**
  75099. * Updates the effect with the current post process compile time values and recompiles the shader.
  75100. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75101. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75102. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75103. * @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
  75104. * @param onCompiled Called when the shader has been compiled.
  75105. * @param onError Called if there is an error when compiling a shader.
  75106. */
  75107. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75108. if (defines === void 0) { defines = null; }
  75109. if (uniforms === void 0) { uniforms = null; }
  75110. if (samplers === void 0) { samplers = null; }
  75111. if (!defines) {
  75112. defines = "";
  75113. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75114. }
  75115. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75116. };
  75117. return DepthOfFieldMergePostProcess;
  75118. }(BABYLON.PostProcess));
  75119. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75120. })(BABYLON || (BABYLON = {}));
  75121. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75122. var BABYLON;
  75123. (function (BABYLON) {
  75124. /**
  75125. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75126. */
  75127. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75128. __extends(CircleOfConfusionPostProcess, _super);
  75129. /**
  75130. * Creates a new instance CircleOfConfusionPostProcess
  75131. * @param name The name of the effect.
  75132. * @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.
  75133. * @param options The required width/height ratio to downsize to before computing the render pass.
  75134. * @param camera The camera to apply the render pass to.
  75135. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75136. * @param engine The engine which the post process will be applied. (default: current engine)
  75137. * @param reusable If the post process can be reused on the same frame. (default: false)
  75138. * @param textureType Type of textures used when performing the post process. (default: 0)
  75139. * @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)
  75140. */
  75141. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75143. if (blockCompilation === void 0) { blockCompilation = false; }
  75144. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75145. /**
  75146. * 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.
  75147. */
  75148. _this.lensSize = 50;
  75149. /**
  75150. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75151. */
  75152. _this.fStop = 1.4;
  75153. /**
  75154. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75155. */
  75156. _this.focusDistance = 2000;
  75157. /**
  75158. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75159. */
  75160. _this.focalLength = 50;
  75161. _this._depthTexture = null;
  75162. _this._depthTexture = depthTexture;
  75163. _this.onApplyObservable.add(function (effect) {
  75164. if (!_this._depthTexture) {
  75165. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75166. return;
  75167. }
  75168. effect.setTexture("depthSampler", _this._depthTexture);
  75169. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75170. var aperture = _this.lensSize / _this.fStop;
  75171. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75172. effect.setFloat('focusDistance', _this.focusDistance);
  75173. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75174. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75175. });
  75176. return _this;
  75177. }
  75178. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75179. /**
  75180. * 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.
  75181. */
  75182. set: function (value) {
  75183. this._depthTexture = value;
  75184. },
  75185. enumerable: true,
  75186. configurable: true
  75187. });
  75188. return CircleOfConfusionPostProcess;
  75189. }(BABYLON.PostProcess));
  75190. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75191. })(BABYLON || (BABYLON = {}));
  75192. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75193. var BABYLON;
  75194. (function (BABYLON) {
  75195. /**
  75196. * Specifies the level of max blur that should be applied when using the depth of field effect
  75197. */
  75198. var DepthOfFieldEffectBlurLevel;
  75199. (function (DepthOfFieldEffectBlurLevel) {
  75200. /**
  75201. * Subtle blur
  75202. */
  75203. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75204. /**
  75205. * Medium blur
  75206. */
  75207. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75208. /**
  75209. * Large blur
  75210. */
  75211. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75212. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75213. ;
  75214. /**
  75215. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75216. */
  75217. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75218. __extends(DepthOfFieldEffect, _super);
  75219. /**
  75220. * Creates a new instance DepthOfFieldEffect
  75221. * @param scene The scene the effect belongs to.
  75222. * @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.
  75223. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75224. * @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)
  75225. */
  75226. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75227. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75228. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75229. if (blockCompilation === void 0) { blockCompilation = false; }
  75230. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75231. return _this._effects;
  75232. }, true) || this;
  75233. /**
  75234. * Internal post processes in depth of field effect
  75235. */
  75236. _this._effects = [];
  75237. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75238. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75239. // 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)
  75240. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75241. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75242. _this._depthOfFieldBlurY = [];
  75243. _this._depthOfFieldBlurX = [];
  75244. var blurCount = 1;
  75245. var kernelSize = 15;
  75246. switch (blurLevel) {
  75247. case DepthOfFieldEffectBlurLevel.High: {
  75248. blurCount = 3;
  75249. kernelSize = 51;
  75250. break;
  75251. }
  75252. case DepthOfFieldEffectBlurLevel.Medium: {
  75253. blurCount = 2;
  75254. kernelSize = 31;
  75255. break;
  75256. }
  75257. default: {
  75258. kernelSize = 15;
  75259. blurCount = 1;
  75260. break;
  75261. }
  75262. }
  75263. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75264. var ratio = 1.0;
  75265. for (var i = 0; i < blurCount; i++) {
  75266. 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);
  75267. blurY.autoClear = false;
  75268. ratio = 0.75 / Math.pow(2, i);
  75269. 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);
  75270. blurX.autoClear = false;
  75271. _this._depthOfFieldBlurY.push(blurY);
  75272. _this._depthOfFieldBlurX.push(blurX);
  75273. }
  75274. // Set all post processes on the effect.
  75275. _this._effects = [_this._circleOfConfusion];
  75276. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75277. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75278. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75279. }
  75280. // Merge blurred images with original image based on circleOfConfusion
  75281. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75282. _this._dofMerge.autoClear = false;
  75283. _this._effects.push(_this._dofMerge);
  75284. return _this;
  75285. }
  75286. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75287. get: function () {
  75288. return this._circleOfConfusion.focalLength;
  75289. },
  75290. /**
  75291. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75292. */
  75293. set: function (value) {
  75294. this._circleOfConfusion.focalLength = value;
  75295. },
  75296. enumerable: true,
  75297. configurable: true
  75298. });
  75299. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75300. get: function () {
  75301. return this._circleOfConfusion.fStop;
  75302. },
  75303. /**
  75304. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75305. */
  75306. set: function (value) {
  75307. this._circleOfConfusion.fStop = value;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75313. get: function () {
  75314. return this._circleOfConfusion.focusDistance;
  75315. },
  75316. /**
  75317. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75318. */
  75319. set: function (value) {
  75320. this._circleOfConfusion.focusDistance = value;
  75321. },
  75322. enumerable: true,
  75323. configurable: true
  75324. });
  75325. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75326. get: function () {
  75327. return this._circleOfConfusion.lensSize;
  75328. },
  75329. /**
  75330. * 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.
  75331. */
  75332. set: function (value) {
  75333. this._circleOfConfusion.lensSize = value;
  75334. },
  75335. enumerable: true,
  75336. configurable: true
  75337. });
  75338. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75339. /**
  75340. * 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.
  75341. */
  75342. set: function (value) {
  75343. this._circleOfConfusion.depthTexture = value;
  75344. },
  75345. enumerable: true,
  75346. configurable: true
  75347. });
  75348. /**
  75349. * Disposes each of the internal effects for a given camera.
  75350. * @param camera The camera to dispose the effect on.
  75351. */
  75352. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75353. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75354. this._effects[effectIndex].dispose(camera);
  75355. }
  75356. };
  75357. /**
  75358. * Internal
  75359. */
  75360. DepthOfFieldEffect.prototype._updateEffects = function () {
  75361. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75362. this._effects[effectIndex].updateEffect();
  75363. }
  75364. };
  75365. /**
  75366. * Internal
  75367. * @returns if all the contained post processes are ready.
  75368. */
  75369. DepthOfFieldEffect.prototype._isReady = function () {
  75370. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75371. if (!this._effects[effectIndex].isReady()) {
  75372. return false;
  75373. }
  75374. }
  75375. return true;
  75376. };
  75377. return DepthOfFieldEffect;
  75378. }(BABYLON.PostProcessRenderEffect));
  75379. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75380. })(BABYLON || (BABYLON = {}));
  75381. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75382. var BABYLON;
  75383. (function (BABYLON) {
  75384. /**
  75385. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75386. */
  75387. var BloomMergePostProcess = /** @class */ (function (_super) {
  75388. __extends(BloomMergePostProcess, _super);
  75389. /**
  75390. * Creates a new instance of @see BloomMergePostProcess
  75391. * @param name The name of the effect.
  75392. * @param originalFromInput Post process which's input will be used for the merge.
  75393. * @param blurred Blurred highlights post process which's output will be used.
  75394. * @param weight Weight of the bloom to be added to the original input.
  75395. * @param options The required width/height ratio to downsize to before computing the render pass.
  75396. * @param camera The camera to apply the render pass to.
  75397. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75398. * @param engine The engine which the post process will be applied. (default: current engine)
  75399. * @param reusable If the post process can be reused on the same frame. (default: false)
  75400. * @param textureType Type of textures used when performing the post process. (default: 0)
  75401. * @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)
  75402. */
  75403. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75404. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75405. if (blockCompilation === void 0) { blockCompilation = false; }
  75406. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75407. _this.weight = weight;
  75408. _this.onApplyObservable.add(function (effect) {
  75409. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75410. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75411. effect.setFloat("bloomWeight", _this.weight);
  75412. });
  75413. if (!blockCompilation) {
  75414. _this.updateEffect();
  75415. }
  75416. return _this;
  75417. }
  75418. return BloomMergePostProcess;
  75419. }(BABYLON.PostProcess));
  75420. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75421. })(BABYLON || (BABYLON = {}));
  75422. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75423. var BABYLON;
  75424. (function (BABYLON) {
  75425. /**
  75426. * 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.
  75427. */
  75428. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75429. __extends(ExtractHighlightsPostProcess, _super);
  75430. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75431. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75432. if (blockCompilation === void 0) { blockCompilation = false; }
  75433. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75434. /**
  75435. * The luminance threshold, pixels below this value will be set to black.
  75436. */
  75437. _this.threshold = 0.9;
  75438. /**
  75439. * Internal
  75440. */
  75441. _this._exposure = 1;
  75442. /**
  75443. * Post process which has the input texture to be used when performing highlight extraction
  75444. */
  75445. _this._inputPostProcess = null;
  75446. _this.onApplyObservable.add(function (effect) {
  75447. if (_this._inputPostProcess) {
  75448. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75449. }
  75450. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75451. effect.setFloat('exposure', _this._exposure);
  75452. });
  75453. return _this;
  75454. }
  75455. return ExtractHighlightsPostProcess;
  75456. }(BABYLON.PostProcess));
  75457. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75458. })(BABYLON || (BABYLON = {}));
  75459. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75460. var BABYLON;
  75461. (function (BABYLON) {
  75462. /**
  75463. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75464. */
  75465. var BloomEffect = /** @class */ (function (_super) {
  75466. __extends(BloomEffect, _super);
  75467. /**
  75468. * Creates a new instance of @see BloomEffect
  75469. * @param scene The scene the effect belongs to.
  75470. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75471. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75472. * @param bloomWeight The the strength of bloom.
  75473. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75474. * @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)
  75475. */
  75476. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75477. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75478. if (blockCompilation === void 0) { blockCompilation = false; }
  75479. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75480. return _this._effects;
  75481. }, true) || this;
  75482. _this.bloomScale = bloomScale;
  75483. /**
  75484. * Internal
  75485. */
  75486. _this._effects = [];
  75487. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75488. _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);
  75489. _this._blurX.alwaysForcePOT = true;
  75490. _this._blurX.autoClear = false;
  75491. _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);
  75492. _this._blurY.alwaysForcePOT = true;
  75493. _this._blurY.autoClear = false;
  75494. _this.kernel = bloomKernel;
  75495. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75496. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75497. _this._merge.autoClear = false;
  75498. _this._effects.push(_this._merge);
  75499. return _this;
  75500. }
  75501. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75502. /**
  75503. * The luminance threshold to find bright areas of the image to bloom.
  75504. */
  75505. get: function () {
  75506. return this._downscale.threshold;
  75507. },
  75508. set: function (value) {
  75509. this._downscale.threshold = value;
  75510. },
  75511. enumerable: true,
  75512. configurable: true
  75513. });
  75514. Object.defineProperty(BloomEffect.prototype, "weight", {
  75515. /**
  75516. * The strength of the bloom.
  75517. */
  75518. get: function () {
  75519. return this._merge.weight;
  75520. },
  75521. set: function (value) {
  75522. this._merge.weight = value;
  75523. },
  75524. enumerable: true,
  75525. configurable: true
  75526. });
  75527. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75528. /**
  75529. * Specifies the size of the bloom blur kernel, relative to the final output size
  75530. */
  75531. get: function () {
  75532. return this._blurX.kernel / this.bloomScale;
  75533. },
  75534. set: function (value) {
  75535. this._blurX.kernel = value * this.bloomScale;
  75536. this._blurY.kernel = value * this.bloomScale;
  75537. },
  75538. enumerable: true,
  75539. configurable: true
  75540. });
  75541. /**
  75542. * Disposes each of the internal effects for a given camera.
  75543. * @param camera The camera to dispose the effect on.
  75544. */
  75545. BloomEffect.prototype.disposeEffects = function (camera) {
  75546. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75547. this._effects[effectIndex].dispose(camera);
  75548. }
  75549. };
  75550. /**
  75551. * Internal
  75552. */
  75553. BloomEffect.prototype._updateEffects = function () {
  75554. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75555. this._effects[effectIndex].updateEffect();
  75556. }
  75557. };
  75558. /**
  75559. * Internal
  75560. * @returns if all the contained post processes are ready.
  75561. */
  75562. BloomEffect.prototype._isReady = function () {
  75563. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75564. if (!this._effects[effectIndex].isReady()) {
  75565. return false;
  75566. }
  75567. }
  75568. return true;
  75569. };
  75570. return BloomEffect;
  75571. }(BABYLON.PostProcessRenderEffect));
  75572. BABYLON.BloomEffect = BloomEffect;
  75573. })(BABYLON || (BABYLON = {}));
  75574. //# sourceMappingURL=babylon.bloomEffect.js.map
  75575. var BABYLON;
  75576. (function (BABYLON) {
  75577. /**
  75578. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75579. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75580. */
  75581. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75582. __extends(DefaultRenderingPipeline, _super);
  75583. /**
  75584. * @constructor
  75585. * @param {string} name - The rendering pipeline name (default: "")
  75586. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75587. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75588. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75589. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75590. */
  75591. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75592. if (name === void 0) { name = ""; }
  75593. if (hdr === void 0) { hdr = true; }
  75594. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75595. if (automaticBuild === void 0) { automaticBuild = true; }
  75596. var _this = _super.call(this, scene.getEngine(), name) || this;
  75597. _this._originalCameras = [];
  75598. /**
  75599. * ID of the sharpen post process,
  75600. */
  75601. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75602. /**
  75603. * ID of the image processing post process;
  75604. */
  75605. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75606. /**
  75607. * ID of the Fast Approximate Anti-Aliasing post process;
  75608. */
  75609. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75610. /**
  75611. * ID of the chromatic aberration post process,
  75612. */
  75613. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75614. /**
  75615. * ID of the grain post process
  75616. */
  75617. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75618. /**
  75619. * Glow post process which adds a glow to emmisive areas of the image
  75620. */
  75621. _this._glowLayer = null;
  75622. /**
  75623. * Animations which can be used to tweak settings over a period of time
  75624. */
  75625. _this.animations = [];
  75626. _this._imageProcessingConfigurationObserver = null;
  75627. // Values
  75628. _this._sharpenEnabled = false;
  75629. _this._bloomEnabled = false;
  75630. _this._depthOfFieldEnabled = false;
  75631. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75632. _this._fxaaEnabled = false;
  75633. _this._imageProcessingEnabled = true;
  75634. _this._bloomScale = 0.5;
  75635. _this._chromaticAberrationEnabled = false;
  75636. _this._grainEnabled = false;
  75637. _this._buildAllowed = true;
  75638. _this._resizeObserver = null;
  75639. _this._hardwareScaleLevel = 1.0;
  75640. _this._bloomKernel = 64;
  75641. /**
  75642. * Specifies the weight of the bloom in the final rendering
  75643. */
  75644. _this._bloomWeight = 0.15;
  75645. /**
  75646. * Specifies the luma threshold for the area that will be blurred by the bloom
  75647. */
  75648. _this._bloomThreshold = 0.9;
  75649. _this._samples = 1;
  75650. _this._hasCleared = false;
  75651. _this._prevPostProcess = null;
  75652. _this._prevPrevPostProcess = null;
  75653. _this._cameras = cameras || scene.cameras;
  75654. _this._originalCameras = _this._cameras.slice();
  75655. _this._buildAllowed = automaticBuild;
  75656. // Initialize
  75657. _this._scene = scene;
  75658. var caps = _this._scene.getEngine().getCaps();
  75659. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75660. // Misc
  75661. if (_this._hdr) {
  75662. if (caps.textureHalfFloatRender) {
  75663. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75664. }
  75665. else if (caps.textureFloatRender) {
  75666. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75667. }
  75668. }
  75669. else {
  75670. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75671. }
  75672. // Attach
  75673. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75674. var engine = _this._scene.getEngine();
  75675. // Create post processes before hand so they can be modified before enabled.
  75676. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75677. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75678. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75679. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75680. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75681. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75682. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75683. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75684. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75685. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75686. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75687. _this.bloomKernel = _this.bloomKernel;
  75688. });
  75689. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75690. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75691. });
  75692. _this._buildPipeline();
  75693. return _this;
  75694. }
  75695. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75696. get: function () {
  75697. return this._sharpenEnabled;
  75698. },
  75699. /**
  75700. * Enable or disable the sharpen process from the pipeline
  75701. */
  75702. set: function (enabled) {
  75703. if (this._sharpenEnabled === enabled) {
  75704. return;
  75705. }
  75706. this._sharpenEnabled = enabled;
  75707. this._buildPipeline();
  75708. },
  75709. enumerable: true,
  75710. configurable: true
  75711. });
  75712. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75713. /**
  75714. * Specifies the size of the bloom blur kernel, relative to the final output size
  75715. */
  75716. get: function () {
  75717. return this._bloomKernel;
  75718. },
  75719. set: function (value) {
  75720. this._bloomKernel = value;
  75721. this.bloom.kernel = value / this._hardwareScaleLevel;
  75722. },
  75723. enumerable: true,
  75724. configurable: true
  75725. });
  75726. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75727. get: function () {
  75728. return this._bloomWeight;
  75729. },
  75730. /**
  75731. * The strength of the bloom.
  75732. */
  75733. set: function (value) {
  75734. if (this._bloomWeight === value) {
  75735. return;
  75736. }
  75737. this.bloom.weight = value;
  75738. this._bloomWeight = value;
  75739. },
  75740. enumerable: true,
  75741. configurable: true
  75742. });
  75743. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75744. get: function () {
  75745. return this._bloomThreshold;
  75746. },
  75747. /**
  75748. * The strength of the bloom.
  75749. */
  75750. set: function (value) {
  75751. if (this._bloomThreshold === value) {
  75752. return;
  75753. }
  75754. this.bloom.threshold = value;
  75755. this._bloomThreshold = value;
  75756. },
  75757. enumerable: true,
  75758. configurable: true
  75759. });
  75760. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75761. get: function () {
  75762. return this._bloomScale;
  75763. },
  75764. /**
  75765. * The scale of the bloom, lower value will provide better performance.
  75766. */
  75767. set: function (value) {
  75768. if (this._bloomScale === value) {
  75769. return;
  75770. }
  75771. this._bloomScale = value;
  75772. // recreate bloom and dispose old as this setting is not dynamic
  75773. this._rebuildBloom();
  75774. this._buildPipeline();
  75775. },
  75776. enumerable: true,
  75777. configurable: true
  75778. });
  75779. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75780. get: function () {
  75781. return this._bloomEnabled;
  75782. },
  75783. /**
  75784. * Enable or disable the bloom from the pipeline
  75785. */
  75786. set: function (enabled) {
  75787. if (this._bloomEnabled === enabled) {
  75788. return;
  75789. }
  75790. this._bloomEnabled = enabled;
  75791. this._buildPipeline();
  75792. },
  75793. enumerable: true,
  75794. configurable: true
  75795. });
  75796. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75797. // recreate bloom and dispose old as this setting is not dynamic
  75798. var oldBloom = this.bloom;
  75799. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75800. this.bloom.threshold = oldBloom.threshold;
  75801. for (var i = 0; i < this._cameras.length; i++) {
  75802. oldBloom.disposeEffects(this._cameras[i]);
  75803. }
  75804. };
  75805. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75806. /**
  75807. * If the depth of field is enabled.
  75808. */
  75809. get: function () {
  75810. return this._depthOfFieldEnabled;
  75811. },
  75812. set: function (enabled) {
  75813. if (this._depthOfFieldEnabled === enabled) {
  75814. return;
  75815. }
  75816. this._depthOfFieldEnabled = enabled;
  75817. this._buildPipeline();
  75818. },
  75819. enumerable: true,
  75820. configurable: true
  75821. });
  75822. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75823. /**
  75824. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75825. */
  75826. get: function () {
  75827. return this._depthOfFieldBlurLevel;
  75828. },
  75829. set: function (value) {
  75830. if (this._depthOfFieldBlurLevel === value) {
  75831. return;
  75832. }
  75833. this._depthOfFieldBlurLevel = value;
  75834. // recreate dof and dispose old as this setting is not dynamic
  75835. var oldDof = this.depthOfField;
  75836. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75837. this.depthOfField.focalLength = oldDof.focalLength;
  75838. this.depthOfField.focusDistance = oldDof.focusDistance;
  75839. this.depthOfField.fStop = oldDof.fStop;
  75840. this.depthOfField.lensSize = oldDof.lensSize;
  75841. for (var i = 0; i < this._cameras.length; i++) {
  75842. oldDof.disposeEffects(this._cameras[i]);
  75843. }
  75844. this._buildPipeline();
  75845. },
  75846. enumerable: true,
  75847. configurable: true
  75848. });
  75849. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75850. get: function () {
  75851. return this._fxaaEnabled;
  75852. },
  75853. /**
  75854. * If the anti aliasing is enabled.
  75855. */
  75856. set: function (enabled) {
  75857. if (this._fxaaEnabled === enabled) {
  75858. return;
  75859. }
  75860. this._fxaaEnabled = enabled;
  75861. this._buildPipeline();
  75862. },
  75863. enumerable: true,
  75864. configurable: true
  75865. });
  75866. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75867. get: function () {
  75868. return this._samples;
  75869. },
  75870. /**
  75871. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75872. */
  75873. set: function (sampleCount) {
  75874. if (this._samples === sampleCount) {
  75875. return;
  75876. }
  75877. this._samples = sampleCount;
  75878. this._buildPipeline();
  75879. },
  75880. enumerable: true,
  75881. configurable: true
  75882. });
  75883. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75884. get: function () {
  75885. return this._imageProcessingEnabled;
  75886. },
  75887. /**
  75888. * If image processing is enabled.
  75889. */
  75890. set: function (enabled) {
  75891. if (this._imageProcessingEnabled === enabled) {
  75892. return;
  75893. }
  75894. this._imageProcessingEnabled = enabled;
  75895. this._buildPipeline();
  75896. },
  75897. enumerable: true,
  75898. configurable: true
  75899. });
  75900. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75901. get: function () {
  75902. return this._glowLayer == null;
  75903. },
  75904. /**
  75905. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75906. */
  75907. set: function (enabled) {
  75908. if (enabled && !this._glowLayer) {
  75909. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75910. }
  75911. else if (!enabled && this._glowLayer) {
  75912. this._glowLayer.dispose();
  75913. this._glowLayer = null;
  75914. }
  75915. },
  75916. enumerable: true,
  75917. configurable: true
  75918. });
  75919. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75920. get: function () {
  75921. return this._chromaticAberrationEnabled;
  75922. },
  75923. /**
  75924. * Enable or disable the chromaticAberration process from the pipeline
  75925. */
  75926. set: function (enabled) {
  75927. if (this._chromaticAberrationEnabled === enabled) {
  75928. return;
  75929. }
  75930. this._chromaticAberrationEnabled = enabled;
  75931. this._buildPipeline();
  75932. },
  75933. enumerable: true,
  75934. configurable: true
  75935. });
  75936. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75937. get: function () {
  75938. return this._grainEnabled;
  75939. },
  75940. /**
  75941. * Enable or disable the grain process from the pipeline
  75942. */
  75943. set: function (enabled) {
  75944. if (this._grainEnabled === enabled) {
  75945. return;
  75946. }
  75947. this._grainEnabled = enabled;
  75948. this._buildPipeline();
  75949. },
  75950. enumerable: true,
  75951. configurable: true
  75952. });
  75953. /**
  75954. * Force the compilation of the entire pipeline.
  75955. */
  75956. DefaultRenderingPipeline.prototype.prepare = function () {
  75957. var previousState = this._buildAllowed;
  75958. this._buildAllowed = true;
  75959. this._buildPipeline();
  75960. this._buildAllowed = previousState;
  75961. };
  75962. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75963. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75964. if (this._hasCleared) {
  75965. postProcess.autoClear = false;
  75966. }
  75967. else {
  75968. postProcess.autoClear = true;
  75969. this._scene.autoClear = false;
  75970. this._hasCleared = true;
  75971. }
  75972. if (!skipTextureSharing) {
  75973. if (this._prevPrevPostProcess) {
  75974. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75975. }
  75976. else {
  75977. postProcess.useOwnOutput();
  75978. }
  75979. if (this._prevPostProcess) {
  75980. this._prevPrevPostProcess = this._prevPostProcess;
  75981. }
  75982. this._prevPostProcess = postProcess;
  75983. }
  75984. };
  75985. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75986. var _this = this;
  75987. if (!this._buildAllowed) {
  75988. return;
  75989. }
  75990. this._scene.autoClear = true;
  75991. var engine = this._scene.getEngine();
  75992. this._disposePostProcesses();
  75993. if (this._cameras !== null) {
  75994. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75995. // get back cameras to be used to reattach pipeline
  75996. this._cameras = this._originalCameras.slice();
  75997. }
  75998. this._reset();
  75999. this._prevPostProcess = null;
  76000. this._prevPrevPostProcess = null;
  76001. this._hasCleared = false;
  76002. if (this.depthOfFieldEnabled) {
  76003. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76004. this.depthOfField.depthTexture = depthTexture;
  76005. if (!this.depthOfField._isReady()) {
  76006. this.depthOfField._updateEffects();
  76007. }
  76008. this.addEffect(this.depthOfField);
  76009. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76010. }
  76011. if (this.bloomEnabled) {
  76012. if (!this.bloom._isReady()) {
  76013. this.bloom._updateEffects();
  76014. }
  76015. this.addEffect(this.bloom);
  76016. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76017. }
  76018. if (this._imageProcessingEnabled) {
  76019. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76020. if (this._hdr) {
  76021. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76022. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76023. }
  76024. else {
  76025. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76026. }
  76027. }
  76028. if (this.sharpenEnabled) {
  76029. if (!this.sharpen.isReady()) {
  76030. this.sharpen.updateEffect();
  76031. }
  76032. this.addEffect(this._sharpenEffect);
  76033. this._setAutoClearAndTextureSharing(this.sharpen);
  76034. }
  76035. if (this.grainEnabled) {
  76036. if (!this.grain.isReady()) {
  76037. this.grain.updateEffect();
  76038. }
  76039. this.addEffect(this._grainEffect);
  76040. this._setAutoClearAndTextureSharing(this.grain);
  76041. }
  76042. if (this.chromaticAberrationEnabled) {
  76043. if (!this.chromaticAberration.isReady()) {
  76044. this.chromaticAberration.updateEffect();
  76045. }
  76046. this.addEffect(this._chromaticAberrationEffect);
  76047. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76048. }
  76049. if (this.fxaaEnabled) {
  76050. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76051. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76052. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76053. }
  76054. if (this._cameras !== null) {
  76055. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76056. }
  76057. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76058. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76059. }
  76060. };
  76061. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76062. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76063. for (var i = 0; i < this._cameras.length; i++) {
  76064. var camera = this._cameras[i];
  76065. if (this.imageProcessing) {
  76066. this.imageProcessing.dispose(camera);
  76067. }
  76068. if (this.fxaa) {
  76069. this.fxaa.dispose(camera);
  76070. }
  76071. // These are created in the constructor and should not be disposed on every pipeline change
  76072. if (disposeNonRecreated) {
  76073. if (this.sharpen) {
  76074. this.sharpen.dispose(camera);
  76075. }
  76076. if (this.depthOfField) {
  76077. this.depthOfField.disposeEffects(camera);
  76078. }
  76079. if (this.bloom) {
  76080. this.bloom.disposeEffects(camera);
  76081. }
  76082. if (this.chromaticAberration) {
  76083. this.chromaticAberration.dispose(camera);
  76084. }
  76085. if (this.grain) {
  76086. this.grain.dispose(camera);
  76087. }
  76088. if (this._glowLayer) {
  76089. this._glowLayer.dispose();
  76090. }
  76091. }
  76092. }
  76093. this.imageProcessing = null;
  76094. this.fxaa = null;
  76095. if (disposeNonRecreated) {
  76096. this.sharpen = null;
  76097. this._sharpenEffect = null;
  76098. this.depthOfField = null;
  76099. this.bloom = null;
  76100. this.chromaticAberration = null;
  76101. this._chromaticAberrationEffect = null;
  76102. this.grain = null;
  76103. this._grainEffect = null;
  76104. this._glowLayer = null;
  76105. }
  76106. };
  76107. /**
  76108. * Dispose of the pipeline and stop all post processes
  76109. */
  76110. DefaultRenderingPipeline.prototype.dispose = function () {
  76111. this._disposePostProcesses(true);
  76112. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76113. this._scene.autoClear = true;
  76114. if (this._resizeObserver) {
  76115. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76116. this._resizeObserver = null;
  76117. }
  76118. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76119. _super.prototype.dispose.call(this);
  76120. };
  76121. /**
  76122. * Serialize the rendering pipeline (Used when exporting)
  76123. * @returns the serialized object
  76124. */
  76125. DefaultRenderingPipeline.prototype.serialize = function () {
  76126. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76127. serializationObject.customType = "DefaultRenderingPipeline";
  76128. return serializationObject;
  76129. };
  76130. /**
  76131. * Parse the serialized pipeline
  76132. * @param source Source pipeline.
  76133. * @param scene The scene to load the pipeline to.
  76134. * @param rootUrl The URL of the serialized pipeline.
  76135. * @returns An instantiated pipeline from the serialized object.
  76136. */
  76137. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76138. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76139. };
  76140. __decorate([
  76141. BABYLON.serialize()
  76142. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76143. __decorate([
  76144. BABYLON.serialize()
  76145. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76146. __decorate([
  76147. BABYLON.serialize()
  76148. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76149. __decorate([
  76150. BABYLON.serialize()
  76151. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76152. __decorate([
  76153. BABYLON.serialize()
  76154. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76155. __decorate([
  76156. BABYLON.serialize()
  76157. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76158. __decorate([
  76159. BABYLON.serialize()
  76160. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76161. __decorate([
  76162. BABYLON.serialize()
  76163. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76164. __decorate([
  76165. BABYLON.serialize()
  76166. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76167. __decorate([
  76168. BABYLON.serialize()
  76169. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76170. __decorate([
  76171. BABYLON.serialize()
  76172. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76173. __decorate([
  76174. BABYLON.serialize()
  76175. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76176. __decorate([
  76177. BABYLON.serialize()
  76178. ], DefaultRenderingPipeline.prototype, "samples", null);
  76179. __decorate([
  76180. BABYLON.serialize()
  76181. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76182. __decorate([
  76183. BABYLON.serialize()
  76184. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76185. __decorate([
  76186. BABYLON.serialize()
  76187. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76188. __decorate([
  76189. BABYLON.serialize()
  76190. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76191. return DefaultRenderingPipeline;
  76192. }(BABYLON.PostProcessRenderPipeline));
  76193. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76194. })(BABYLON || (BABYLON = {}));
  76195. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76196. var BABYLON;
  76197. (function (BABYLON) {
  76198. /**
  76199. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76200. */
  76201. var GeometryBufferRenderer = /** @class */ (function () {
  76202. /**
  76203. * Creates a new G Buffer for the scene
  76204. * @param scene The scene the buffer belongs to
  76205. * @param ratio How big is the buffer related to the main canvas.
  76206. */
  76207. function GeometryBufferRenderer(scene, ratio) {
  76208. if (ratio === void 0) { ratio = 1; }
  76209. this._enablePosition = false;
  76210. this._scene = scene;
  76211. this._ratio = ratio;
  76212. // Render target
  76213. this._createRenderTargets();
  76214. }
  76215. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76216. /**
  76217. * Set the render list (meshes to be rendered) used in the G buffer.
  76218. */
  76219. set: function (meshes) {
  76220. this._multiRenderTarget.renderList = meshes;
  76221. },
  76222. enumerable: true,
  76223. configurable: true
  76224. });
  76225. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76226. /**
  76227. * Gets wether or not G buffer are supported by the running hardware.
  76228. * This requires draw buffer supports
  76229. */
  76230. get: function () {
  76231. return this._multiRenderTarget.isSupported;
  76232. },
  76233. enumerable: true,
  76234. configurable: true
  76235. });
  76236. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76237. /**
  76238. * Gets wether or not position are enabled for the G buffer.
  76239. */
  76240. get: function () {
  76241. return this._enablePosition;
  76242. },
  76243. /**
  76244. * Sets wether or not position are enabled for the G buffer.
  76245. */
  76246. set: function (enable) {
  76247. this._enablePosition = enable;
  76248. this.dispose();
  76249. this._createRenderTargets();
  76250. },
  76251. enumerable: true,
  76252. configurable: true
  76253. });
  76254. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76255. /**
  76256. * Gets the scene associated with the buffer.
  76257. */
  76258. get: function () {
  76259. return this._scene;
  76260. },
  76261. enumerable: true,
  76262. configurable: true
  76263. });
  76264. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76265. /**
  76266. * Gets the ratio used by the buffer during its creation.
  76267. * How big is the buffer related to the main canvas.
  76268. */
  76269. get: function () {
  76270. return this._ratio;
  76271. },
  76272. enumerable: true,
  76273. configurable: true
  76274. });
  76275. /**
  76276. * Checks wether everything is ready to render a submesh to the G buffer.
  76277. * @param subMesh the submesh to check readiness for
  76278. * @param useInstances is the mesh drawn using instance or not
  76279. * @returns true if ready otherwise false
  76280. */
  76281. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76282. var material = subMesh.getMaterial();
  76283. if (material && material.disableDepthWrite) {
  76284. return false;
  76285. }
  76286. var defines = [];
  76287. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76288. var mesh = subMesh.getMesh();
  76289. // Alpha test
  76290. if (material && material.needAlphaTesting()) {
  76291. defines.push("#define ALPHATEST");
  76292. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76293. attribs.push(BABYLON.VertexBuffer.UVKind);
  76294. defines.push("#define UV1");
  76295. }
  76296. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76297. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76298. defines.push("#define UV2");
  76299. }
  76300. }
  76301. // Buffers
  76302. if (this._enablePosition) {
  76303. defines.push("#define POSITION");
  76304. }
  76305. // Bones
  76306. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76307. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76308. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76309. if (mesh.numBoneInfluencers > 4) {
  76310. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76311. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76312. }
  76313. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76314. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76315. }
  76316. else {
  76317. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76318. }
  76319. // Instances
  76320. if (useInstances) {
  76321. defines.push("#define INSTANCES");
  76322. attribs.push("world0");
  76323. attribs.push("world1");
  76324. attribs.push("world2");
  76325. attribs.push("world3");
  76326. }
  76327. // Get correct effect
  76328. var join = defines.join("\n");
  76329. if (this._cachedDefines !== join) {
  76330. this._cachedDefines = join;
  76331. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76332. }
  76333. return this._effect.isReady();
  76334. };
  76335. /**
  76336. * Gets the current underlying G Buffer.
  76337. * @returns the buffer
  76338. */
  76339. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76340. return this._multiRenderTarget;
  76341. };
  76342. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76343. /**
  76344. * Gets the number of samples used to render the buffer (anti aliasing).
  76345. */
  76346. get: function () {
  76347. return this._multiRenderTarget.samples;
  76348. },
  76349. /**
  76350. * Sets the number of samples used to render the buffer (anti aliasing).
  76351. */
  76352. set: function (value) {
  76353. this._multiRenderTarget.samples = value;
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. /**
  76359. * Disposes the renderer and frees up associated resources.
  76360. */
  76361. GeometryBufferRenderer.prototype.dispose = function () {
  76362. this.getGBuffer().dispose();
  76363. };
  76364. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76365. var _this = this;
  76366. var engine = this._scene.getEngine();
  76367. var count = this._enablePosition ? 3 : 2;
  76368. 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 });
  76369. if (!this.isSupported) {
  76370. return;
  76371. }
  76372. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76373. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76374. this._multiRenderTarget.refreshRate = 1;
  76375. this._multiRenderTarget.renderParticles = false;
  76376. this._multiRenderTarget.renderList = null;
  76377. // set default depth value to 1.0 (far away)
  76378. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76379. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76380. });
  76381. // Custom render function
  76382. var renderSubMesh = function (subMesh) {
  76383. var mesh = subMesh.getRenderingMesh();
  76384. var scene = _this._scene;
  76385. var engine = scene.getEngine();
  76386. var material = subMesh.getMaterial();
  76387. if (!material) {
  76388. return;
  76389. }
  76390. // Culling
  76391. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76392. // Managing instances
  76393. var batch = mesh._getInstancesRenderList(subMesh._id);
  76394. if (batch.mustReturn) {
  76395. return;
  76396. }
  76397. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76398. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76399. engine.enableEffect(_this._effect);
  76400. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76401. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76402. _this._effect.setMatrix("view", scene.getViewMatrix());
  76403. // Alpha test
  76404. if (material && material.needAlphaTesting()) {
  76405. var alphaTexture = material.getAlphaTestTexture();
  76406. if (alphaTexture) {
  76407. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76408. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76409. }
  76410. }
  76411. // Bones
  76412. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76413. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76414. }
  76415. // Draw
  76416. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76417. }
  76418. };
  76419. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76420. var index;
  76421. if (depthOnlySubMeshes.length) {
  76422. engine.setColorWrite(false);
  76423. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76424. renderSubMesh(depthOnlySubMeshes.data[index]);
  76425. }
  76426. engine.setColorWrite(true);
  76427. }
  76428. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76429. renderSubMesh(opaqueSubMeshes.data[index]);
  76430. }
  76431. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76432. renderSubMesh(alphaTestSubMeshes.data[index]);
  76433. }
  76434. };
  76435. };
  76436. return GeometryBufferRenderer;
  76437. }());
  76438. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76439. })(BABYLON || (BABYLON = {}));
  76440. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76441. var BABYLON;
  76442. (function (BABYLON) {
  76443. var RefractionPostProcess = /** @class */ (function (_super) {
  76444. __extends(RefractionPostProcess, _super);
  76445. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76446. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76447. _this.color = color;
  76448. _this.depth = depth;
  76449. _this.colorLevel = colorLevel;
  76450. _this._ownRefractionTexture = true;
  76451. _this.onActivateObservable.add(function (cam) {
  76452. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76453. });
  76454. _this.onApplyObservable.add(function (effect) {
  76455. effect.setColor3("baseColor", _this.color);
  76456. effect.setFloat("depth", _this.depth);
  76457. effect.setFloat("colorLevel", _this.colorLevel);
  76458. effect.setTexture("refractionSampler", _this._refTexture);
  76459. });
  76460. return _this;
  76461. }
  76462. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76463. /**
  76464. * Gets or sets the refraction texture
  76465. * Please note that you are responsible for disposing the texture if you set it manually
  76466. */
  76467. get: function () {
  76468. return this._refTexture;
  76469. },
  76470. set: function (value) {
  76471. if (this._refTexture && this._ownRefractionTexture) {
  76472. this._refTexture.dispose();
  76473. }
  76474. this._refTexture = value;
  76475. this._ownRefractionTexture = false;
  76476. },
  76477. enumerable: true,
  76478. configurable: true
  76479. });
  76480. // Methods
  76481. RefractionPostProcess.prototype.dispose = function (camera) {
  76482. if (this._refTexture && this._ownRefractionTexture) {
  76483. this._refTexture.dispose();
  76484. this._refTexture = null;
  76485. }
  76486. _super.prototype.dispose.call(this, camera);
  76487. };
  76488. return RefractionPostProcess;
  76489. }(BABYLON.PostProcess));
  76490. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76491. })(BABYLON || (BABYLON = {}));
  76492. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76493. var BABYLON;
  76494. (function (BABYLON) {
  76495. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76496. __extends(BlackAndWhitePostProcess, _super);
  76497. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76498. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76499. _this.degree = 1;
  76500. _this.onApplyObservable.add(function (effect) {
  76501. effect.setFloat("degree", _this.degree);
  76502. });
  76503. return _this;
  76504. }
  76505. return BlackAndWhitePostProcess;
  76506. }(BABYLON.PostProcess));
  76507. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76508. })(BABYLON || (BABYLON = {}));
  76509. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76510. var BABYLON;
  76511. (function (BABYLON) {
  76512. /**
  76513. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76514. * input texture to perform effects such as edge detection or sharpening
  76515. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76516. */
  76517. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76518. __extends(ConvolutionPostProcess, _super);
  76519. /**
  76520. * Creates a new instance ConvolutionPostProcess
  76521. * @param name The name of the effect.
  76522. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76523. * @param options The required width/height ratio to downsize to before computing the render pass.
  76524. * @param camera The camera to apply the render pass to.
  76525. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76526. * @param engine The engine which the post process will be applied. (default: current engine)
  76527. * @param reusable If the post process can be reused on the same frame. (default: false)
  76528. * @param textureType Type of textures used when performing the post process. (default: 0)
  76529. */
  76530. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76532. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76533. _this.kernel = kernel;
  76534. _this.onApply = function (effect) {
  76535. effect.setFloat2("screenSize", _this.width, _this.height);
  76536. effect.setArray("kernel", _this.kernel);
  76537. };
  76538. return _this;
  76539. }
  76540. // Statics
  76541. /**
  76542. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76543. */
  76544. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76545. /**
  76546. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76547. */
  76548. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76549. /**
  76550. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76551. */
  76552. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76553. /**
  76554. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76555. */
  76556. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76557. /**
  76558. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76559. */
  76560. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76561. /**
  76562. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76563. */
  76564. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76565. return ConvolutionPostProcess;
  76566. }(BABYLON.PostProcess));
  76567. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76568. })(BABYLON || (BABYLON = {}));
  76569. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76570. var BABYLON;
  76571. (function (BABYLON) {
  76572. var FilterPostProcess = /** @class */ (function (_super) {
  76573. __extends(FilterPostProcess, _super);
  76574. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76575. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76576. _this.kernelMatrix = kernelMatrix;
  76577. _this.onApply = function (effect) {
  76578. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76579. };
  76580. return _this;
  76581. }
  76582. return FilterPostProcess;
  76583. }(BABYLON.PostProcess));
  76584. BABYLON.FilterPostProcess = FilterPostProcess;
  76585. })(BABYLON || (BABYLON = {}));
  76586. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76587. var BABYLON;
  76588. (function (BABYLON) {
  76589. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76590. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76591. __extends(VolumetricLightScatteringPostProcess, _super);
  76592. /**
  76593. * @constructor
  76594. * @param {string} name - The post-process name
  76595. * @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)
  76596. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76597. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76598. * @param {number} samples - The post-process quality, default 100
  76599. * @param {number} samplingMode - The post-process filtering mode
  76600. * @param {BABYLON.Engine} engine - The babylon engine
  76601. * @param {boolean} reusable - If the post-process is reusable
  76602. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76603. */
  76604. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76605. if (samples === void 0) { samples = 100; }
  76606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76607. 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;
  76608. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76609. /**
  76610. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76611. */
  76612. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76613. /**
  76614. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76615. */
  76616. _this.useCustomMeshPosition = false;
  76617. /**
  76618. * If the post-process should inverse the light scattering direction
  76619. */
  76620. _this.invert = true;
  76621. /**
  76622. * Array containing the excluded meshes not rendered in the internal pass
  76623. */
  76624. _this.excludedMeshes = new Array();
  76625. /**
  76626. * Controls the overall intensity of the post-process
  76627. */
  76628. _this.exposure = 0.3;
  76629. /**
  76630. * Dissipates each sample's contribution in range [0, 1]
  76631. */
  76632. _this.decay = 0.96815;
  76633. /**
  76634. * Controls the overall intensity of each sample
  76635. */
  76636. _this.weight = 0.58767;
  76637. /**
  76638. * Controls the density of each sample
  76639. */
  76640. _this.density = 0.926;
  76641. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76642. engine = scene.getEngine();
  76643. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76644. // Configure mesh
  76645. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76646. // Configure
  76647. _this._createPass(scene, ratio.passRatio || ratio);
  76648. _this.onActivate = function (camera) {
  76649. if (!_this.isSupported) {
  76650. _this.dispose(camera);
  76651. }
  76652. _this.onActivate = null;
  76653. };
  76654. _this.onApplyObservable.add(function (effect) {
  76655. _this._updateMeshScreenCoordinates(scene);
  76656. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76657. effect.setFloat("exposure", _this.exposure);
  76658. effect.setFloat("decay", _this.decay);
  76659. effect.setFloat("weight", _this.weight);
  76660. effect.setFloat("density", _this.density);
  76661. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76662. });
  76663. return _this;
  76664. }
  76665. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76666. get: function () {
  76667. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76668. return false;
  76669. },
  76670. set: function (useDiffuseColor) {
  76671. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76672. },
  76673. enumerable: true,
  76674. configurable: true
  76675. });
  76676. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76677. return "VolumetricLightScatteringPostProcess";
  76678. };
  76679. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76680. var mesh = subMesh.getMesh();
  76681. // Render this.mesh as default
  76682. if (mesh === this.mesh && mesh.material) {
  76683. return mesh.material.isReady(mesh);
  76684. }
  76685. var defines = [];
  76686. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76687. var material = subMesh.getMaterial();
  76688. // Alpha test
  76689. if (material) {
  76690. if (material.needAlphaTesting()) {
  76691. defines.push("#define ALPHATEST");
  76692. }
  76693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76694. attribs.push(BABYLON.VertexBuffer.UVKind);
  76695. defines.push("#define UV1");
  76696. }
  76697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76698. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76699. defines.push("#define UV2");
  76700. }
  76701. }
  76702. // Bones
  76703. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76706. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76707. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76708. }
  76709. else {
  76710. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76711. }
  76712. // Instances
  76713. if (useInstances) {
  76714. defines.push("#define INSTANCES");
  76715. attribs.push("world0");
  76716. attribs.push("world1");
  76717. attribs.push("world2");
  76718. attribs.push("world3");
  76719. }
  76720. // Get correct effect
  76721. var join = defines.join("\n");
  76722. if (this._cachedDefines !== join) {
  76723. this._cachedDefines = join;
  76724. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76725. }
  76726. return this._volumetricLightScatteringPass.isReady();
  76727. };
  76728. /**
  76729. * Sets the new light position for light scattering effect
  76730. * @param {BABYLON.Vector3} The new custom light position
  76731. */
  76732. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76733. this.customMeshPosition = position;
  76734. };
  76735. /**
  76736. * Returns the light position for light scattering effect
  76737. * @return {BABYLON.Vector3} The custom light position
  76738. */
  76739. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76740. return this.customMeshPosition;
  76741. };
  76742. /**
  76743. * Disposes the internal assets and detaches the post-process from the camera
  76744. */
  76745. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76746. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76747. if (rttIndex !== -1) {
  76748. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76749. }
  76750. this._volumetricLightScatteringRTT.dispose();
  76751. _super.prototype.dispose.call(this, camera);
  76752. };
  76753. /**
  76754. * Returns the render target texture used by the post-process
  76755. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76756. */
  76757. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76758. return this._volumetricLightScatteringRTT;
  76759. };
  76760. // Private methods
  76761. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76762. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76763. return true;
  76764. }
  76765. return false;
  76766. };
  76767. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76768. var _this = this;
  76769. var engine = scene.getEngine();
  76770. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76771. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76772. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76773. this._volumetricLightScatteringRTT.renderList = null;
  76774. this._volumetricLightScatteringRTT.renderParticles = false;
  76775. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76776. var camera = this.getCamera();
  76777. if (camera) {
  76778. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76779. }
  76780. else {
  76781. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76782. }
  76783. // Custom render function for submeshes
  76784. var renderSubMesh = function (subMesh) {
  76785. var mesh = subMesh.getRenderingMesh();
  76786. if (_this._meshExcluded(mesh)) {
  76787. return;
  76788. }
  76789. var material = subMesh.getMaterial();
  76790. if (!material) {
  76791. return;
  76792. }
  76793. var scene = mesh.getScene();
  76794. var engine = scene.getEngine();
  76795. // Culling
  76796. engine.setState(material.backFaceCulling);
  76797. // Managing instances
  76798. var batch = mesh._getInstancesRenderList(subMesh._id);
  76799. if (batch.mustReturn) {
  76800. return;
  76801. }
  76802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76803. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76804. var effect = _this._volumetricLightScatteringPass;
  76805. if (mesh === _this.mesh) {
  76806. if (subMesh.effect) {
  76807. effect = subMesh.effect;
  76808. }
  76809. else {
  76810. effect = material.getEffect();
  76811. }
  76812. }
  76813. engine.enableEffect(effect);
  76814. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76815. if (mesh === _this.mesh) {
  76816. material.bind(mesh.getWorldMatrix(), mesh);
  76817. }
  76818. else {
  76819. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76820. // Alpha test
  76821. if (material && material.needAlphaTesting()) {
  76822. var alphaTexture = material.getAlphaTestTexture();
  76823. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76824. if (alphaTexture) {
  76825. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76826. }
  76827. }
  76828. // Bones
  76829. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76830. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76831. }
  76832. }
  76833. // Draw
  76834. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76835. }
  76836. };
  76837. // Render target texture callbacks
  76838. var savedSceneClearColor;
  76839. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76840. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76841. savedSceneClearColor = scene.clearColor;
  76842. scene.clearColor = sceneClearColor;
  76843. });
  76844. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76845. scene.clearColor = savedSceneClearColor;
  76846. });
  76847. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76848. var engine = scene.getEngine();
  76849. var index;
  76850. if (depthOnlySubMeshes.length) {
  76851. engine.setColorWrite(false);
  76852. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76853. renderSubMesh(depthOnlySubMeshes.data[index]);
  76854. }
  76855. engine.setColorWrite(true);
  76856. }
  76857. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76858. renderSubMesh(opaqueSubMeshes.data[index]);
  76859. }
  76860. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76861. renderSubMesh(alphaTestSubMeshes.data[index]);
  76862. }
  76863. if (transparentSubMeshes.length) {
  76864. // Sort sub meshes
  76865. for (index = 0; index < transparentSubMeshes.length; index++) {
  76866. var submesh = transparentSubMeshes.data[index];
  76867. var boundingInfo = submesh.getBoundingInfo();
  76868. if (boundingInfo && scene.activeCamera) {
  76869. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76870. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76871. }
  76872. }
  76873. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76874. sortedArray.sort(function (a, b) {
  76875. // Alpha index first
  76876. if (a._alphaIndex > b._alphaIndex) {
  76877. return 1;
  76878. }
  76879. if (a._alphaIndex < b._alphaIndex) {
  76880. return -1;
  76881. }
  76882. // Then distance to camera
  76883. if (a._distanceToCamera < b._distanceToCamera) {
  76884. return 1;
  76885. }
  76886. if (a._distanceToCamera > b._distanceToCamera) {
  76887. return -1;
  76888. }
  76889. return 0;
  76890. });
  76891. // Render sub meshes
  76892. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76893. for (index = 0; index < sortedArray.length; index++) {
  76894. renderSubMesh(sortedArray[index]);
  76895. }
  76896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76897. }
  76898. };
  76899. };
  76900. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76901. var transform = scene.getTransformMatrix();
  76902. var meshPosition;
  76903. if (this.useCustomMeshPosition) {
  76904. meshPosition = this.customMeshPosition;
  76905. }
  76906. else if (this.attachedNode) {
  76907. meshPosition = this.attachedNode.position;
  76908. }
  76909. else {
  76910. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76911. }
  76912. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76913. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76914. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76915. if (this.invert)
  76916. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76917. };
  76918. // Static methods
  76919. /**
  76920. * Creates a default mesh for the Volumeric Light Scattering post-process
  76921. * @param {string} The mesh name
  76922. * @param {BABYLON.Scene} The scene where to create the mesh
  76923. * @return {BABYLON.Mesh} the default mesh
  76924. */
  76925. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76926. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76927. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76928. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76929. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76930. mesh.material = material;
  76931. return mesh;
  76932. };
  76933. __decorate([
  76934. BABYLON.serializeAsVector3()
  76935. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76936. __decorate([
  76937. BABYLON.serialize()
  76938. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76939. __decorate([
  76940. BABYLON.serialize()
  76941. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76942. __decorate([
  76943. BABYLON.serializeAsMeshReference()
  76944. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76945. __decorate([
  76946. BABYLON.serialize()
  76947. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76948. __decorate([
  76949. BABYLON.serialize()
  76950. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76951. __decorate([
  76952. BABYLON.serialize()
  76953. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76954. __decorate([
  76955. BABYLON.serialize()
  76956. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76957. __decorate([
  76958. BABYLON.serialize()
  76959. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76960. return VolumetricLightScatteringPostProcess;
  76961. }(BABYLON.PostProcess));
  76962. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76963. })(BABYLON || (BABYLON = {}));
  76964. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76965. //
  76966. // This post-process allows the modification of rendered colors by using
  76967. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76968. //
  76969. // The object needs to be provided an url to a texture containing the color
  76970. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76971. // Use an image editing software to tweak the LUT to match your needs.
  76972. //
  76973. // For an example of a color LUT, see here:
  76974. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76975. // For explanations on color grading, see here:
  76976. // http://udn.epicgames.com/Three/ColorGrading.html
  76977. //
  76978. var BABYLON;
  76979. (function (BABYLON) {
  76980. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76981. __extends(ColorCorrectionPostProcess, _super);
  76982. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76983. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76984. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76985. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76986. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76987. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76988. _this.onApply = function (effect) {
  76989. effect.setTexture("colorTable", _this._colorTableTexture);
  76990. };
  76991. return _this;
  76992. }
  76993. return ColorCorrectionPostProcess;
  76994. }(BABYLON.PostProcess));
  76995. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76996. })(BABYLON || (BABYLON = {}));
  76997. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76998. var BABYLON;
  76999. (function (BABYLON) {
  77000. /** Defines operator used for tonemapping */
  77001. var TonemappingOperator;
  77002. (function (TonemappingOperator) {
  77003. /** Hable */
  77004. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77005. /** Reinhard */
  77006. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77007. /** HejiDawson */
  77008. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77009. /** Photographic */
  77010. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77011. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77012. ;
  77013. /**
  77014. * Defines a post process to apply tone mapping
  77015. */
  77016. var TonemapPostProcess = /** @class */ (function (_super) {
  77017. __extends(TonemapPostProcess, _super);
  77018. /**
  77019. * Creates a new TonemapPostProcess
  77020. * @param name defines the name of the postprocess
  77021. * @param _operator defines the operator to use
  77022. * @param exposureAdjustment defines the required exposure adjustement
  77023. * @param camera defines the camera to use (can be null)
  77024. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77025. * @param engine defines the hosting engine (can be ignore if camera is set)
  77026. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77027. */
  77028. function TonemapPostProcess(name, _operator,
  77029. /** Defines the required exposure adjustement */
  77030. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77032. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77033. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77034. _this._operator = _operator;
  77035. _this.exposureAdjustment = exposureAdjustment;
  77036. var defines = "#define ";
  77037. if (_this._operator === TonemappingOperator.Hable)
  77038. defines += "HABLE_TONEMAPPING";
  77039. else if (_this._operator === TonemappingOperator.Reinhard)
  77040. defines += "REINHARD_TONEMAPPING";
  77041. else if (_this._operator === TonemappingOperator.HejiDawson)
  77042. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77043. else if (_this._operator === TonemappingOperator.Photographic)
  77044. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77045. //sadly a second call to create the effect.
  77046. _this.updateEffect(defines);
  77047. _this.onApply = function (effect) {
  77048. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77049. };
  77050. return _this;
  77051. }
  77052. return TonemapPostProcess;
  77053. }(BABYLON.PostProcess));
  77054. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77055. })(BABYLON || (BABYLON = {}));
  77056. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77057. var BABYLON;
  77058. (function (BABYLON) {
  77059. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77060. __extends(DisplayPassPostProcess, _super);
  77061. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77062. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77063. }
  77064. return DisplayPassPostProcess;
  77065. }(BABYLON.PostProcess));
  77066. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77067. })(BABYLON || (BABYLON = {}));
  77068. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77069. var BABYLON;
  77070. (function (BABYLON) {
  77071. var HighlightsPostProcess = /** @class */ (function (_super) {
  77072. __extends(HighlightsPostProcess, _super);
  77073. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77074. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77075. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77076. }
  77077. return HighlightsPostProcess;
  77078. }(BABYLON.PostProcess));
  77079. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77080. })(BABYLON || (BABYLON = {}));
  77081. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77082. var BABYLON;
  77083. (function (BABYLON) {
  77084. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77085. __extends(ImageProcessingPostProcess, _super);
  77086. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77087. if (camera === void 0) { camera = null; }
  77088. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77089. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77090. _this._fromLinearSpace = true;
  77091. /**
  77092. * Defines cache preventing GC.
  77093. */
  77094. _this._defines = {
  77095. IMAGEPROCESSING: false,
  77096. VIGNETTE: false,
  77097. VIGNETTEBLENDMODEMULTIPLY: false,
  77098. VIGNETTEBLENDMODEOPAQUE: false,
  77099. TONEMAPPING: false,
  77100. CONTRAST: false,
  77101. COLORCURVES: false,
  77102. COLORGRADING: false,
  77103. COLORGRADING3D: false,
  77104. FROMLINEARSPACE: false,
  77105. SAMPLER3DGREENDEPTH: false,
  77106. SAMPLER3DBGRMAP: false,
  77107. IMAGEPROCESSINGPOSTPROCESS: false,
  77108. EXPOSURE: false,
  77109. };
  77110. // Setup the configuration as forced by the constructor. This would then not force the
  77111. // scene materials output in linear space and let untouched the default forward pass.
  77112. if (imageProcessingConfiguration) {
  77113. imageProcessingConfiguration.applyByPostProcess = true;
  77114. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77115. // This will cause the shader to be compiled
  77116. _this.fromLinearSpace = false;
  77117. }
  77118. // Setup the default processing configuration to the scene.
  77119. else {
  77120. _this._attachImageProcessingConfiguration(null, true);
  77121. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77122. }
  77123. _this.onApply = function (effect) {
  77124. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77125. };
  77126. return _this;
  77127. }
  77128. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77129. /**
  77130. * Gets the image processing configuration used either in this material.
  77131. */
  77132. get: function () {
  77133. return this._imageProcessingConfiguration;
  77134. },
  77135. /**
  77136. * Sets the Default image processing configuration used either in the this material.
  77137. *
  77138. * If sets to null, the scene one is in use.
  77139. */
  77140. set: function (value) {
  77141. this._attachImageProcessingConfiguration(value);
  77142. },
  77143. enumerable: true,
  77144. configurable: true
  77145. });
  77146. /**
  77147. * Attaches a new image processing configuration to the PBR Material.
  77148. * @param configuration
  77149. */
  77150. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77151. var _this = this;
  77152. if (doNotBuild === void 0) { doNotBuild = false; }
  77153. if (configuration === this._imageProcessingConfiguration) {
  77154. return;
  77155. }
  77156. // Detaches observer.
  77157. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77158. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77159. }
  77160. // Pick the scene configuration if needed.
  77161. if (!configuration) {
  77162. var scene = null;
  77163. var engine = this.getEngine();
  77164. var camera = this.getCamera();
  77165. if (camera) {
  77166. scene = camera.getScene();
  77167. }
  77168. else if (engine && engine.scenes) {
  77169. var scenes = engine.scenes;
  77170. scene = scenes[scenes.length - 1];
  77171. }
  77172. else {
  77173. scene = BABYLON.Engine.LastCreatedScene;
  77174. }
  77175. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77176. }
  77177. else {
  77178. this._imageProcessingConfiguration = configuration;
  77179. }
  77180. // Attaches observer.
  77181. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77182. _this._updateParameters();
  77183. });
  77184. // Ensure the effect will be rebuilt.
  77185. if (!doNotBuild) {
  77186. this._updateParameters();
  77187. }
  77188. };
  77189. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77190. /**
  77191. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77192. */
  77193. get: function () {
  77194. return this.imageProcessingConfiguration.colorCurves;
  77195. },
  77196. /**
  77197. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77198. */
  77199. set: function (value) {
  77200. this.imageProcessingConfiguration.colorCurves = value;
  77201. },
  77202. enumerable: true,
  77203. configurable: true
  77204. });
  77205. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77206. /**
  77207. * Gets wether the color curves effect is enabled.
  77208. */
  77209. get: function () {
  77210. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77211. },
  77212. /**
  77213. * Sets wether the color curves effect is enabled.
  77214. */
  77215. set: function (value) {
  77216. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77217. },
  77218. enumerable: true,
  77219. configurable: true
  77220. });
  77221. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77222. /**
  77223. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77224. */
  77225. get: function () {
  77226. return this.imageProcessingConfiguration.colorGradingTexture;
  77227. },
  77228. /**
  77229. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77230. */
  77231. set: function (value) {
  77232. this.imageProcessingConfiguration.colorGradingTexture = value;
  77233. },
  77234. enumerable: true,
  77235. configurable: true
  77236. });
  77237. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77238. /**
  77239. * Gets wether the color grading effect is enabled.
  77240. */
  77241. get: function () {
  77242. return this.imageProcessingConfiguration.colorGradingEnabled;
  77243. },
  77244. /**
  77245. * Gets wether the color grading effect is enabled.
  77246. */
  77247. set: function (value) {
  77248. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77249. },
  77250. enumerable: true,
  77251. configurable: true
  77252. });
  77253. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77254. /**
  77255. * Gets exposure used in the effect.
  77256. */
  77257. get: function () {
  77258. return this.imageProcessingConfiguration.exposure;
  77259. },
  77260. /**
  77261. * Sets exposure used in the effect.
  77262. */
  77263. set: function (value) {
  77264. this.imageProcessingConfiguration.exposure = value;
  77265. },
  77266. enumerable: true,
  77267. configurable: true
  77268. });
  77269. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77270. /**
  77271. * Gets wether tonemapping is enabled or not.
  77272. */
  77273. get: function () {
  77274. return this._imageProcessingConfiguration.toneMappingEnabled;
  77275. },
  77276. /**
  77277. * Sets wether tonemapping is enabled or not
  77278. */
  77279. set: function (value) {
  77280. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77281. },
  77282. enumerable: true,
  77283. configurable: true
  77284. });
  77285. ;
  77286. ;
  77287. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77288. /**
  77289. * Gets contrast used in the effect.
  77290. */
  77291. get: function () {
  77292. return this.imageProcessingConfiguration.contrast;
  77293. },
  77294. /**
  77295. * Sets contrast used in the effect.
  77296. */
  77297. set: function (value) {
  77298. this.imageProcessingConfiguration.contrast = value;
  77299. },
  77300. enumerable: true,
  77301. configurable: true
  77302. });
  77303. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77304. /**
  77305. * Gets Vignette stretch size.
  77306. */
  77307. get: function () {
  77308. return this.imageProcessingConfiguration.vignetteStretch;
  77309. },
  77310. /**
  77311. * Sets Vignette stretch size.
  77312. */
  77313. set: function (value) {
  77314. this.imageProcessingConfiguration.vignetteStretch = value;
  77315. },
  77316. enumerable: true,
  77317. configurable: true
  77318. });
  77319. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77320. /**
  77321. * Gets Vignette centre X Offset.
  77322. */
  77323. get: function () {
  77324. return this.imageProcessingConfiguration.vignetteCentreX;
  77325. },
  77326. /**
  77327. * Sets Vignette centre X Offset.
  77328. */
  77329. set: function (value) {
  77330. this.imageProcessingConfiguration.vignetteCentreX = value;
  77331. },
  77332. enumerable: true,
  77333. configurable: true
  77334. });
  77335. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77336. /**
  77337. * Gets Vignette centre Y Offset.
  77338. */
  77339. get: function () {
  77340. return this.imageProcessingConfiguration.vignetteCentreY;
  77341. },
  77342. /**
  77343. * Sets Vignette centre Y Offset.
  77344. */
  77345. set: function (value) {
  77346. this.imageProcessingConfiguration.vignetteCentreY = value;
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77352. /**
  77353. * Gets Vignette weight or intensity of the vignette effect.
  77354. */
  77355. get: function () {
  77356. return this.imageProcessingConfiguration.vignetteWeight;
  77357. },
  77358. /**
  77359. * Sets Vignette weight or intensity of the vignette effect.
  77360. */
  77361. set: function (value) {
  77362. this.imageProcessingConfiguration.vignetteWeight = value;
  77363. },
  77364. enumerable: true,
  77365. configurable: true
  77366. });
  77367. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77368. /**
  77369. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77370. * if vignetteEnabled is set to true.
  77371. */
  77372. get: function () {
  77373. return this.imageProcessingConfiguration.vignetteColor;
  77374. },
  77375. /**
  77376. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77377. * if vignetteEnabled is set to true.
  77378. */
  77379. set: function (value) {
  77380. this.imageProcessingConfiguration.vignetteColor = value;
  77381. },
  77382. enumerable: true,
  77383. configurable: true
  77384. });
  77385. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77386. /**
  77387. * Gets Camera field of view used by the Vignette effect.
  77388. */
  77389. get: function () {
  77390. return this.imageProcessingConfiguration.vignetteCameraFov;
  77391. },
  77392. /**
  77393. * Sets Camera field of view used by the Vignette effect.
  77394. */
  77395. set: function (value) {
  77396. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77397. },
  77398. enumerable: true,
  77399. configurable: true
  77400. });
  77401. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77402. /**
  77403. * Gets the vignette blend mode allowing different kind of effect.
  77404. */
  77405. get: function () {
  77406. return this.imageProcessingConfiguration.vignetteBlendMode;
  77407. },
  77408. /**
  77409. * Sets the vignette blend mode allowing different kind of effect.
  77410. */
  77411. set: function (value) {
  77412. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77413. },
  77414. enumerable: true,
  77415. configurable: true
  77416. });
  77417. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77418. /**
  77419. * Gets wether the vignette effect is enabled.
  77420. */
  77421. get: function () {
  77422. return this.imageProcessingConfiguration.vignetteEnabled;
  77423. },
  77424. /**
  77425. * Sets wether the vignette effect is enabled.
  77426. */
  77427. set: function (value) {
  77428. this.imageProcessingConfiguration.vignetteEnabled = value;
  77429. },
  77430. enumerable: true,
  77431. configurable: true
  77432. });
  77433. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77434. /**
  77435. * Gets wether the input of the processing is in Gamma or Linear Space.
  77436. */
  77437. get: function () {
  77438. return this._fromLinearSpace;
  77439. },
  77440. /**
  77441. * Sets wether the input of the processing is in Gamma or Linear Space.
  77442. */
  77443. set: function (value) {
  77444. if (this._fromLinearSpace === value) {
  77445. return;
  77446. }
  77447. this._fromLinearSpace = value;
  77448. this._updateParameters();
  77449. },
  77450. enumerable: true,
  77451. configurable: true
  77452. });
  77453. ImageProcessingPostProcess.prototype.getClassName = function () {
  77454. return "ImageProcessingPostProcess";
  77455. };
  77456. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77457. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77458. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77459. var defines = "";
  77460. for (var define in this._defines) {
  77461. if (this._defines[define]) {
  77462. defines += "#define " + define + ";\r\n";
  77463. }
  77464. }
  77465. var samplers = ["textureSampler"];
  77466. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77467. var uniforms = ["scale"];
  77468. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77469. this.updateEffect(defines, uniforms, samplers);
  77470. };
  77471. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77472. _super.prototype.dispose.call(this, camera);
  77473. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77474. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77475. }
  77476. this.imageProcessingConfiguration.applyByPostProcess = false;
  77477. };
  77478. __decorate([
  77479. BABYLON.serialize()
  77480. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77481. return ImageProcessingPostProcess;
  77482. }(BABYLON.PostProcess));
  77483. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77484. })(BABYLON || (BABYLON = {}));
  77485. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77486. var BABYLON;
  77487. (function (BABYLON) {
  77488. /**
  77489. * Class used to store bone information
  77490. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77491. */
  77492. var Bone = /** @class */ (function (_super) {
  77493. __extends(Bone, _super);
  77494. /**
  77495. * Create a new bone
  77496. * @param name defines the bone name
  77497. * @param skeleton defines the parent skeleton
  77498. * @param parentBone defines the parent (can be null if the bone is the root)
  77499. * @param localMatrix defines the local matrix
  77500. * @param restPose defines the rest pose matrix
  77501. * @param baseMatrix defines the base matrix
  77502. * @param index defines index of the bone in the hiearchy
  77503. */
  77504. function Bone(
  77505. /**
  77506. * defines the bone name
  77507. */
  77508. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77509. if (parentBone === void 0) { parentBone = null; }
  77510. if (localMatrix === void 0) { localMatrix = null; }
  77511. if (restPose === void 0) { restPose = null; }
  77512. if (baseMatrix === void 0) { baseMatrix = null; }
  77513. if (index === void 0) { index = null; }
  77514. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77515. _this.name = name;
  77516. /**
  77517. * Gets the list of child bones
  77518. */
  77519. _this.children = new Array();
  77520. /** Gets the animations associated with this bone */
  77521. _this.animations = new Array();
  77522. /**
  77523. * @hidden Internal only
  77524. * Set this value to map this bone to a different index in the transform matrices
  77525. * Set this value to -1 to exclude the bone from the transform matrices
  77526. */
  77527. _this._index = null;
  77528. _this._absoluteTransform = new BABYLON.Matrix();
  77529. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77530. _this._scalingDeterminant = 1;
  77531. _this._worldTransform = new BABYLON.Matrix();
  77532. _this._needToDecompose = true;
  77533. _this._needToCompose = false;
  77534. _this._skeleton = skeleton;
  77535. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77536. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77537. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77538. _this._index = index;
  77539. skeleton.bones.push(_this);
  77540. _this.setParent(parentBone, false);
  77541. if (baseMatrix || localMatrix) {
  77542. _this._updateDifferenceMatrix();
  77543. }
  77544. return _this;
  77545. }
  77546. Object.defineProperty(Bone.prototype, "_matrix", {
  77547. /** @hidden */
  77548. get: function () {
  77549. this._compose();
  77550. return this._localMatrix;
  77551. },
  77552. /** @hidden */
  77553. set: function (value) {
  77554. this._localMatrix.copyFrom(value);
  77555. this._needToDecompose = true;
  77556. },
  77557. enumerable: true,
  77558. configurable: true
  77559. });
  77560. // Members
  77561. /**
  77562. * Gets the parent skeleton
  77563. * @returns a skeleton
  77564. */
  77565. Bone.prototype.getSkeleton = function () {
  77566. return this._skeleton;
  77567. };
  77568. /**
  77569. * Gets parent bone
  77570. * @returns a bone or null if the bone is the root of the bone hierarchy
  77571. */
  77572. Bone.prototype.getParent = function () {
  77573. return this._parent;
  77574. };
  77575. /**
  77576. * Sets the parent bone
  77577. * @param parent defines the parent (can be null if the bone is the root)
  77578. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77579. */
  77580. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77581. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77582. if (this._parent === parent) {
  77583. return;
  77584. }
  77585. if (this._parent) {
  77586. var index = this._parent.children.indexOf(this);
  77587. if (index !== -1) {
  77588. this._parent.children.splice(index, 1);
  77589. }
  77590. }
  77591. this._parent = parent;
  77592. if (this._parent) {
  77593. this._parent.children.push(this);
  77594. }
  77595. if (updateDifferenceMatrix) {
  77596. this._updateDifferenceMatrix();
  77597. }
  77598. this.markAsDirty();
  77599. };
  77600. /**
  77601. * Gets the local matrix
  77602. * @returns a matrix
  77603. */
  77604. Bone.prototype.getLocalMatrix = function () {
  77605. this._compose();
  77606. return this._localMatrix;
  77607. };
  77608. /**
  77609. * Gets the base matrix (initial matrix which remains unchanged)
  77610. * @returns a matrix
  77611. */
  77612. Bone.prototype.getBaseMatrix = function () {
  77613. return this._baseMatrix;
  77614. };
  77615. /**
  77616. * Gets the rest pose matrix
  77617. * @returns a matrix
  77618. */
  77619. Bone.prototype.getRestPose = function () {
  77620. return this._restPose;
  77621. };
  77622. /**
  77623. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77624. */
  77625. Bone.prototype.getWorldMatrix = function () {
  77626. return this._worldTransform;
  77627. };
  77628. /**
  77629. * Sets the local matrix to rest pose matrix
  77630. */
  77631. Bone.prototype.returnToRest = function () {
  77632. this.updateMatrix(this._restPose.clone());
  77633. };
  77634. /**
  77635. * Gets the inverse of the absolute transform matrix.
  77636. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77637. * @returns a matrix
  77638. */
  77639. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77640. return this._invertedAbsoluteTransform;
  77641. };
  77642. /**
  77643. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77644. * @returns a matrix
  77645. */
  77646. Bone.prototype.getAbsoluteTransform = function () {
  77647. return this._absoluteTransform;
  77648. };
  77649. Object.defineProperty(Bone.prototype, "position", {
  77650. // Properties (matches AbstractMesh properties)
  77651. /** Gets or sets current position (in local space) */
  77652. get: function () {
  77653. this._decompose();
  77654. return this._localPosition;
  77655. },
  77656. set: function (newPosition) {
  77657. this._decompose();
  77658. this._localPosition.copyFrom(newPosition);
  77659. this._markAsDirtyAndCompose();
  77660. },
  77661. enumerable: true,
  77662. configurable: true
  77663. });
  77664. Object.defineProperty(Bone.prototype, "rotation", {
  77665. /** Gets or sets current rotation (in local space) */
  77666. get: function () {
  77667. return this.getRotation();
  77668. },
  77669. set: function (newRotation) {
  77670. this.setRotation(newRotation);
  77671. },
  77672. enumerable: true,
  77673. configurable: true
  77674. });
  77675. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77676. /** Gets or sets current rotation quaternion (in local space) */
  77677. get: function () {
  77678. this._decompose();
  77679. return this._localRotation;
  77680. },
  77681. set: function (newRotation) {
  77682. this.setRotationQuaternion(newRotation);
  77683. },
  77684. enumerable: true,
  77685. configurable: true
  77686. });
  77687. Object.defineProperty(Bone.prototype, "scaling", {
  77688. /** Gets or sets current scaling (in local space) */
  77689. get: function () {
  77690. return this.getScale();
  77691. },
  77692. set: function (newScaling) {
  77693. this.setScale(newScaling);
  77694. },
  77695. enumerable: true,
  77696. configurable: true
  77697. });
  77698. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77699. /**
  77700. * Gets the animation properties override
  77701. */
  77702. get: function () {
  77703. return this._skeleton.animationPropertiesOverride;
  77704. },
  77705. enumerable: true,
  77706. configurable: true
  77707. });
  77708. // Methods
  77709. Bone.prototype._decompose = function () {
  77710. if (!this._needToDecompose) {
  77711. return;
  77712. }
  77713. this._needToDecompose = false;
  77714. if (!this._localScaling) {
  77715. this._localScaling = BABYLON.Vector3.Zero();
  77716. this._localRotation = BABYLON.Quaternion.Zero();
  77717. this._localPosition = BABYLON.Vector3.Zero();
  77718. }
  77719. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77720. };
  77721. Bone.prototype._compose = function () {
  77722. if (!this._needToCompose) {
  77723. return;
  77724. }
  77725. this._needToCompose = false;
  77726. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77727. };
  77728. /**
  77729. * Update the base and local matrices
  77730. * @param matrix defines the new base or local matrix
  77731. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77732. * @param updateLocalMatrix defines if the local matrix should be updated
  77733. */
  77734. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77735. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77736. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77737. this._baseMatrix.copyFrom(matrix);
  77738. if (updateDifferenceMatrix) {
  77739. this._updateDifferenceMatrix();
  77740. }
  77741. if (updateLocalMatrix) {
  77742. this._localMatrix.copyFrom(matrix);
  77743. this._markAsDirtyAndDecompose();
  77744. }
  77745. else {
  77746. this.markAsDirty();
  77747. }
  77748. };
  77749. /** @hidden */
  77750. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77751. if (updateChildren === void 0) { updateChildren = true; }
  77752. if (!rootMatrix) {
  77753. rootMatrix = this._baseMatrix;
  77754. }
  77755. if (this._parent) {
  77756. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77757. }
  77758. else {
  77759. this._absoluteTransform.copyFrom(rootMatrix);
  77760. }
  77761. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77762. if (updateChildren) {
  77763. for (var index = 0; index < this.children.length; index++) {
  77764. this.children[index]._updateDifferenceMatrix();
  77765. }
  77766. }
  77767. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77768. };
  77769. /**
  77770. * Flag the bone as dirty (Forcing it to update everything)
  77771. */
  77772. Bone.prototype.markAsDirty = function () {
  77773. this._currentRenderId++;
  77774. this._childRenderId++;
  77775. this._skeleton._markAsDirty();
  77776. };
  77777. Bone.prototype._markAsDirtyAndCompose = function () {
  77778. this.markAsDirty();
  77779. this._needToCompose = true;
  77780. };
  77781. Bone.prototype._markAsDirtyAndDecompose = function () {
  77782. this.markAsDirty();
  77783. this._needToDecompose = true;
  77784. };
  77785. /**
  77786. * Copy an animation range from another bone
  77787. * @param source defines the source bone
  77788. * @param rangeName defines the range name to copy
  77789. * @param frameOffset defines the frame offset
  77790. * @param rescaleAsRequired defines if rescaling must be applied if required
  77791. * @param skelDimensionsRatio defines the scaling ratio
  77792. * @returns true if operation was successful
  77793. */
  77794. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77795. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77796. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77797. // all animation may be coming from a library skeleton, so may need to create animation
  77798. if (this.animations.length === 0) {
  77799. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77800. this.animations[0].setKeys([]);
  77801. }
  77802. // get animation info / verify there is such a range from the source bone
  77803. var sourceRange = source.animations[0].getRange(rangeName);
  77804. if (!sourceRange) {
  77805. return false;
  77806. }
  77807. var from = sourceRange.from;
  77808. var to = sourceRange.to;
  77809. var sourceKeys = source.animations[0].getKeys();
  77810. // rescaling prep
  77811. var sourceBoneLength = source.length;
  77812. var sourceParent = source.getParent();
  77813. var parent = this.getParent();
  77814. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77815. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77816. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77817. var destKeys = this.animations[0].getKeys();
  77818. // loop vars declaration
  77819. var orig;
  77820. var origTranslation;
  77821. var mat;
  77822. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77823. orig = sourceKeys[key];
  77824. if (orig.frame >= from && orig.frame <= to) {
  77825. if (rescaleAsRequired) {
  77826. mat = orig.value.clone();
  77827. // scale based on parent ratio, when bone has parent
  77828. if (parentScalingReqd) {
  77829. origTranslation = mat.getTranslation();
  77830. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77831. // scale based on skeleton dimension ratio when root bone, and value is passed
  77832. }
  77833. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77834. origTranslation = mat.getTranslation();
  77835. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77836. // use original when root bone, and no data for skelDimensionsRatio
  77837. }
  77838. else {
  77839. mat = orig.value;
  77840. }
  77841. }
  77842. else {
  77843. mat = orig.value;
  77844. }
  77845. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77846. }
  77847. }
  77848. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77849. return true;
  77850. };
  77851. /**
  77852. * Translate the bone in local or world space
  77853. * @param vec The amount to translate the bone
  77854. * @param space The space that the translation is in
  77855. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77856. */
  77857. Bone.prototype.translate = function (vec, space, mesh) {
  77858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77859. var lm = this.getLocalMatrix();
  77860. if (space == BABYLON.Space.LOCAL) {
  77861. lm.m[12] += vec.x;
  77862. lm.m[13] += vec.y;
  77863. lm.m[14] += vec.z;
  77864. }
  77865. else {
  77866. var wm = null;
  77867. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77868. if (mesh) {
  77869. wm = mesh.getWorldMatrix();
  77870. }
  77871. this._skeleton.computeAbsoluteTransforms();
  77872. var tmat = Bone._tmpMats[0];
  77873. var tvec = Bone._tmpVecs[0];
  77874. if (this._parent) {
  77875. if (mesh && wm) {
  77876. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77877. tmat.multiplyToRef(wm, tmat);
  77878. }
  77879. else {
  77880. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77881. }
  77882. }
  77883. tmat.m[12] = 0;
  77884. tmat.m[13] = 0;
  77885. tmat.m[14] = 0;
  77886. tmat.invert();
  77887. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77888. lm.m[12] += tvec.x;
  77889. lm.m[13] += tvec.y;
  77890. lm.m[14] += tvec.z;
  77891. }
  77892. this._markAsDirtyAndDecompose();
  77893. };
  77894. /**
  77895. * Set the postion of the bone in local or world space
  77896. * @param position The position to set the bone
  77897. * @param space The space that the position is in
  77898. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77899. */
  77900. Bone.prototype.setPosition = function (position, space, mesh) {
  77901. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77902. var lm = this.getLocalMatrix();
  77903. if (space == BABYLON.Space.LOCAL) {
  77904. lm.m[12] = position.x;
  77905. lm.m[13] = position.y;
  77906. lm.m[14] = position.z;
  77907. }
  77908. else {
  77909. var wm = null;
  77910. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77911. if (mesh) {
  77912. wm = mesh.getWorldMatrix();
  77913. }
  77914. this._skeleton.computeAbsoluteTransforms();
  77915. var tmat = Bone._tmpMats[0];
  77916. var vec = Bone._tmpVecs[0];
  77917. if (this._parent) {
  77918. if (mesh && wm) {
  77919. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77920. tmat.multiplyToRef(wm, tmat);
  77921. }
  77922. else {
  77923. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77924. }
  77925. }
  77926. tmat.invert();
  77927. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77928. lm.m[12] = vec.x;
  77929. lm.m[13] = vec.y;
  77930. lm.m[14] = vec.z;
  77931. }
  77932. this._markAsDirtyAndDecompose();
  77933. };
  77934. /**
  77935. * Set the absolute position of the bone (world space)
  77936. * @param position The position to set the bone
  77937. * @param mesh The mesh that this bone is attached to
  77938. */
  77939. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77940. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77941. };
  77942. /**
  77943. * Scale the bone on the x, y and z axes (in local space)
  77944. * @param x The amount to scale the bone on the x axis
  77945. * @param y The amount to scale the bone on the y axis
  77946. * @param z The amount to scale the bone on the z axis
  77947. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77948. */
  77949. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77950. if (scaleChildren === void 0) { scaleChildren = false; }
  77951. var locMat = this.getLocalMatrix();
  77952. // Apply new scaling on top of current local matrix
  77953. var scaleMat = Bone._tmpMats[0];
  77954. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77955. scaleMat.multiplyToRef(locMat, locMat);
  77956. // Invert scaling matrix and apply the inverse to all children
  77957. scaleMat.invert();
  77958. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77959. var child = _a[_i];
  77960. var cm = child.getLocalMatrix();
  77961. cm.multiplyToRef(scaleMat, cm);
  77962. cm.m[12] *= x;
  77963. cm.m[13] *= y;
  77964. cm.m[14] *= z;
  77965. child._markAsDirtyAndDecompose();
  77966. }
  77967. this._markAsDirtyAndDecompose();
  77968. if (scaleChildren) {
  77969. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77970. var child = _c[_b];
  77971. child.scale(x, y, z, scaleChildren);
  77972. }
  77973. }
  77974. };
  77975. /**
  77976. * Set the bone scaling in local space
  77977. * @param scale defines the scaling vector
  77978. */
  77979. Bone.prototype.setScale = function (scale) {
  77980. this._decompose();
  77981. this._localScaling.copyFrom(scale);
  77982. this._markAsDirtyAndCompose();
  77983. };
  77984. /**
  77985. * Gets the current scaling in local space
  77986. * @returns the current scaling vector
  77987. */
  77988. Bone.prototype.getScale = function () {
  77989. this._decompose();
  77990. return this._localScaling;
  77991. };
  77992. /**
  77993. * Gets the current scaling in local space and stores it in a target vector
  77994. * @param result defines the target vector
  77995. */
  77996. Bone.prototype.getScaleToRef = function (result) {
  77997. this._decompose();
  77998. result.copyFrom(this._localScaling);
  77999. };
  78000. /**
  78001. * Set the yaw, pitch, and roll of the bone in local or world space
  78002. * @param yaw The rotation of the bone on the y axis
  78003. * @param pitch The rotation of the bone on the x axis
  78004. * @param roll The rotation of the bone on the z axis
  78005. * @param space The space that the axes of rotation are in
  78006. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78007. */
  78008. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78010. if (space === BABYLON.Space.LOCAL) {
  78011. var quat = Bone._tmpQuat;
  78012. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78013. this.setRotationQuaternion(quat, space, mesh);
  78014. return;
  78015. }
  78016. var rotMatInv = Bone._tmpMats[0];
  78017. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78018. return;
  78019. }
  78020. var rotMat = Bone._tmpMats[1];
  78021. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78022. rotMatInv.multiplyToRef(rotMat, rotMat);
  78023. this._rotateWithMatrix(rotMat, space, mesh);
  78024. };
  78025. /**
  78026. * Add a rotation to the bone on an axis in local or world space
  78027. * @param axis The axis to rotate the bone on
  78028. * @param amount The amount to rotate the bone
  78029. * @param space The space that the axis is in
  78030. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78031. */
  78032. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78034. var rmat = Bone._tmpMats[0];
  78035. rmat.m[12] = 0;
  78036. rmat.m[13] = 0;
  78037. rmat.m[14] = 0;
  78038. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78039. this._rotateWithMatrix(rmat, space, mesh);
  78040. };
  78041. /**
  78042. * Set the rotation of the bone to a particular axis angle in local or world space
  78043. * @param axis The axis to rotate the bone on
  78044. * @param angle The angle that the bone should be rotated to
  78045. * @param space The space that the axis is in
  78046. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78047. */
  78048. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78050. if (space === BABYLON.Space.LOCAL) {
  78051. var quat = Bone._tmpQuat;
  78052. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78053. this.setRotationQuaternion(quat, space, mesh);
  78054. return;
  78055. }
  78056. var rotMatInv = Bone._tmpMats[0];
  78057. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78058. return;
  78059. }
  78060. var rotMat = Bone._tmpMats[1];
  78061. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78062. rotMatInv.multiplyToRef(rotMat, rotMat);
  78063. this._rotateWithMatrix(rotMat, space, mesh);
  78064. };
  78065. /**
  78066. * Set the euler rotation of the bone in local of world space
  78067. * @param rotation The euler rotation that the bone should be set to
  78068. * @param space The space that the rotation is in
  78069. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78070. */
  78071. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78072. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78073. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78074. };
  78075. /**
  78076. * Set the quaternion rotation of the bone in local of world space
  78077. * @param quat The quaternion rotation that the bone should be set to
  78078. * @param space The space that the rotation is in
  78079. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78080. */
  78081. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78083. if (space === BABYLON.Space.LOCAL) {
  78084. this._decompose();
  78085. this._localRotation.copyFrom(quat);
  78086. this._markAsDirtyAndCompose();
  78087. return;
  78088. }
  78089. var rotMatInv = Bone._tmpMats[0];
  78090. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78091. return;
  78092. }
  78093. var rotMat = Bone._tmpMats[1];
  78094. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78095. rotMatInv.multiplyToRef(rotMat, rotMat);
  78096. this._rotateWithMatrix(rotMat, space, mesh);
  78097. };
  78098. /**
  78099. * Set the rotation matrix of the bone in local of world space
  78100. * @param rotMat The rotation matrix that the bone should be set to
  78101. * @param space The space that the rotation is in
  78102. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78103. */
  78104. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78106. if (space === BABYLON.Space.LOCAL) {
  78107. var quat = Bone._tmpQuat;
  78108. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78109. this.setRotationQuaternion(quat, space, mesh);
  78110. return;
  78111. }
  78112. var rotMatInv = Bone._tmpMats[0];
  78113. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78114. return;
  78115. }
  78116. var rotMat2 = Bone._tmpMats[1];
  78117. rotMat2.copyFrom(rotMat);
  78118. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78119. this._rotateWithMatrix(rotMat2, space, mesh);
  78120. };
  78121. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78122. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78123. var lmat = this.getLocalMatrix();
  78124. var lx = lmat.m[12];
  78125. var ly = lmat.m[13];
  78126. var lz = lmat.m[14];
  78127. var parent = this.getParent();
  78128. var parentScale = Bone._tmpMats[3];
  78129. var parentScaleInv = Bone._tmpMats[4];
  78130. if (parent && space == BABYLON.Space.WORLD) {
  78131. if (mesh) {
  78132. parentScale.copyFrom(mesh.getWorldMatrix());
  78133. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78134. }
  78135. else {
  78136. parentScale.copyFrom(parent.getAbsoluteTransform());
  78137. }
  78138. parentScaleInv.copyFrom(parentScale);
  78139. parentScaleInv.invert();
  78140. lmat.multiplyToRef(parentScale, lmat);
  78141. lmat.multiplyToRef(rmat, lmat);
  78142. lmat.multiplyToRef(parentScaleInv, lmat);
  78143. }
  78144. else {
  78145. if (space == BABYLON.Space.WORLD && mesh) {
  78146. parentScale.copyFrom(mesh.getWorldMatrix());
  78147. parentScaleInv.copyFrom(parentScale);
  78148. parentScaleInv.invert();
  78149. lmat.multiplyToRef(parentScale, lmat);
  78150. lmat.multiplyToRef(rmat, lmat);
  78151. lmat.multiplyToRef(parentScaleInv, lmat);
  78152. }
  78153. else {
  78154. lmat.multiplyToRef(rmat, lmat);
  78155. }
  78156. }
  78157. lmat.m[12] = lx;
  78158. lmat.m[13] = ly;
  78159. lmat.m[14] = lz;
  78160. this.computeAbsoluteTransforms();
  78161. this._markAsDirtyAndDecompose();
  78162. };
  78163. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78164. var scaleMatrix = Bone._tmpMats[2];
  78165. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78166. if (mesh) {
  78167. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78168. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78169. }
  78170. rotMatInv.invert();
  78171. if (isNaN(rotMatInv.m[0])) {
  78172. // Matrix failed to invert.
  78173. // This can happen if scale is zero for example.
  78174. return false;
  78175. }
  78176. scaleMatrix.m[0] *= this._scalingDeterminant;
  78177. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78178. return true;
  78179. };
  78180. /**
  78181. * Get the position of the bone in local or world space
  78182. * @param space The space that the returned position is in
  78183. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78184. * @returns The position of the bone
  78185. */
  78186. Bone.prototype.getPosition = function (space, mesh) {
  78187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78188. if (mesh === void 0) { mesh = null; }
  78189. var pos = BABYLON.Vector3.Zero();
  78190. this.getPositionToRef(space, mesh, pos);
  78191. return pos;
  78192. };
  78193. /**
  78194. * Copy the position of the bone to a vector3 in local or world space
  78195. * @param space The space that the returned position is in
  78196. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78197. * @param result The vector3 to copy the position to
  78198. */
  78199. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78200. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78201. if (space == BABYLON.Space.LOCAL) {
  78202. var lm = this.getLocalMatrix();
  78203. result.x = lm.m[12];
  78204. result.y = lm.m[13];
  78205. result.z = lm.m[14];
  78206. }
  78207. else {
  78208. var wm = null;
  78209. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78210. if (mesh) {
  78211. wm = mesh.getWorldMatrix();
  78212. }
  78213. this._skeleton.computeAbsoluteTransforms();
  78214. var tmat = Bone._tmpMats[0];
  78215. if (mesh && wm) {
  78216. tmat.copyFrom(this.getAbsoluteTransform());
  78217. tmat.multiplyToRef(wm, tmat);
  78218. }
  78219. else {
  78220. tmat = this.getAbsoluteTransform();
  78221. }
  78222. result.x = tmat.m[12];
  78223. result.y = tmat.m[13];
  78224. result.z = tmat.m[14];
  78225. }
  78226. };
  78227. /**
  78228. * Get the absolute position of the bone (world space)
  78229. * @param mesh The mesh that this bone is attached to
  78230. * @returns The absolute position of the bone
  78231. */
  78232. Bone.prototype.getAbsolutePosition = function (mesh) {
  78233. if (mesh === void 0) { mesh = null; }
  78234. var pos = BABYLON.Vector3.Zero();
  78235. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78236. return pos;
  78237. };
  78238. /**
  78239. * Copy the absolute position of the bone (world space) to the result param
  78240. * @param mesh The mesh that this bone is attached to
  78241. * @param result The vector3 to copy the absolute position to
  78242. */
  78243. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78244. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78245. };
  78246. /**
  78247. * Compute the absolute transforms of this bone and its children
  78248. */
  78249. Bone.prototype.computeAbsoluteTransforms = function () {
  78250. this._compose();
  78251. if (this._parent) {
  78252. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78253. }
  78254. else {
  78255. this._absoluteTransform.copyFrom(this._localMatrix);
  78256. var poseMatrix = this._skeleton.getPoseMatrix();
  78257. if (poseMatrix) {
  78258. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78259. }
  78260. }
  78261. var children = this.children;
  78262. var len = children.length;
  78263. for (var i = 0; i < len; i++) {
  78264. children[i].computeAbsoluteTransforms();
  78265. }
  78266. };
  78267. /**
  78268. * Get the world direction from an axis that is in the local space of the bone
  78269. * @param localAxis The local direction that is used to compute the world direction
  78270. * @param mesh The mesh that this bone is attached to
  78271. * @returns The world direction
  78272. */
  78273. Bone.prototype.getDirection = function (localAxis, mesh) {
  78274. if (mesh === void 0) { mesh = null; }
  78275. var result = BABYLON.Vector3.Zero();
  78276. this.getDirectionToRef(localAxis, mesh, result);
  78277. return result;
  78278. };
  78279. /**
  78280. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78281. * @param localAxis The local direction that is used to compute the world direction
  78282. * @param mesh The mesh that this bone is attached to
  78283. * @param result The vector3 that the world direction will be copied to
  78284. */
  78285. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78286. if (mesh === void 0) { mesh = null; }
  78287. var wm = null;
  78288. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78289. if (mesh) {
  78290. wm = mesh.getWorldMatrix();
  78291. }
  78292. this._skeleton.computeAbsoluteTransforms();
  78293. var mat = Bone._tmpMats[0];
  78294. mat.copyFrom(this.getAbsoluteTransform());
  78295. if (mesh && wm) {
  78296. mat.multiplyToRef(wm, mat);
  78297. }
  78298. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78299. result.normalize();
  78300. };
  78301. /**
  78302. * Get the euler rotation of the bone in local or world space
  78303. * @param space The space that the rotation should be in
  78304. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78305. * @returns The euler rotation
  78306. */
  78307. Bone.prototype.getRotation = function (space, mesh) {
  78308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78309. if (mesh === void 0) { mesh = null; }
  78310. var result = BABYLON.Vector3.Zero();
  78311. this.getRotationToRef(space, mesh, result);
  78312. return result;
  78313. };
  78314. /**
  78315. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78316. * @param space The space that the rotation should be in
  78317. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78318. * @param result The vector3 that the rotation should be copied to
  78319. */
  78320. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78322. if (mesh === void 0) { mesh = null; }
  78323. var quat = Bone._tmpQuat;
  78324. this.getRotationQuaternionToRef(space, mesh, quat);
  78325. quat.toEulerAnglesToRef(result);
  78326. };
  78327. /**
  78328. * Get the quaternion rotation of the bone in either local or world space
  78329. * @param space The space that the rotation should be in
  78330. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78331. * @returns The quaternion rotation
  78332. */
  78333. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78335. if (mesh === void 0) { mesh = null; }
  78336. var result = BABYLON.Quaternion.Identity();
  78337. this.getRotationQuaternionToRef(space, mesh, result);
  78338. return result;
  78339. };
  78340. /**
  78341. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78342. * @param space The space that the rotation should be in
  78343. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78344. * @param result The quaternion that the rotation should be copied to
  78345. */
  78346. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78347. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78348. if (mesh === void 0) { mesh = null; }
  78349. if (space == BABYLON.Space.LOCAL) {
  78350. this._decompose();
  78351. result.copyFrom(this._localRotation);
  78352. }
  78353. else {
  78354. var mat = Bone._tmpMats[0];
  78355. var amat = this.getAbsoluteTransform();
  78356. if (mesh) {
  78357. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78358. }
  78359. else {
  78360. mat.copyFrom(amat);
  78361. }
  78362. mat.m[0] *= this._scalingDeterminant;
  78363. mat.m[1] *= this._scalingDeterminant;
  78364. mat.m[2] *= this._scalingDeterminant;
  78365. mat.decompose(undefined, result, undefined);
  78366. }
  78367. };
  78368. /**
  78369. * Get the rotation matrix of the bone in local or world space
  78370. * @param space The space that the rotation should be in
  78371. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78372. * @returns The rotation matrix
  78373. */
  78374. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78375. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78376. var result = BABYLON.Matrix.Identity();
  78377. this.getRotationMatrixToRef(space, mesh, result);
  78378. return result;
  78379. };
  78380. /**
  78381. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78382. * @param space The space that the rotation should be in
  78383. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78384. * @param result The quaternion that the rotation should be copied to
  78385. */
  78386. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78388. if (space == BABYLON.Space.LOCAL) {
  78389. this.getLocalMatrix().getRotationMatrixToRef(result);
  78390. }
  78391. else {
  78392. var mat = Bone._tmpMats[0];
  78393. var amat = this.getAbsoluteTransform();
  78394. if (mesh) {
  78395. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78396. }
  78397. else {
  78398. mat.copyFrom(amat);
  78399. }
  78400. mat.m[0] *= this._scalingDeterminant;
  78401. mat.m[1] *= this._scalingDeterminant;
  78402. mat.m[2] *= this._scalingDeterminant;
  78403. mat.getRotationMatrixToRef(result);
  78404. }
  78405. };
  78406. /**
  78407. * Get the world position of a point that is in the local space of the bone
  78408. * @param position The local position
  78409. * @param mesh The mesh that this bone is attached to
  78410. * @returns The world position
  78411. */
  78412. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78413. if (mesh === void 0) { mesh = null; }
  78414. var result = BABYLON.Vector3.Zero();
  78415. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78416. return result;
  78417. };
  78418. /**
  78419. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78420. * @param position The local position
  78421. * @param mesh The mesh that this bone is attached to
  78422. * @param result The vector3 that the world position should be copied to
  78423. */
  78424. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78425. if (mesh === void 0) { mesh = null; }
  78426. var wm = null;
  78427. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78428. if (mesh) {
  78429. wm = mesh.getWorldMatrix();
  78430. }
  78431. this._skeleton.computeAbsoluteTransforms();
  78432. var tmat = Bone._tmpMats[0];
  78433. if (mesh && wm) {
  78434. tmat.copyFrom(this.getAbsoluteTransform());
  78435. tmat.multiplyToRef(wm, tmat);
  78436. }
  78437. else {
  78438. tmat = this.getAbsoluteTransform();
  78439. }
  78440. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78441. };
  78442. /**
  78443. * Get the local position of a point that is in world space
  78444. * @param position The world position
  78445. * @param mesh The mesh that this bone is attached to
  78446. * @returns The local position
  78447. */
  78448. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78449. if (mesh === void 0) { mesh = null; }
  78450. var result = BABYLON.Vector3.Zero();
  78451. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78452. return result;
  78453. };
  78454. /**
  78455. * Get the local position of a point that is in world space and copy it to the result param
  78456. * @param position The world position
  78457. * @param mesh The mesh that this bone is attached to
  78458. * @param result The vector3 that the local position should be copied to
  78459. */
  78460. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78461. if (mesh === void 0) { mesh = null; }
  78462. var wm = null;
  78463. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78464. if (mesh) {
  78465. wm = mesh.getWorldMatrix();
  78466. }
  78467. this._skeleton.computeAbsoluteTransforms();
  78468. var tmat = Bone._tmpMats[0];
  78469. tmat.copyFrom(this.getAbsoluteTransform());
  78470. if (mesh && wm) {
  78471. tmat.multiplyToRef(wm, tmat);
  78472. }
  78473. tmat.invert();
  78474. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78475. };
  78476. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78477. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78478. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78479. return Bone;
  78480. }(BABYLON.Node));
  78481. BABYLON.Bone = Bone;
  78482. })(BABYLON || (BABYLON = {}));
  78483. //# sourceMappingURL=babylon.bone.js.map
  78484. var BABYLON;
  78485. (function (BABYLON) {
  78486. /**
  78487. * Class used to apply inverse kinematics to bones
  78488. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78489. */
  78490. var BoneIKController = /** @class */ (function () {
  78491. /**
  78492. * Creates a new BoneIKController
  78493. * @param mesh defines the mesh to control
  78494. * @param bone defines the bone to control
  78495. * @param options defines options to set up the controller
  78496. */
  78497. function BoneIKController(mesh, bone, options) {
  78498. /**
  78499. * Gets or sets the target position
  78500. */
  78501. this.targetPosition = BABYLON.Vector3.Zero();
  78502. /**
  78503. * Gets or sets the pole target position
  78504. */
  78505. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78506. /**
  78507. * Gets or sets the pole target local offset
  78508. */
  78509. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78510. /**
  78511. * Gets or sets the pole angle
  78512. */
  78513. this.poleAngle = 0;
  78514. /**
  78515. * 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)
  78516. */
  78517. this.slerpAmount = 1;
  78518. this._bone1Quat = BABYLON.Quaternion.Identity();
  78519. this._bone1Mat = BABYLON.Matrix.Identity();
  78520. this._bone2Ang = Math.PI;
  78521. this._maxAngle = Math.PI;
  78522. this._rightHandedSystem = false;
  78523. this._bendAxis = BABYLON.Vector3.Right();
  78524. this._slerping = false;
  78525. this._adjustRoll = 0;
  78526. this._bone2 = bone;
  78527. this._bone1 = bone.getParent();
  78528. if (!this._bone1) {
  78529. return;
  78530. }
  78531. this.mesh = mesh;
  78532. var bonePos = bone.getPosition();
  78533. if (bone.getAbsoluteTransform().determinant() > 0) {
  78534. this._rightHandedSystem = true;
  78535. this._bendAxis.x = 0;
  78536. this._bendAxis.y = 0;
  78537. this._bendAxis.z = -1;
  78538. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78539. this._adjustRoll = Math.PI * .5;
  78540. this._bendAxis.z = 1;
  78541. }
  78542. }
  78543. if (this._bone1.length) {
  78544. var boneScale1 = this._bone1.getScale();
  78545. var boneScale2 = this._bone2.getScale();
  78546. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78547. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78548. }
  78549. else if (this._bone1.children[0]) {
  78550. mesh.computeWorldMatrix(true);
  78551. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78552. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78553. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78554. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78555. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78556. }
  78557. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78558. this.maxAngle = Math.PI;
  78559. if (options) {
  78560. if (options.targetMesh) {
  78561. this.targetMesh = options.targetMesh;
  78562. this.targetMesh.computeWorldMatrix(true);
  78563. }
  78564. if (options.poleTargetMesh) {
  78565. this.poleTargetMesh = options.poleTargetMesh;
  78566. this.poleTargetMesh.computeWorldMatrix(true);
  78567. }
  78568. else if (options.poleTargetBone) {
  78569. this.poleTargetBone = options.poleTargetBone;
  78570. }
  78571. else if (this._bone1.getParent()) {
  78572. this.poleTargetBone = this._bone1.getParent();
  78573. }
  78574. if (options.poleTargetLocalOffset) {
  78575. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78576. }
  78577. if (options.poleAngle) {
  78578. this.poleAngle = options.poleAngle;
  78579. }
  78580. if (options.bendAxis) {
  78581. this._bendAxis.copyFrom(options.bendAxis);
  78582. }
  78583. if (options.maxAngle) {
  78584. this.maxAngle = options.maxAngle;
  78585. }
  78586. if (options.slerpAmount) {
  78587. this.slerpAmount = options.slerpAmount;
  78588. }
  78589. }
  78590. }
  78591. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78592. /**
  78593. * Gets or sets maximum allowed angle
  78594. */
  78595. get: function () {
  78596. return this._maxAngle;
  78597. },
  78598. set: function (value) {
  78599. this._setMaxAngle(value);
  78600. },
  78601. enumerable: true,
  78602. configurable: true
  78603. });
  78604. BoneIKController.prototype._setMaxAngle = function (ang) {
  78605. if (ang < 0) {
  78606. ang = 0;
  78607. }
  78608. if (ang > Math.PI || ang == undefined) {
  78609. ang = Math.PI;
  78610. }
  78611. this._maxAngle = ang;
  78612. var a = this._bone1Length;
  78613. var b = this._bone2Length;
  78614. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78615. };
  78616. /**
  78617. * Force the controller to update the bones
  78618. */
  78619. BoneIKController.prototype.update = function () {
  78620. var bone1 = this._bone1;
  78621. if (!bone1) {
  78622. return;
  78623. }
  78624. var target = this.targetPosition;
  78625. var poleTarget = this.poleTargetPosition;
  78626. var mat1 = BoneIKController._tmpMats[0];
  78627. var mat2 = BoneIKController._tmpMats[1];
  78628. if (this.targetMesh) {
  78629. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78630. }
  78631. if (this.poleTargetBone) {
  78632. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78633. }
  78634. else if (this.poleTargetMesh) {
  78635. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78636. }
  78637. var bonePos = BoneIKController._tmpVecs[0];
  78638. var zaxis = BoneIKController._tmpVecs[1];
  78639. var xaxis = BoneIKController._tmpVecs[2];
  78640. var yaxis = BoneIKController._tmpVecs[3];
  78641. var upAxis = BoneIKController._tmpVecs[4];
  78642. var _tmpQuat = BoneIKController._tmpQuat;
  78643. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78644. poleTarget.subtractToRef(bonePos, upAxis);
  78645. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78646. upAxis.y = 1;
  78647. }
  78648. else {
  78649. upAxis.normalize();
  78650. }
  78651. target.subtractToRef(bonePos, yaxis);
  78652. yaxis.normalize();
  78653. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78654. zaxis.normalize();
  78655. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78656. xaxis.normalize();
  78657. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78658. var a = this._bone1Length;
  78659. var b = this._bone2Length;
  78660. var c = BABYLON.Vector3.Distance(bonePos, target);
  78661. if (this._maxReach > 0) {
  78662. c = Math.min(this._maxReach, c);
  78663. }
  78664. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78665. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78666. if (acosa > 1) {
  78667. acosa = 1;
  78668. }
  78669. if (acosb > 1) {
  78670. acosb = 1;
  78671. }
  78672. if (acosa < -1) {
  78673. acosa = -1;
  78674. }
  78675. if (acosb < -1) {
  78676. acosb = -1;
  78677. }
  78678. var angA = Math.acos(acosa);
  78679. var angB = Math.acos(acosb);
  78680. var angC = -angA - angB;
  78681. if (this._rightHandedSystem) {
  78682. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78683. mat2.multiplyToRef(mat1, mat1);
  78684. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78685. mat2.multiplyToRef(mat1, mat1);
  78686. }
  78687. else {
  78688. var _tmpVec = BoneIKController._tmpVecs[5];
  78689. _tmpVec.copyFrom(this._bendAxis);
  78690. _tmpVec.x *= -1;
  78691. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78692. mat2.multiplyToRef(mat1, mat1);
  78693. }
  78694. if (this.poleAngle) {
  78695. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78696. mat1.multiplyToRef(mat2, mat1);
  78697. }
  78698. if (this._bone1) {
  78699. if (this.slerpAmount < 1) {
  78700. if (!this._slerping) {
  78701. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78702. }
  78703. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78704. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78705. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78706. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78707. this._slerping = true;
  78708. }
  78709. else {
  78710. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78711. this._bone1Mat.copyFrom(mat1);
  78712. this._slerping = false;
  78713. }
  78714. }
  78715. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78716. this._bone2Ang = angC;
  78717. };
  78718. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78719. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78720. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78721. return BoneIKController;
  78722. }());
  78723. BABYLON.BoneIKController = BoneIKController;
  78724. })(BABYLON || (BABYLON = {}));
  78725. //# sourceMappingURL=babylon.boneIKController.js.map
  78726. var BABYLON;
  78727. (function (BABYLON) {
  78728. /**
  78729. * Class used to make a bone look toward a point in space
  78730. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78731. */
  78732. var BoneLookController = /** @class */ (function () {
  78733. /**
  78734. * Create a BoneLookController
  78735. * @param mesh the mesh that the bone belongs to
  78736. * @param bone the bone that will be looking to the target
  78737. * @param target the target Vector3 to look at
  78738. * @param settings optional settings:
  78739. * * maxYaw: the maximum angle the bone will yaw to
  78740. * * minYaw: the minimum angle the bone will yaw to
  78741. * * maxPitch: the maximum angle the bone will pitch to
  78742. * * minPitch: the minimum angle the bone will yaw to
  78743. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78744. * * upAxis: the up axis of the coordinate system
  78745. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78746. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78747. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78748. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78749. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78750. * * adjustRoll: used to make an adjustment to the roll of the bone
  78751. **/
  78752. function BoneLookController(mesh, bone, target, options) {
  78753. /**
  78754. * The up axis of the coordinate system that is used when the bone is rotated
  78755. */
  78756. this.upAxis = BABYLON.Vector3.Up();
  78757. /**
  78758. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78759. */
  78760. this.upAxisSpace = BABYLON.Space.LOCAL;
  78761. /**
  78762. * Used to make an adjustment to the yaw of the bone
  78763. */
  78764. this.adjustYaw = 0;
  78765. /**
  78766. * Used to make an adjustment to the pitch of the bone
  78767. */
  78768. this.adjustPitch = 0;
  78769. /**
  78770. * Used to make an adjustment to the roll of the bone
  78771. */
  78772. this.adjustRoll = 0;
  78773. /**
  78774. * 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)
  78775. */
  78776. this.slerpAmount = 1;
  78777. this._boneQuat = BABYLON.Quaternion.Identity();
  78778. this._slerping = false;
  78779. this._firstFrameSkipped = false;
  78780. this._fowardAxis = BABYLON.Vector3.Forward();
  78781. this.mesh = mesh;
  78782. this.bone = bone;
  78783. this.target = target;
  78784. if (options) {
  78785. if (options.adjustYaw) {
  78786. this.adjustYaw = options.adjustYaw;
  78787. }
  78788. if (options.adjustPitch) {
  78789. this.adjustPitch = options.adjustPitch;
  78790. }
  78791. if (options.adjustRoll) {
  78792. this.adjustRoll = options.adjustRoll;
  78793. }
  78794. if (options.maxYaw != null) {
  78795. this.maxYaw = options.maxYaw;
  78796. }
  78797. else {
  78798. this.maxYaw = Math.PI;
  78799. }
  78800. if (options.minYaw != null) {
  78801. this.minYaw = options.minYaw;
  78802. }
  78803. else {
  78804. this.minYaw = -Math.PI;
  78805. }
  78806. if (options.maxPitch != null) {
  78807. this.maxPitch = options.maxPitch;
  78808. }
  78809. else {
  78810. this.maxPitch = Math.PI;
  78811. }
  78812. if (options.minPitch != null) {
  78813. this.minPitch = options.minPitch;
  78814. }
  78815. else {
  78816. this.minPitch = -Math.PI;
  78817. }
  78818. if (options.slerpAmount != null) {
  78819. this.slerpAmount = options.slerpAmount;
  78820. }
  78821. if (options.upAxis != null) {
  78822. this.upAxis = options.upAxis;
  78823. }
  78824. if (options.upAxisSpace != null) {
  78825. this.upAxisSpace = options.upAxisSpace;
  78826. }
  78827. if (options.yawAxis != null || options.pitchAxis != null) {
  78828. var newYawAxis = BABYLON.Axis.Y;
  78829. var newPitchAxis = BABYLON.Axis.X;
  78830. if (options.yawAxis != null) {
  78831. newYawAxis = options.yawAxis.clone();
  78832. newYawAxis.normalize();
  78833. }
  78834. if (options.pitchAxis != null) {
  78835. newPitchAxis = options.pitchAxis.clone();
  78836. newPitchAxis.normalize();
  78837. }
  78838. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78839. this._transformYawPitch = BABYLON.Matrix.Identity();
  78840. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78841. this._transformYawPitchInv = this._transformYawPitch.clone();
  78842. this._transformYawPitch.invert();
  78843. }
  78844. }
  78845. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78846. this.upAxisSpace = BABYLON.Space.LOCAL;
  78847. }
  78848. }
  78849. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78850. /**
  78851. * Gets or sets the minimum yaw angle that the bone can look to
  78852. */
  78853. get: function () {
  78854. return this._minYaw;
  78855. },
  78856. set: function (value) {
  78857. this._minYaw = value;
  78858. this._minYawSin = Math.sin(value);
  78859. this._minYawCos = Math.cos(value);
  78860. if (this._maxYaw != null) {
  78861. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78862. this._yawRange = this._maxYaw - this._minYaw;
  78863. }
  78864. },
  78865. enumerable: true,
  78866. configurable: true
  78867. });
  78868. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78869. /**
  78870. * Gets or sets the maximum yaw angle that the bone can look to
  78871. */
  78872. get: function () {
  78873. return this._maxYaw;
  78874. },
  78875. set: function (value) {
  78876. this._maxYaw = value;
  78877. this._maxYawSin = Math.sin(value);
  78878. this._maxYawCos = Math.cos(value);
  78879. if (this._minYaw != null) {
  78880. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78881. this._yawRange = this._maxYaw - this._minYaw;
  78882. }
  78883. },
  78884. enumerable: true,
  78885. configurable: true
  78886. });
  78887. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78888. /**
  78889. * Gets or sets the minimum pitch angle that the bone can look to
  78890. */
  78891. get: function () {
  78892. return this._minPitch;
  78893. },
  78894. set: function (value) {
  78895. this._minPitch = value;
  78896. this._minPitchTan = Math.tan(value);
  78897. },
  78898. enumerable: true,
  78899. configurable: true
  78900. });
  78901. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78902. /**
  78903. * Gets or sets the maximum pitch angle that the bone can look to
  78904. */
  78905. get: function () {
  78906. return this._maxPitch;
  78907. },
  78908. set: function (value) {
  78909. this._maxPitch = value;
  78910. this._maxPitchTan = Math.tan(value);
  78911. },
  78912. enumerable: true,
  78913. configurable: true
  78914. });
  78915. /**
  78916. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78917. */
  78918. BoneLookController.prototype.update = function () {
  78919. //skip the first frame when slerping so that the mesh rotation is correct
  78920. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78921. this._firstFrameSkipped = true;
  78922. return;
  78923. }
  78924. var bone = this.bone;
  78925. var bonePos = BoneLookController._tmpVecs[0];
  78926. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78927. var target = this.target;
  78928. var _tmpMat1 = BoneLookController._tmpMats[0];
  78929. var _tmpMat2 = BoneLookController._tmpMats[1];
  78930. var mesh = this.mesh;
  78931. var parentBone = bone.getParent();
  78932. var upAxis = BoneLookController._tmpVecs[1];
  78933. upAxis.copyFrom(this.upAxis);
  78934. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78935. if (this._transformYawPitch) {
  78936. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78937. }
  78938. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78939. }
  78940. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78941. mesh.getDirectionToRef(upAxis, upAxis);
  78942. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78943. upAxis.normalize();
  78944. }
  78945. }
  78946. var checkYaw = false;
  78947. var checkPitch = false;
  78948. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78949. checkYaw = true;
  78950. }
  78951. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78952. checkPitch = true;
  78953. }
  78954. if (checkYaw || checkPitch) {
  78955. var spaceMat = BoneLookController._tmpMats[2];
  78956. var spaceMatInv = BoneLookController._tmpMats[3];
  78957. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78958. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78959. }
  78960. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78961. spaceMat.copyFrom(mesh.getWorldMatrix());
  78962. }
  78963. else {
  78964. var forwardAxis = BoneLookController._tmpVecs[2];
  78965. forwardAxis.copyFrom(this._fowardAxis);
  78966. if (this._transformYawPitch) {
  78967. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78968. }
  78969. if (parentBone) {
  78970. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78971. }
  78972. else {
  78973. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78974. }
  78975. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78976. rightAxis.normalize();
  78977. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78978. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78979. }
  78980. spaceMat.invertToRef(spaceMatInv);
  78981. var xzlen = null;
  78982. if (checkPitch) {
  78983. var localTarget = BoneLookController._tmpVecs[3];
  78984. target.subtractToRef(bonePos, localTarget);
  78985. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78986. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78987. var pitch = Math.atan2(localTarget.y, xzlen);
  78988. var newPitch = pitch;
  78989. if (pitch > this._maxPitch) {
  78990. localTarget.y = this._maxPitchTan * xzlen;
  78991. newPitch = this._maxPitch;
  78992. }
  78993. else if (pitch < this._minPitch) {
  78994. localTarget.y = this._minPitchTan * xzlen;
  78995. newPitch = this._minPitch;
  78996. }
  78997. if (pitch != newPitch) {
  78998. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78999. localTarget.addInPlace(bonePos);
  79000. target = localTarget;
  79001. }
  79002. }
  79003. if (checkYaw) {
  79004. var localTarget = BoneLookController._tmpVecs[4];
  79005. target.subtractToRef(bonePos, localTarget);
  79006. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79007. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79008. var newYaw = yaw;
  79009. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79010. if (xzlen == null) {
  79011. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79012. }
  79013. if (this._yawRange > Math.PI) {
  79014. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79015. localTarget.z = this._maxYawCos * xzlen;
  79016. localTarget.x = this._maxYawSin * xzlen;
  79017. newYaw = this._maxYaw;
  79018. }
  79019. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79020. localTarget.z = this._minYawCos * xzlen;
  79021. localTarget.x = this._minYawSin * xzlen;
  79022. newYaw = this._minYaw;
  79023. }
  79024. }
  79025. else {
  79026. if (yaw > this._maxYaw) {
  79027. localTarget.z = this._maxYawCos * xzlen;
  79028. localTarget.x = this._maxYawSin * xzlen;
  79029. newYaw = this._maxYaw;
  79030. }
  79031. else if (yaw < this._minYaw) {
  79032. localTarget.z = this._minYawCos * xzlen;
  79033. localTarget.x = this._minYawSin * xzlen;
  79034. newYaw = this._minYaw;
  79035. }
  79036. }
  79037. }
  79038. if (this._slerping && this._yawRange > Math.PI) {
  79039. //are we going to be crossing into the min/max region?
  79040. var boneFwd = BoneLookController._tmpVecs[8];
  79041. boneFwd.copyFrom(BABYLON.Axis.Z);
  79042. if (this._transformYawPitch) {
  79043. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79044. }
  79045. var boneRotMat = BoneLookController._tmpMats[4];
  79046. this._boneQuat.toRotationMatrix(boneRotMat);
  79047. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79048. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79049. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79050. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79051. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79052. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79053. if (angBtwTar > angBtwMidYaw) {
  79054. if (xzlen == null) {
  79055. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79056. }
  79057. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79058. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79059. if (angBtwMin < angBtwMax) {
  79060. newYaw = boneYaw + Math.PI * .75;
  79061. localTarget.z = Math.cos(newYaw) * xzlen;
  79062. localTarget.x = Math.sin(newYaw) * xzlen;
  79063. }
  79064. else {
  79065. newYaw = boneYaw - Math.PI * .75;
  79066. localTarget.z = Math.cos(newYaw) * xzlen;
  79067. localTarget.x = Math.sin(newYaw) * xzlen;
  79068. }
  79069. }
  79070. }
  79071. if (yaw != newYaw) {
  79072. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79073. localTarget.addInPlace(bonePos);
  79074. target = localTarget;
  79075. }
  79076. }
  79077. }
  79078. var zaxis = BoneLookController._tmpVecs[5];
  79079. var xaxis = BoneLookController._tmpVecs[6];
  79080. var yaxis = BoneLookController._tmpVecs[7];
  79081. var _tmpQuat = BoneLookController._tmpQuat;
  79082. target.subtractToRef(bonePos, zaxis);
  79083. zaxis.normalize();
  79084. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79085. xaxis.normalize();
  79086. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79087. yaxis.normalize();
  79088. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79089. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79090. return;
  79091. }
  79092. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79093. return;
  79094. }
  79095. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79096. return;
  79097. }
  79098. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79099. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79100. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79101. }
  79102. if (this.slerpAmount < 1) {
  79103. if (!this._slerping) {
  79104. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79105. }
  79106. if (this._transformYawPitch) {
  79107. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79108. }
  79109. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79110. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79111. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79112. this._slerping = true;
  79113. }
  79114. else {
  79115. if (this._transformYawPitch) {
  79116. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79117. }
  79118. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79119. this._slerping = false;
  79120. }
  79121. };
  79122. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79123. var angDiff = ang2 - ang1;
  79124. angDiff %= Math.PI * 2;
  79125. if (angDiff > Math.PI) {
  79126. angDiff -= Math.PI * 2;
  79127. }
  79128. else if (angDiff < -Math.PI) {
  79129. angDiff += Math.PI * 2;
  79130. }
  79131. return angDiff;
  79132. };
  79133. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79134. ang1 %= (2 * Math.PI);
  79135. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79136. ang2 %= (2 * Math.PI);
  79137. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79138. var ab = 0;
  79139. if (ang1 < ang2) {
  79140. ab = ang2 - ang1;
  79141. }
  79142. else {
  79143. ab = ang1 - ang2;
  79144. }
  79145. if (ab > Math.PI) {
  79146. ab = Math.PI * 2 - ab;
  79147. }
  79148. return ab;
  79149. };
  79150. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79151. ang %= (2 * Math.PI);
  79152. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79153. ang1 %= (2 * Math.PI);
  79154. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79155. ang2 %= (2 * Math.PI);
  79156. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79157. if (ang1 < ang2) {
  79158. if (ang > ang1 && ang < ang2) {
  79159. return true;
  79160. }
  79161. }
  79162. else {
  79163. if (ang > ang2 && ang < ang1) {
  79164. return true;
  79165. }
  79166. }
  79167. return false;
  79168. };
  79169. 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()];
  79170. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79171. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79172. return BoneLookController;
  79173. }());
  79174. BABYLON.BoneLookController = BoneLookController;
  79175. })(BABYLON || (BABYLON = {}));
  79176. //# sourceMappingURL=babylon.boneLookController.js.map
  79177. var BABYLON;
  79178. (function (BABYLON) {
  79179. /**
  79180. * Class used to handle skinning animations
  79181. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79182. */
  79183. var Skeleton = /** @class */ (function () {
  79184. /**
  79185. * Creates a new skeleton
  79186. * @param name defines the skeleton name
  79187. * @param id defines the skeleton Id
  79188. * @param scene defines the hosting scene
  79189. */
  79190. function Skeleton(
  79191. /** defines the skeleton name */
  79192. name,
  79193. /** defines the skeleton Id */
  79194. id, scene) {
  79195. this.name = name;
  79196. this.id = id;
  79197. /**
  79198. * Gets the list of child bones
  79199. */
  79200. this.bones = new Array();
  79201. /**
  79202. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79203. */
  79204. this.needInitialSkinMatrix = false;
  79205. this._isDirty = true;
  79206. this._meshesWithPoseMatrix = new Array();
  79207. this._identity = BABYLON.Matrix.Identity();
  79208. this._ranges = {};
  79209. this._lastAbsoluteTransformsUpdateId = -1;
  79210. /**
  79211. * Specifies if the skeleton should be serialized
  79212. */
  79213. this.doNotSerialize = false;
  79214. this._animationPropertiesOverride = null;
  79215. // Events
  79216. /**
  79217. * An observable triggered before computing the skeleton's matrices
  79218. */
  79219. this.onBeforeComputeObservable = new BABYLON.Observable();
  79220. this.bones = [];
  79221. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79222. scene.skeletons.push(this);
  79223. //make sure it will recalculate the matrix next time prepare is called.
  79224. this._isDirty = true;
  79225. }
  79226. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79227. /**
  79228. * Gets or sets the animation properties override
  79229. */
  79230. get: function () {
  79231. if (!this._animationPropertiesOverride) {
  79232. return this._scene.animationPropertiesOverride;
  79233. }
  79234. return this._animationPropertiesOverride;
  79235. },
  79236. set: function (value) {
  79237. this._animationPropertiesOverride = value;
  79238. },
  79239. enumerable: true,
  79240. configurable: true
  79241. });
  79242. // Members
  79243. /**
  79244. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79245. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79246. * @returns a Float32Array containing matrices data
  79247. */
  79248. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79249. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79250. return mesh._bonesTransformMatrices;
  79251. }
  79252. if (!this._transformMatrices) {
  79253. this.prepare();
  79254. }
  79255. return this._transformMatrices;
  79256. };
  79257. /**
  79258. * Gets the current hosting scene
  79259. * @returns a scene object
  79260. */
  79261. Skeleton.prototype.getScene = function () {
  79262. return this._scene;
  79263. };
  79264. // Methods
  79265. /**
  79266. * Gets a string representing the current skeleton data
  79267. * @param fullDetails defines a boolean indicating if we want a verbose version
  79268. * @returns a string representing the current skeleton data
  79269. */
  79270. Skeleton.prototype.toString = function (fullDetails) {
  79271. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79272. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79273. if (fullDetails) {
  79274. ret += ", Ranges: {";
  79275. var first = true;
  79276. for (var name_1 in this._ranges) {
  79277. if (first) {
  79278. ret += ", ";
  79279. first = false;
  79280. }
  79281. ret += name_1;
  79282. }
  79283. ret += "}";
  79284. }
  79285. return ret;
  79286. };
  79287. /**
  79288. * Get bone's index searching by name
  79289. * @param name defines bone's name to search for
  79290. * @return the indice of the bone. Returns -1 if not found
  79291. */
  79292. Skeleton.prototype.getBoneIndexByName = function (name) {
  79293. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79294. if (this.bones[boneIndex].name === name) {
  79295. return boneIndex;
  79296. }
  79297. }
  79298. return -1;
  79299. };
  79300. /**
  79301. * Creater a new animation range
  79302. * @param name defines the name of the range
  79303. * @param from defines the start key
  79304. * @param to defines the end key
  79305. */
  79306. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79307. // check name not already in use
  79308. if (!this._ranges[name]) {
  79309. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79310. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79311. if (this.bones[i].animations[0]) {
  79312. this.bones[i].animations[0].createRange(name, from, to);
  79313. }
  79314. }
  79315. }
  79316. };
  79317. /**
  79318. * Delete a specific animation range
  79319. * @param name defines the name of the range
  79320. * @param deleteFrames defines if frames must be removed as well
  79321. */
  79322. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79323. if (deleteFrames === void 0) { deleteFrames = true; }
  79324. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79325. if (this.bones[i].animations[0]) {
  79326. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79327. }
  79328. }
  79329. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79330. };
  79331. /**
  79332. * Gets a specific animation range
  79333. * @param name defines the name of the range to look for
  79334. * @returns the requested animation range or null if not found
  79335. */
  79336. Skeleton.prototype.getAnimationRange = function (name) {
  79337. return this._ranges[name];
  79338. };
  79339. /**
  79340. * Gets the list of all animation ranges defined on this skeleton
  79341. * @returns an array
  79342. */
  79343. Skeleton.prototype.getAnimationRanges = function () {
  79344. var animationRanges = [];
  79345. var name;
  79346. var i = 0;
  79347. for (name in this._ranges) {
  79348. animationRanges[i] = this._ranges[name];
  79349. i++;
  79350. }
  79351. return animationRanges;
  79352. };
  79353. /**
  79354. * Copy animation range from a source skeleton.
  79355. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79356. * @param source defines the source skeleton
  79357. * @param name defines the name of the range to copy
  79358. * @param rescaleAsRequired defines if rescaling must be applied if required
  79359. * @returns true if operation was successful
  79360. */
  79361. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79362. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79363. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79364. return false;
  79365. }
  79366. var ret = true;
  79367. var frameOffset = this._getHighestAnimationFrame() + 1;
  79368. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79369. var boneDict = {};
  79370. var sourceBones = source.bones;
  79371. var nBones;
  79372. var i;
  79373. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79374. boneDict[sourceBones[i].name] = sourceBones[i];
  79375. }
  79376. if (this.bones.length !== sourceBones.length) {
  79377. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79378. ret = false;
  79379. }
  79380. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79381. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79382. var boneName = this.bones[i].name;
  79383. var sourceBone = boneDict[boneName];
  79384. if (sourceBone) {
  79385. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79386. }
  79387. else {
  79388. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79389. ret = false;
  79390. }
  79391. }
  79392. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79393. var range = source.getAnimationRange(name);
  79394. if (range) {
  79395. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79396. }
  79397. return ret;
  79398. };
  79399. /**
  79400. * Forces the skeleton to go to rest pose
  79401. */
  79402. Skeleton.prototype.returnToRest = function () {
  79403. for (var index = 0; index < this.bones.length; index++) {
  79404. this.bones[index].returnToRest();
  79405. }
  79406. };
  79407. Skeleton.prototype._getHighestAnimationFrame = function () {
  79408. var ret = 0;
  79409. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79410. if (this.bones[i].animations[0]) {
  79411. var highest = this.bones[i].animations[0].getHighestFrame();
  79412. if (ret < highest) {
  79413. ret = highest;
  79414. }
  79415. }
  79416. }
  79417. return ret;
  79418. };
  79419. /**
  79420. * Begin a specific animation range
  79421. * @param name defines the name of the range to start
  79422. * @param loop defines if looping must be turned on (false by default)
  79423. * @param speedRatio defines the speed ratio to apply (1 by default)
  79424. * @param onAnimationEnd defines a callback which will be called when animation will end
  79425. * @returns a new animatable
  79426. */
  79427. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79428. var range = this.getAnimationRange(name);
  79429. if (!range) {
  79430. return null;
  79431. }
  79432. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79433. };
  79434. /** @hidden */
  79435. Skeleton.prototype._markAsDirty = function () {
  79436. this._isDirty = true;
  79437. };
  79438. /** @hidden */
  79439. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79440. this._meshesWithPoseMatrix.push(mesh);
  79441. };
  79442. /** @hidden */
  79443. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79444. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79445. if (index > -1) {
  79446. this._meshesWithPoseMatrix.splice(index, 1);
  79447. }
  79448. };
  79449. /** @hidden */
  79450. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79451. this.onBeforeComputeObservable.notifyObservers(this);
  79452. for (var index = 0; index < this.bones.length; index++) {
  79453. var bone = this.bones[index];
  79454. var parentBone = bone.getParent();
  79455. if (parentBone) {
  79456. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79457. }
  79458. else {
  79459. if (initialSkinMatrix) {
  79460. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79461. }
  79462. else {
  79463. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79464. }
  79465. }
  79466. if (bone._index !== -1) {
  79467. var mappedIndex = bone._index === null ? index : bone._index;
  79468. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79469. }
  79470. }
  79471. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79472. };
  79473. /**
  79474. * Build all resources required to render a skeleton
  79475. */
  79476. Skeleton.prototype.prepare = function () {
  79477. if (!this._isDirty) {
  79478. return;
  79479. }
  79480. if (this.needInitialSkinMatrix) {
  79481. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79482. var mesh = this._meshesWithPoseMatrix[index];
  79483. var poseMatrix = mesh.getPoseMatrix();
  79484. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79485. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79486. }
  79487. if (this._synchronizedWithMesh !== mesh) {
  79488. this._synchronizedWithMesh = mesh;
  79489. // Prepare bones
  79490. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79491. var bone = this.bones[boneIndex];
  79492. if (!bone.getParent()) {
  79493. var matrix = bone.getBaseMatrix();
  79494. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79495. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79496. }
  79497. }
  79498. }
  79499. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79500. }
  79501. }
  79502. else {
  79503. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79504. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79505. }
  79506. this._computeTransformMatrices(this._transformMatrices, null);
  79507. }
  79508. this._isDirty = false;
  79509. this._scene._activeBones.addCount(this.bones.length, false);
  79510. };
  79511. /**
  79512. * Gets the list of animatables currently running for this skeleton
  79513. * @returns an array of animatables
  79514. */
  79515. Skeleton.prototype.getAnimatables = function () {
  79516. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79517. this._animatables = [];
  79518. for (var index = 0; index < this.bones.length; index++) {
  79519. this._animatables.push(this.bones[index]);
  79520. }
  79521. }
  79522. return this._animatables;
  79523. };
  79524. /**
  79525. * Clone the current skeleton
  79526. * @param name defines the name of the new skeleton
  79527. * @param id defines the id of the enw skeleton
  79528. * @returns the new skeleton
  79529. */
  79530. Skeleton.prototype.clone = function (name, id) {
  79531. var result = new Skeleton(name, id || name, this._scene);
  79532. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79533. for (var index = 0; index < this.bones.length; index++) {
  79534. var source = this.bones[index];
  79535. var parentBone = null;
  79536. var parent_1 = source.getParent();
  79537. if (parent_1) {
  79538. var parentIndex = this.bones.indexOf(parent_1);
  79539. parentBone = result.bones[parentIndex];
  79540. }
  79541. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79542. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79543. }
  79544. if (this._ranges) {
  79545. result._ranges = {};
  79546. for (var rangeName in this._ranges) {
  79547. var range = this._ranges[rangeName];
  79548. if (range) {
  79549. result._ranges[rangeName] = range.clone();
  79550. }
  79551. }
  79552. }
  79553. this._isDirty = true;
  79554. return result;
  79555. };
  79556. /**
  79557. * Enable animation blending for this skeleton
  79558. * @param blendingSpeed defines the blending speed to apply
  79559. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79560. */
  79561. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79562. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79563. this.bones.forEach(function (bone) {
  79564. bone.animations.forEach(function (animation) {
  79565. animation.enableBlending = true;
  79566. animation.blendingSpeed = blendingSpeed;
  79567. });
  79568. });
  79569. };
  79570. /**
  79571. * Releases all resources associated with the current skeleton
  79572. */
  79573. Skeleton.prototype.dispose = function () {
  79574. this._meshesWithPoseMatrix = [];
  79575. // Animations
  79576. this.getScene().stopAnimation(this);
  79577. // Remove from scene
  79578. this.getScene().removeSkeleton(this);
  79579. };
  79580. /**
  79581. * Serialize the skeleton in a JSON object
  79582. * @returns a JSON object
  79583. */
  79584. Skeleton.prototype.serialize = function () {
  79585. var serializationObject = {};
  79586. serializationObject.name = this.name;
  79587. serializationObject.id = this.id;
  79588. if (this.dimensionsAtRest) {
  79589. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79590. }
  79591. serializationObject.bones = [];
  79592. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79593. for (var index = 0; index < this.bones.length; index++) {
  79594. var bone = this.bones[index];
  79595. var parent_2 = bone.getParent();
  79596. var serializedBone = {
  79597. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79598. name: bone.name,
  79599. matrix: bone.getBaseMatrix().toArray(),
  79600. rest: bone.getRestPose().toArray()
  79601. };
  79602. serializationObject.bones.push(serializedBone);
  79603. if (bone.length) {
  79604. serializedBone.length = bone.length;
  79605. }
  79606. if (bone.metadata) {
  79607. serializedBone.metadata = bone.metadata;
  79608. }
  79609. if (bone.animations && bone.animations.length > 0) {
  79610. serializedBone.animation = bone.animations[0].serialize();
  79611. }
  79612. serializationObject.ranges = [];
  79613. for (var name in this._ranges) {
  79614. var source = this._ranges[name];
  79615. if (!source) {
  79616. continue;
  79617. }
  79618. var range = {};
  79619. range.name = name;
  79620. range.from = source.from;
  79621. range.to = source.to;
  79622. serializationObject.ranges.push(range);
  79623. }
  79624. }
  79625. return serializationObject;
  79626. };
  79627. /**
  79628. * Creates a new skeleton from serialized data
  79629. * @param parsedSkeleton defines the serialized data
  79630. * @param scene defines the hosting scene
  79631. * @returns a new skeleton
  79632. */
  79633. Skeleton.Parse = function (parsedSkeleton, scene) {
  79634. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79635. if (parsedSkeleton.dimensionsAtRest) {
  79636. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79637. }
  79638. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79639. var index;
  79640. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79641. var parsedBone = parsedSkeleton.bones[index];
  79642. var parentBone = null;
  79643. if (parsedBone.parentBoneIndex > -1) {
  79644. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79645. }
  79646. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79647. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79648. if (parsedBone.length) {
  79649. bone.length = parsedBone.length;
  79650. }
  79651. if (parsedBone.metadata) {
  79652. bone.metadata = parsedBone.metadata;
  79653. }
  79654. if (parsedBone.animation) {
  79655. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79656. }
  79657. }
  79658. // placed after bones, so createAnimationRange can cascade down
  79659. if (parsedSkeleton.ranges) {
  79660. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79661. var data = parsedSkeleton.ranges[index];
  79662. skeleton.createAnimationRange(data.name, data.from, data.to);
  79663. }
  79664. }
  79665. return skeleton;
  79666. };
  79667. /**
  79668. * Compute all node absolute transforms
  79669. * @param forceUpdate defines if computation must be done even if cache is up to date
  79670. */
  79671. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79672. if (forceUpdate === void 0) { forceUpdate = false; }
  79673. var renderId = this._scene.getRenderId();
  79674. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79675. this.bones[0].computeAbsoluteTransforms();
  79676. this._lastAbsoluteTransformsUpdateId = renderId;
  79677. }
  79678. };
  79679. /**
  79680. * Gets the root pose matrix
  79681. * @returns a matrix
  79682. */
  79683. Skeleton.prototype.getPoseMatrix = function () {
  79684. var poseMatrix = null;
  79685. if (this._meshesWithPoseMatrix.length > 0) {
  79686. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79687. }
  79688. return poseMatrix;
  79689. };
  79690. /**
  79691. * Sorts bones per internal index
  79692. */
  79693. Skeleton.prototype.sortBones = function () {
  79694. var bones = new Array();
  79695. var visited = new Array(this.bones.length);
  79696. for (var index = 0; index < this.bones.length; index++) {
  79697. this._sortBones(index, bones, visited);
  79698. }
  79699. this.bones = bones;
  79700. };
  79701. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79702. if (visited[index]) {
  79703. return;
  79704. }
  79705. visited[index] = true;
  79706. var bone = this.bones[index];
  79707. if (bone._index === undefined) {
  79708. bone._index = index;
  79709. }
  79710. var parentBone = bone.getParent();
  79711. if (parentBone) {
  79712. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79713. }
  79714. bones.push(bone);
  79715. };
  79716. return Skeleton;
  79717. }());
  79718. BABYLON.Skeleton = Skeleton;
  79719. })(BABYLON || (BABYLON = {}));
  79720. //# sourceMappingURL=babylon.skeleton.js.map
  79721. var BABYLON;
  79722. (function (BABYLON) {
  79723. var SphericalPolynomial = /** @class */ (function () {
  79724. function SphericalPolynomial() {
  79725. this.x = BABYLON.Vector3.Zero();
  79726. this.y = BABYLON.Vector3.Zero();
  79727. this.z = BABYLON.Vector3.Zero();
  79728. this.xx = BABYLON.Vector3.Zero();
  79729. this.yy = BABYLON.Vector3.Zero();
  79730. this.zz = BABYLON.Vector3.Zero();
  79731. this.xy = BABYLON.Vector3.Zero();
  79732. this.yz = BABYLON.Vector3.Zero();
  79733. this.zx = BABYLON.Vector3.Zero();
  79734. }
  79735. SphericalPolynomial.prototype.addAmbient = function (color) {
  79736. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79737. this.xx = this.xx.add(colorVector);
  79738. this.yy = this.yy.add(colorVector);
  79739. this.zz = this.zz.add(colorVector);
  79740. };
  79741. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79742. var result = new SphericalPolynomial();
  79743. result.x = harmonics.L11.scale(1.02333);
  79744. result.y = harmonics.L1_1.scale(1.02333);
  79745. result.z = harmonics.L10.scale(1.02333);
  79746. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79747. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79748. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79749. result.yz = harmonics.L2_1.scale(0.858086);
  79750. result.zx = harmonics.L21.scale(0.858086);
  79751. result.xy = harmonics.L2_2.scale(0.858086);
  79752. result.scale(1.0 / Math.PI);
  79753. return result;
  79754. };
  79755. SphericalPolynomial.prototype.scale = function (scale) {
  79756. this.x = this.x.scale(scale);
  79757. this.y = this.y.scale(scale);
  79758. this.z = this.z.scale(scale);
  79759. this.xx = this.xx.scale(scale);
  79760. this.yy = this.yy.scale(scale);
  79761. this.zz = this.zz.scale(scale);
  79762. this.yz = this.yz.scale(scale);
  79763. this.zx = this.zx.scale(scale);
  79764. this.xy = this.xy.scale(scale);
  79765. };
  79766. return SphericalPolynomial;
  79767. }());
  79768. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79769. var SphericalHarmonics = /** @class */ (function () {
  79770. function SphericalHarmonics() {
  79771. this.L00 = BABYLON.Vector3.Zero();
  79772. this.L1_1 = BABYLON.Vector3.Zero();
  79773. this.L10 = BABYLON.Vector3.Zero();
  79774. this.L11 = BABYLON.Vector3.Zero();
  79775. this.L2_2 = BABYLON.Vector3.Zero();
  79776. this.L2_1 = BABYLON.Vector3.Zero();
  79777. this.L20 = BABYLON.Vector3.Zero();
  79778. this.L21 = BABYLON.Vector3.Zero();
  79779. this.L22 = BABYLON.Vector3.Zero();
  79780. }
  79781. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79782. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79783. var c = colorVector.scale(deltaSolidAngle);
  79784. this.L00 = this.L00.add(c.scale(0.282095));
  79785. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79786. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79787. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79788. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79789. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79790. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79791. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79792. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79793. };
  79794. SphericalHarmonics.prototype.scale = function (scale) {
  79795. this.L00 = this.L00.scale(scale);
  79796. this.L1_1 = this.L1_1.scale(scale);
  79797. this.L10 = this.L10.scale(scale);
  79798. this.L11 = this.L11.scale(scale);
  79799. this.L2_2 = this.L2_2.scale(scale);
  79800. this.L2_1 = this.L2_1.scale(scale);
  79801. this.L20 = this.L20.scale(scale);
  79802. this.L21 = this.L21.scale(scale);
  79803. this.L22 = this.L22.scale(scale);
  79804. };
  79805. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79806. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79807. //
  79808. // E_lm = A_l * L_lm
  79809. //
  79810. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79811. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79812. // the scaling factors are given in equation 9.
  79813. // Constant (Band 0)
  79814. this.L00 = this.L00.scale(3.141593);
  79815. // Linear (Band 1)
  79816. this.L1_1 = this.L1_1.scale(2.094395);
  79817. this.L10 = this.L10.scale(2.094395);
  79818. this.L11 = this.L11.scale(2.094395);
  79819. // Quadratic (Band 2)
  79820. this.L2_2 = this.L2_2.scale(0.785398);
  79821. this.L2_1 = this.L2_1.scale(0.785398);
  79822. this.L20 = this.L20.scale(0.785398);
  79823. this.L21 = this.L21.scale(0.785398);
  79824. this.L22 = this.L22.scale(0.785398);
  79825. };
  79826. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79827. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79828. // L = (1/pi) * E * rho
  79829. //
  79830. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79831. this.scale(1.0 / Math.PI);
  79832. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79833. // (The pixel shader must apply albedo after texture fetches, etc).
  79834. };
  79835. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79836. var result = new SphericalHarmonics();
  79837. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79838. result.L1_1 = polynomial.y.scale(0.977204);
  79839. result.L10 = polynomial.z.scale(0.977204);
  79840. result.L11 = polynomial.x.scale(0.977204);
  79841. result.L2_2 = polynomial.xy.scale(1.16538);
  79842. result.L2_1 = polynomial.yz.scale(1.16538);
  79843. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79844. result.L21 = polynomial.zx.scale(1.16538);
  79845. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79846. result.scale(Math.PI);
  79847. return result;
  79848. };
  79849. return SphericalHarmonics;
  79850. }());
  79851. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79852. })(BABYLON || (BABYLON = {}));
  79853. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79854. var BABYLON;
  79855. (function (BABYLON) {
  79856. var FileFaceOrientation = /** @class */ (function () {
  79857. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79858. this.name = name;
  79859. this.worldAxisForNormal = worldAxisForNormal;
  79860. this.worldAxisForFileX = worldAxisForFileX;
  79861. this.worldAxisForFileY = worldAxisForFileY;
  79862. }
  79863. return FileFaceOrientation;
  79864. }());
  79865. ;
  79866. /**
  79867. * Helper class dealing with the extraction of spherical polynomial dataArray
  79868. * from a cube map.
  79869. */
  79870. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79871. function CubeMapToSphericalPolynomialTools() {
  79872. }
  79873. /**
  79874. * Converts a texture to the according Spherical Polynomial data.
  79875. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79876. *
  79877. * @param texture The texture to extract the information from.
  79878. * @return The Spherical Polynomial data.
  79879. */
  79880. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79881. if (!texture.isCube) {
  79882. // Only supports cube Textures currently.
  79883. return null;
  79884. }
  79885. var size = texture.getSize().width;
  79886. var right = texture.readPixels(0);
  79887. var left = texture.readPixels(1);
  79888. var up;
  79889. var down;
  79890. if (texture.isRenderTarget) {
  79891. up = texture.readPixels(3);
  79892. down = texture.readPixels(2);
  79893. }
  79894. else {
  79895. up = texture.readPixels(2);
  79896. down = texture.readPixels(3);
  79897. }
  79898. var front = texture.readPixels(4);
  79899. var back = texture.readPixels(5);
  79900. var gammaSpace = texture.gammaSpace;
  79901. // Always read as RGBA.
  79902. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79903. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79904. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79905. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79906. }
  79907. var cubeInfo = {
  79908. size: size,
  79909. right: right,
  79910. left: left,
  79911. up: up,
  79912. down: down,
  79913. front: front,
  79914. back: back,
  79915. format: format,
  79916. type: type,
  79917. gammaSpace: gammaSpace,
  79918. };
  79919. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79920. };
  79921. /**
  79922. * Converts a cubemap to the according Spherical Polynomial data.
  79923. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79924. *
  79925. * @param cubeInfo The Cube map to extract the information from.
  79926. * @return The Spherical Polynomial data.
  79927. */
  79928. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79929. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79930. var totalSolidAngle = 0.0;
  79931. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79932. var du = 2.0 / cubeInfo.size;
  79933. var dv = du;
  79934. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79935. var minUV = du * 0.5 - 1.0;
  79936. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79937. var fileFace = this.FileFaces[faceIndex];
  79938. var dataArray = cubeInfo[fileFace.name];
  79939. var v = minUV;
  79940. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79941. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79942. // Because SP is still linear, so summation is fine in that basis.
  79943. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79944. for (var y = 0; y < cubeInfo.size; y++) {
  79945. var u = minUV;
  79946. for (var x = 0; x < cubeInfo.size; x++) {
  79947. // World direction (not normalised)
  79948. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79949. worldDirection.normalize();
  79950. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79951. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79952. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79953. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79954. // Handle Integer types.
  79955. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79956. r /= 255;
  79957. g /= 255;
  79958. b /= 255;
  79959. }
  79960. // Handle Gamma space textures.
  79961. if (cubeInfo.gammaSpace) {
  79962. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79963. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79964. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79965. }
  79966. var color = new BABYLON.Color3(r, g, b);
  79967. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79968. totalSolidAngle += deltaSolidAngle;
  79969. u += du;
  79970. }
  79971. v += dv;
  79972. }
  79973. }
  79974. // Solid angle for entire sphere is 4*pi
  79975. var sphereSolidAngle = 4.0 * Math.PI;
  79976. // Adjust the solid angle to allow for how many faces we processed.
  79977. var facesProcessed = 6.0;
  79978. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79979. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79980. // This is needed because the numerical integration over the cube uses a
  79981. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79982. // and also to compensate for accumulative error due to float precision in the summation.
  79983. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79984. sphericalHarmonics.scale(correctionFactor);
  79985. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79986. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79987. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79988. };
  79989. CubeMapToSphericalPolynomialTools.FileFaces = [
  79990. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79991. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79992. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79993. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79994. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79995. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79996. ];
  79997. return CubeMapToSphericalPolynomialTools;
  79998. }());
  79999. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80000. })(BABYLON || (BABYLON = {}));
  80001. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80002. var BABYLON;
  80003. (function (BABYLON) {
  80004. /**
  80005. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80006. */
  80007. var PanoramaToCubeMapTools = /** @class */ (function () {
  80008. function PanoramaToCubeMapTools() {
  80009. }
  80010. /**
  80011. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80012. *
  80013. * @param float32Array The source data.
  80014. * @param inputWidth The width of the input panorama.
  80015. * @param inputhHeight The height of the input panorama.
  80016. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80017. * @return The cubemap data
  80018. */
  80019. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80020. if (!float32Array) {
  80021. throw "ConvertPanoramaToCubemap: input cannot be null";
  80022. }
  80023. if (float32Array.length != inputWidth * inputHeight * 3) {
  80024. throw "ConvertPanoramaToCubemap: input size is wrong";
  80025. }
  80026. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80027. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80028. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80029. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80030. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80031. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80032. return {
  80033. front: textureFront,
  80034. back: textureBack,
  80035. left: textureLeft,
  80036. right: textureRight,
  80037. up: textureUp,
  80038. down: textureDown,
  80039. size: size,
  80040. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80041. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80042. gammaSpace: false,
  80043. };
  80044. };
  80045. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80046. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80047. var textureArray = new Float32Array(buffer);
  80048. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80049. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80050. var dy = 1 / texSize;
  80051. var fy = 0;
  80052. for (var y = 0; y < texSize; y++) {
  80053. var xv1 = faceData[0];
  80054. var xv2 = faceData[2];
  80055. for (var x = 0; x < texSize; x++) {
  80056. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80057. v.normalize();
  80058. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80059. // 3 channels per pixels
  80060. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80061. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80062. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80063. xv1 = xv1.add(rotDX1);
  80064. xv2 = xv2.add(rotDX2);
  80065. }
  80066. fy += dy;
  80067. }
  80068. return textureArray;
  80069. };
  80070. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80071. var theta = Math.atan2(vDir.z, vDir.x);
  80072. var phi = Math.acos(vDir.y);
  80073. while (theta < -Math.PI)
  80074. theta += 2 * Math.PI;
  80075. while (theta > Math.PI)
  80076. theta -= 2 * Math.PI;
  80077. var dx = theta / Math.PI;
  80078. var dy = phi / Math.PI;
  80079. // recenter.
  80080. dx = dx * 0.5 + 0.5;
  80081. var px = Math.round(dx * inputWidth);
  80082. if (px < 0)
  80083. px = 0;
  80084. else if (px >= inputWidth)
  80085. px = inputWidth - 1;
  80086. var py = Math.round(dy * inputHeight);
  80087. if (py < 0)
  80088. py = 0;
  80089. else if (py >= inputHeight)
  80090. py = inputHeight - 1;
  80091. var inputY = (inputHeight - py - 1);
  80092. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80093. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80094. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80095. return {
  80096. r: r,
  80097. g: g,
  80098. b: b
  80099. };
  80100. };
  80101. PanoramaToCubeMapTools.FACE_FRONT = [
  80102. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80103. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80104. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80105. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80106. ];
  80107. PanoramaToCubeMapTools.FACE_BACK = [
  80108. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80109. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80110. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80111. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80112. ];
  80113. PanoramaToCubeMapTools.FACE_RIGHT = [
  80114. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80115. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80116. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80117. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80118. ];
  80119. PanoramaToCubeMapTools.FACE_LEFT = [
  80120. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80121. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80122. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80123. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80124. ];
  80125. PanoramaToCubeMapTools.FACE_DOWN = [
  80126. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80127. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80128. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80129. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80130. ];
  80131. PanoramaToCubeMapTools.FACE_UP = [
  80132. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80133. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80134. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80135. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80136. ];
  80137. return PanoramaToCubeMapTools;
  80138. }());
  80139. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80140. })(BABYLON || (BABYLON = {}));
  80141. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80142. var BABYLON;
  80143. (function (BABYLON) {
  80144. ;
  80145. /**
  80146. * This groups tools to convert HDR texture to native colors array.
  80147. */
  80148. var HDRTools = /** @class */ (function () {
  80149. function HDRTools() {
  80150. }
  80151. HDRTools.Ldexp = function (mantissa, exponent) {
  80152. if (exponent > 1023) {
  80153. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80154. }
  80155. if (exponent < -1074) {
  80156. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80157. }
  80158. return mantissa * Math.pow(2, exponent);
  80159. };
  80160. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80161. if (exponent > 0) { /*nonzero pixel*/
  80162. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80163. float32array[index + 0] = red * exponent;
  80164. float32array[index + 1] = green * exponent;
  80165. float32array[index + 2] = blue * exponent;
  80166. }
  80167. else {
  80168. float32array[index + 0] = 0;
  80169. float32array[index + 1] = 0;
  80170. float32array[index + 2] = 0;
  80171. }
  80172. };
  80173. HDRTools.readStringLine = function (uint8array, startIndex) {
  80174. var line = "";
  80175. var character = "";
  80176. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80177. character = String.fromCharCode(uint8array[i]);
  80178. if (character == "\n") {
  80179. break;
  80180. }
  80181. line += character;
  80182. }
  80183. return line;
  80184. };
  80185. /**
  80186. * Reads header information from an RGBE texture stored in a native array.
  80187. * More information on this format are available here:
  80188. * https://en.wikipedia.org/wiki/RGBE_image_format
  80189. *
  80190. * @param uint8array The binary file stored in native array.
  80191. * @return The header information.
  80192. */
  80193. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80194. var height = 0;
  80195. var width = 0;
  80196. var line = this.readStringLine(uint8array, 0);
  80197. if (line[0] != '#' || line[1] != '?') {
  80198. throw "Bad HDR Format.";
  80199. }
  80200. var endOfHeader = false;
  80201. var findFormat = false;
  80202. var lineIndex = 0;
  80203. do {
  80204. lineIndex += (line.length + 1);
  80205. line = this.readStringLine(uint8array, lineIndex);
  80206. if (line == "FORMAT=32-bit_rle_rgbe") {
  80207. findFormat = true;
  80208. }
  80209. else if (line.length == 0) {
  80210. endOfHeader = true;
  80211. }
  80212. } while (!endOfHeader);
  80213. if (!findFormat) {
  80214. throw "HDR Bad header format, unsupported FORMAT";
  80215. }
  80216. lineIndex += (line.length + 1);
  80217. line = this.readStringLine(uint8array, lineIndex);
  80218. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80219. var match = sizeRegexp.exec(line);
  80220. // TODO. Support +Y and -X if needed.
  80221. if (!match || match.length < 3) {
  80222. throw "HDR Bad header format, no size";
  80223. }
  80224. width = parseInt(match[2]);
  80225. height = parseInt(match[1]);
  80226. if (width < 8 || width > 0x7fff) {
  80227. throw "HDR Bad header format, unsupported size";
  80228. }
  80229. lineIndex += (line.length + 1);
  80230. return {
  80231. height: height,
  80232. width: width,
  80233. dataPosition: lineIndex
  80234. };
  80235. };
  80236. /**
  80237. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80238. * This RGBE texture needs to store the information as a panorama.
  80239. *
  80240. * More information on this format are available here:
  80241. * https://en.wikipedia.org/wiki/RGBE_image_format
  80242. *
  80243. * @param buffer The binary file stored in an array buffer.
  80244. * @param size The expected size of the extracted cubemap.
  80245. * @return The Cube Map information.
  80246. */
  80247. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80248. var uint8array = new Uint8Array(buffer);
  80249. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80250. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80251. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80252. return cubeMapData;
  80253. };
  80254. /**
  80255. * Returns the pixels data extracted from an RGBE texture.
  80256. * This pixels will be stored left to right up to down in the R G B order in one array.
  80257. *
  80258. * More information on this format are available here:
  80259. * https://en.wikipedia.org/wiki/RGBE_image_format
  80260. *
  80261. * @param uint8array The binary file stored in an array buffer.
  80262. * @param hdrInfo The header information of the file.
  80263. * @return The pixels data in RGB right to left up to down order.
  80264. */
  80265. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80266. // Keep for multi format supports.
  80267. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80268. };
  80269. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80270. var num_scanlines = hdrInfo.height;
  80271. var scanline_width = hdrInfo.width;
  80272. var a, b, c, d, count;
  80273. var dataIndex = hdrInfo.dataPosition;
  80274. var index = 0, endIndex = 0, i = 0;
  80275. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80276. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80277. // 3 channels of 4 bytes per pixel in float.
  80278. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80279. var resultArray = new Float32Array(resultBuffer);
  80280. // read in each successive scanline
  80281. while (num_scanlines > 0) {
  80282. a = uint8array[dataIndex++];
  80283. b = uint8array[dataIndex++];
  80284. c = uint8array[dataIndex++];
  80285. d = uint8array[dataIndex++];
  80286. if (a != 2 || b != 2 || (c & 0x80)) {
  80287. // this file is not run length encoded
  80288. throw "HDR Bad header format, not RLE";
  80289. }
  80290. if (((c << 8) | d) != scanline_width) {
  80291. throw "HDR Bad header format, wrong scan line width";
  80292. }
  80293. index = 0;
  80294. // read each of the four channels for the scanline into the buffer
  80295. for (i = 0; i < 4; i++) {
  80296. endIndex = (i + 1) * scanline_width;
  80297. while (index < endIndex) {
  80298. a = uint8array[dataIndex++];
  80299. b = uint8array[dataIndex++];
  80300. if (a > 128) {
  80301. // a run of the same value
  80302. count = a - 128;
  80303. if ((count == 0) || (count > endIndex - index)) {
  80304. throw "HDR Bad Format, bad scanline data (run)";
  80305. }
  80306. while (count-- > 0) {
  80307. scanLineArray[index++] = b;
  80308. }
  80309. }
  80310. else {
  80311. // a non-run
  80312. count = a;
  80313. if ((count == 0) || (count > endIndex - index)) {
  80314. throw "HDR Bad Format, bad scanline data (non-run)";
  80315. }
  80316. scanLineArray[index++] = b;
  80317. if (--count > 0) {
  80318. for (var j = 0; j < count; j++) {
  80319. scanLineArray[index++] = uint8array[dataIndex++];
  80320. }
  80321. }
  80322. }
  80323. }
  80324. }
  80325. // now convert data from buffer into floats
  80326. for (i = 0; i < scanline_width; i++) {
  80327. a = scanLineArray[i];
  80328. b = scanLineArray[i + scanline_width];
  80329. c = scanLineArray[i + 2 * scanline_width];
  80330. d = scanLineArray[i + 3 * scanline_width];
  80331. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80332. }
  80333. num_scanlines--;
  80334. }
  80335. return resultArray;
  80336. };
  80337. return HDRTools;
  80338. }());
  80339. BABYLON.HDRTools = HDRTools;
  80340. })(BABYLON || (BABYLON = {}));
  80341. //# sourceMappingURL=babylon.hdr.js.map
  80342. var BABYLON;
  80343. (function (BABYLON) {
  80344. /**
  80345. * This represents a texture coming from an HDR input.
  80346. *
  80347. * The only supported format is currently panorama picture stored in RGBE format.
  80348. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80349. */
  80350. var HDRCubeTexture = /** @class */ (function (_super) {
  80351. __extends(HDRCubeTexture, _super);
  80352. /**
  80353. * Instantiates an HDRTexture from the following parameters.
  80354. *
  80355. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80356. * @param scene The scene the texture will be used in
  80357. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80358. * @param noMipmap Forces to not generate the mipmap if true
  80359. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80360. * @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)
  80361. * @param reserved Reserved flag for internal use.
  80362. */
  80363. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80364. if (noMipmap === void 0) { noMipmap = false; }
  80365. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80366. if (gammaSpace === void 0) { gammaSpace = false; }
  80367. if (reserved === void 0) { reserved = false; }
  80368. if (onLoad === void 0) { onLoad = null; }
  80369. if (onError === void 0) { onError = null; }
  80370. var _this = _super.call(this, scene) || this;
  80371. _this._generateHarmonics = true;
  80372. _this._onLoad = null;
  80373. _this._onError = null;
  80374. /**
  80375. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80376. */
  80377. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80378. _this._isBlocking = true;
  80379. _this._rotationY = 0;
  80380. /**
  80381. * Gets or sets the center of the bounding box associated with the cube texture
  80382. * It must define where the camera used to render the texture was set
  80383. */
  80384. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80385. if (!url) {
  80386. return _this;
  80387. }
  80388. _this.name = url;
  80389. _this.url = url;
  80390. _this.hasAlpha = false;
  80391. _this.isCube = true;
  80392. _this._textureMatrix = BABYLON.Matrix.Identity();
  80393. _this._onLoad = onLoad;
  80394. _this._onError = onError;
  80395. _this.gammaSpace = gammaSpace;
  80396. _this._noMipmap = noMipmap;
  80397. _this._size = size;
  80398. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80399. if (!_this._texture) {
  80400. if (!scene.useDelayedTextureLoading) {
  80401. _this.loadTexture();
  80402. }
  80403. else {
  80404. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80405. }
  80406. }
  80407. return _this;
  80408. }
  80409. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80410. /**
  80411. * Gets wether or not the texture is blocking during loading.
  80412. */
  80413. get: function () {
  80414. return this._isBlocking;
  80415. },
  80416. /**
  80417. * Sets wether or not the texture is blocking during loading.
  80418. */
  80419. set: function (value) {
  80420. this._isBlocking = value;
  80421. },
  80422. enumerable: true,
  80423. configurable: true
  80424. });
  80425. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80426. /**
  80427. * Gets texture matrix rotation angle around Y axis radians.
  80428. */
  80429. get: function () {
  80430. return this._rotationY;
  80431. },
  80432. /**
  80433. * Sets texture matrix rotation angle around Y axis in radians.
  80434. */
  80435. set: function (value) {
  80436. this._rotationY = value;
  80437. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80438. },
  80439. enumerable: true,
  80440. configurable: true
  80441. });
  80442. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80443. get: function () {
  80444. return this._boundingBoxSize;
  80445. },
  80446. /**
  80447. * Gets or sets the size of the bounding box associated with the cube texture
  80448. * When defined, the cubemap will switch to local mode
  80449. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80450. * @example https://www.babylonjs-playground.com/#RNASML
  80451. */
  80452. set: function (value) {
  80453. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80454. return;
  80455. }
  80456. this._boundingBoxSize = value;
  80457. var scene = this.getScene();
  80458. if (scene) {
  80459. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80460. }
  80461. },
  80462. enumerable: true,
  80463. configurable: true
  80464. });
  80465. /**
  80466. * Occurs when the file is raw .hdr file.
  80467. */
  80468. HDRCubeTexture.prototype.loadTexture = function () {
  80469. var _this = this;
  80470. var callback = function (buffer) {
  80471. var scene = _this.getScene();
  80472. if (!scene) {
  80473. return null;
  80474. }
  80475. // Extract the raw linear data.
  80476. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80477. // Generate harmonics if needed.
  80478. if (_this._generateHarmonics) {
  80479. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80480. _this.sphericalPolynomial = sphericalPolynomial;
  80481. }
  80482. var results = [];
  80483. var byteArray = null;
  80484. // Push each faces.
  80485. for (var j = 0; j < 6; j++) {
  80486. // Create uintarray fallback.
  80487. if (!scene.getEngine().getCaps().textureFloat) {
  80488. // 3 channels of 1 bytes per pixel in bytes.
  80489. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80490. byteArray = new Uint8Array(byteBuffer);
  80491. }
  80492. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80493. // If special cases.
  80494. if (_this.gammaSpace || byteArray) {
  80495. for (var i = 0; i < _this._size * _this._size; i++) {
  80496. // Put in gamma space if requested.
  80497. if (_this.gammaSpace) {
  80498. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80499. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80500. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80501. }
  80502. // Convert to int texture for fallback.
  80503. if (byteArray) {
  80504. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80505. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80506. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80507. // May use luminance instead if the result is not accurate.
  80508. var max = Math.max(Math.max(r, g), b);
  80509. if (max > 255) {
  80510. var scale = 255 / max;
  80511. r *= scale;
  80512. g *= scale;
  80513. b *= scale;
  80514. }
  80515. byteArray[(i * 3) + 0] = r;
  80516. byteArray[(i * 3) + 1] = g;
  80517. byteArray[(i * 3) + 2] = b;
  80518. }
  80519. }
  80520. }
  80521. if (byteArray) {
  80522. results.push(byteArray);
  80523. }
  80524. else {
  80525. results.push(dataFace);
  80526. }
  80527. }
  80528. return results;
  80529. };
  80530. var scene = this.getScene();
  80531. if (scene) {
  80532. 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);
  80533. }
  80534. };
  80535. HDRCubeTexture.prototype.clone = function () {
  80536. var scene = this.getScene();
  80537. if (!scene) {
  80538. return this;
  80539. }
  80540. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80541. // Base texture
  80542. newTexture.level = this.level;
  80543. newTexture.wrapU = this.wrapU;
  80544. newTexture.wrapV = this.wrapV;
  80545. newTexture.coordinatesIndex = this.coordinatesIndex;
  80546. newTexture.coordinatesMode = this.coordinatesMode;
  80547. return newTexture;
  80548. };
  80549. // Methods
  80550. HDRCubeTexture.prototype.delayLoad = function () {
  80551. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80552. return;
  80553. }
  80554. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80555. this._texture = this._getFromCache(this.url, this._noMipmap);
  80556. if (!this._texture) {
  80557. this.loadTexture();
  80558. }
  80559. };
  80560. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80561. return this._textureMatrix;
  80562. };
  80563. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80564. this._textureMatrix = value;
  80565. };
  80566. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80567. var texture = null;
  80568. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80569. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80570. texture.name = parsedTexture.name;
  80571. texture.hasAlpha = parsedTexture.hasAlpha;
  80572. texture.level = parsedTexture.level;
  80573. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80574. texture.isBlocking = parsedTexture.isBlocking;
  80575. }
  80576. if (texture) {
  80577. if (parsedTexture.boundingBoxPosition) {
  80578. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80579. }
  80580. if (parsedTexture.boundingBoxSize) {
  80581. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80582. }
  80583. if (parsedTexture.rotationY) {
  80584. texture.rotationY = parsedTexture.rotationY;
  80585. }
  80586. }
  80587. return texture;
  80588. };
  80589. HDRCubeTexture.prototype.serialize = function () {
  80590. if (!this.name) {
  80591. return null;
  80592. }
  80593. var serializationObject = {};
  80594. serializationObject.name = this.name;
  80595. serializationObject.hasAlpha = this.hasAlpha;
  80596. serializationObject.isCube = true;
  80597. serializationObject.level = this.level;
  80598. serializationObject.size = this._size;
  80599. serializationObject.coordinatesMode = this.coordinatesMode;
  80600. serializationObject.useInGammaSpace = this.gammaSpace;
  80601. serializationObject.generateHarmonics = this._generateHarmonics;
  80602. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80603. serializationObject.noMipmap = this._noMipmap;
  80604. serializationObject.isBlocking = this._isBlocking;
  80605. serializationObject.rotationY = this._rotationY;
  80606. return serializationObject;
  80607. };
  80608. HDRCubeTexture._facesMapping = [
  80609. "right",
  80610. "left",
  80611. "up",
  80612. "down",
  80613. "front",
  80614. "back"
  80615. ];
  80616. return HDRCubeTexture;
  80617. }(BABYLON.BaseTexture));
  80618. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80619. })(BABYLON || (BABYLON = {}));
  80620. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80621. var BABYLON;
  80622. (function (BABYLON) {
  80623. var IndexedVector2 = /** @class */ (function (_super) {
  80624. __extends(IndexedVector2, _super);
  80625. function IndexedVector2(original, index) {
  80626. var _this = _super.call(this, original.x, original.y) || this;
  80627. _this.index = index;
  80628. return _this;
  80629. }
  80630. return IndexedVector2;
  80631. }(BABYLON.Vector2));
  80632. var PolygonPoints = /** @class */ (function () {
  80633. function PolygonPoints() {
  80634. this.elements = new Array();
  80635. }
  80636. PolygonPoints.prototype.add = function (originalPoints) {
  80637. var _this = this;
  80638. var result = new Array();
  80639. originalPoints.forEach(function (point) {
  80640. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80641. var newPoint = new IndexedVector2(point, _this.elements.length);
  80642. result.push(newPoint);
  80643. _this.elements.push(newPoint);
  80644. }
  80645. });
  80646. return result;
  80647. };
  80648. PolygonPoints.prototype.computeBounds = function () {
  80649. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80650. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80651. this.elements.forEach(function (point) {
  80652. // x
  80653. if (point.x < lmin.x) {
  80654. lmin.x = point.x;
  80655. }
  80656. else if (point.x > lmax.x) {
  80657. lmax.x = point.x;
  80658. }
  80659. // y
  80660. if (point.y < lmin.y) {
  80661. lmin.y = point.y;
  80662. }
  80663. else if (point.y > lmax.y) {
  80664. lmax.y = point.y;
  80665. }
  80666. });
  80667. return {
  80668. min: lmin,
  80669. max: lmax,
  80670. width: lmax.x - lmin.x,
  80671. height: lmax.y - lmin.y
  80672. };
  80673. };
  80674. return PolygonPoints;
  80675. }());
  80676. var Polygon = /** @class */ (function () {
  80677. function Polygon() {
  80678. }
  80679. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80680. return [
  80681. new BABYLON.Vector2(xmin, ymin),
  80682. new BABYLON.Vector2(xmax, ymin),
  80683. new BABYLON.Vector2(xmax, ymax),
  80684. new BABYLON.Vector2(xmin, ymax)
  80685. ];
  80686. };
  80687. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80688. if (cx === void 0) { cx = 0; }
  80689. if (cy === void 0) { cy = 0; }
  80690. if (numberOfSides === void 0) { numberOfSides = 32; }
  80691. var result = new Array();
  80692. var angle = 0;
  80693. var increment = (Math.PI * 2) / numberOfSides;
  80694. for (var i = 0; i < numberOfSides; i++) {
  80695. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80696. angle -= increment;
  80697. }
  80698. return result;
  80699. };
  80700. Polygon.Parse = function (input) {
  80701. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80702. var i, result = [];
  80703. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80704. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80705. }
  80706. return result;
  80707. };
  80708. Polygon.StartingAt = function (x, y) {
  80709. return BABYLON.Path2.StartingAt(x, y);
  80710. };
  80711. return Polygon;
  80712. }());
  80713. BABYLON.Polygon = Polygon;
  80714. var PolygonMeshBuilder = /** @class */ (function () {
  80715. function PolygonMeshBuilder(name, contours, scene) {
  80716. this._points = new PolygonPoints();
  80717. this._outlinepoints = new PolygonPoints();
  80718. this._holes = new Array();
  80719. this._epoints = new Array();
  80720. this._eholes = new Array();
  80721. this._name = name;
  80722. this._scene = scene;
  80723. var points;
  80724. if (contours instanceof BABYLON.Path2) {
  80725. points = contours.getPoints();
  80726. }
  80727. else {
  80728. points = contours;
  80729. }
  80730. this._addToepoint(points);
  80731. this._points.add(points);
  80732. this._outlinepoints.add(points);
  80733. if (typeof earcut === 'undefined') {
  80734. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80735. }
  80736. }
  80737. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80738. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80739. var p = points_1[_i];
  80740. this._epoints.push(p.x, p.y);
  80741. }
  80742. };
  80743. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80744. this._points.add(hole);
  80745. var holepoints = new PolygonPoints();
  80746. holepoints.add(hole);
  80747. this._holes.push(holepoints);
  80748. this._eholes.push(this._epoints.length / 2);
  80749. this._addToepoint(hole);
  80750. return this;
  80751. };
  80752. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80753. var _this = this;
  80754. if (updatable === void 0) { updatable = false; }
  80755. if (depth === void 0) { depth = 0; }
  80756. var result = new BABYLON.Mesh(this._name, this._scene);
  80757. var normals = new Array();
  80758. var positions = new Array();
  80759. var uvs = new Array();
  80760. var bounds = this._points.computeBounds();
  80761. this._points.elements.forEach(function (p) {
  80762. normals.push(0, 1.0, 0);
  80763. positions.push(p.x, 0, p.y);
  80764. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80765. });
  80766. var indices = new Array();
  80767. var res = earcut(this._epoints, this._eholes, 2);
  80768. for (var i = 0; i < res.length; i++) {
  80769. indices.push(res[i]);
  80770. }
  80771. if (depth > 0) {
  80772. var positionscount = (positions.length / 3); //get the current pointcount
  80773. this._points.elements.forEach(function (p) {
  80774. normals.push(0, -1.0, 0);
  80775. positions.push(p.x, -depth, p.y);
  80776. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80777. });
  80778. var totalCount = indices.length;
  80779. for (var i = 0; i < totalCount; i += 3) {
  80780. var i0 = indices[i + 0];
  80781. var i1 = indices[i + 1];
  80782. var i2 = indices[i + 2];
  80783. indices.push(i2 + positionscount);
  80784. indices.push(i1 + positionscount);
  80785. indices.push(i0 + positionscount);
  80786. }
  80787. //Add the sides
  80788. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80789. this._holes.forEach(function (hole) {
  80790. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80791. });
  80792. }
  80793. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80794. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80795. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80796. result.setIndices(indices);
  80797. return result;
  80798. };
  80799. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80800. var StartIndex = positions.length / 3;
  80801. var ulength = 0;
  80802. for (var i = 0; i < points.elements.length; i++) {
  80803. var p = points.elements[i];
  80804. var p1;
  80805. if ((i + 1) > points.elements.length - 1) {
  80806. p1 = points.elements[0];
  80807. }
  80808. else {
  80809. p1 = points.elements[i + 1];
  80810. }
  80811. positions.push(p.x, 0, p.y);
  80812. positions.push(p.x, -depth, p.y);
  80813. positions.push(p1.x, 0, p1.y);
  80814. positions.push(p1.x, -depth, p1.y);
  80815. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80816. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80817. var v3 = v2.subtract(v1);
  80818. var v4 = new BABYLON.Vector3(0, 1, 0);
  80819. var vn = BABYLON.Vector3.Cross(v3, v4);
  80820. vn = vn.normalize();
  80821. uvs.push(ulength / bounds.width, 0);
  80822. uvs.push(ulength / bounds.width, 1);
  80823. ulength += v3.length();
  80824. uvs.push((ulength / bounds.width), 0);
  80825. uvs.push((ulength / bounds.width), 1);
  80826. if (!flip) {
  80827. normals.push(-vn.x, -vn.y, -vn.z);
  80828. normals.push(-vn.x, -vn.y, -vn.z);
  80829. normals.push(-vn.x, -vn.y, -vn.z);
  80830. normals.push(-vn.x, -vn.y, -vn.z);
  80831. indices.push(StartIndex);
  80832. indices.push(StartIndex + 1);
  80833. indices.push(StartIndex + 2);
  80834. indices.push(StartIndex + 1);
  80835. indices.push(StartIndex + 3);
  80836. indices.push(StartIndex + 2);
  80837. }
  80838. else {
  80839. normals.push(vn.x, vn.y, vn.z);
  80840. normals.push(vn.x, vn.y, vn.z);
  80841. normals.push(vn.x, vn.y, vn.z);
  80842. normals.push(vn.x, vn.y, vn.z);
  80843. indices.push(StartIndex);
  80844. indices.push(StartIndex + 2);
  80845. indices.push(StartIndex + 1);
  80846. indices.push(StartIndex + 1);
  80847. indices.push(StartIndex + 2);
  80848. indices.push(StartIndex + 3);
  80849. }
  80850. StartIndex += 4;
  80851. }
  80852. ;
  80853. };
  80854. return PolygonMeshBuilder;
  80855. }());
  80856. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80857. })(BABYLON || (BABYLON = {}));
  80858. //# sourceMappingURL=babylon.polygonMesh.js.map
  80859. var BABYLON;
  80860. (function (BABYLON) {
  80861. // Unique ID when we import meshes from Babylon to CSG
  80862. var currentCSGMeshId = 0;
  80863. // # class Vertex
  80864. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80865. // one to provide additional features like texture coordinates and vertex
  80866. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80867. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80868. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80869. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80870. // is not used anywhere else.
  80871. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80872. var Vertex = /** @class */ (function () {
  80873. function Vertex(pos, normal, uv) {
  80874. this.pos = pos;
  80875. this.normal = normal;
  80876. this.uv = uv;
  80877. }
  80878. Vertex.prototype.clone = function () {
  80879. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80880. };
  80881. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80882. // orientation of a polygon is flipped.
  80883. Vertex.prototype.flip = function () {
  80884. this.normal = this.normal.scale(-1);
  80885. };
  80886. // Create a new vertex between this vertex and `other` by linearly
  80887. // interpolating all properties using a parameter of `t`. Subclasses should
  80888. // override this to interpolate additional properties.
  80889. Vertex.prototype.interpolate = function (other, t) {
  80890. 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));
  80891. };
  80892. return Vertex;
  80893. }());
  80894. // # class Plane
  80895. // Represents a plane in 3D space.
  80896. var Plane = /** @class */ (function () {
  80897. function Plane(normal, w) {
  80898. this.normal = normal;
  80899. this.w = w;
  80900. }
  80901. Plane.FromPoints = function (a, b, c) {
  80902. var v0 = c.subtract(a);
  80903. var v1 = b.subtract(a);
  80904. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80905. return null;
  80906. }
  80907. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80908. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80909. };
  80910. Plane.prototype.clone = function () {
  80911. return new Plane(this.normal.clone(), this.w);
  80912. };
  80913. Plane.prototype.flip = function () {
  80914. this.normal.scaleInPlace(-1);
  80915. this.w = -this.w;
  80916. };
  80917. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80918. // fragments in the appropriate lists. Coplanar polygons go into either
  80919. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80920. // respect to this plane. Polygons in front or in back of this plane go into
  80921. // either `front` or `back`.
  80922. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80923. var COPLANAR = 0;
  80924. var FRONT = 1;
  80925. var BACK = 2;
  80926. var SPANNING = 3;
  80927. // Classify each point as well as the entire polygon into one of the above
  80928. // four classes.
  80929. var polygonType = 0;
  80930. var types = [];
  80931. var i;
  80932. var t;
  80933. for (i = 0; i < polygon.vertices.length; i++) {
  80934. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80935. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80936. polygonType |= type;
  80937. types.push(type);
  80938. }
  80939. // Put the polygon in the correct list, splitting it when necessary.
  80940. switch (polygonType) {
  80941. case COPLANAR:
  80942. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80943. break;
  80944. case FRONT:
  80945. front.push(polygon);
  80946. break;
  80947. case BACK:
  80948. back.push(polygon);
  80949. break;
  80950. case SPANNING:
  80951. var f = [], b = [];
  80952. for (i = 0; i < polygon.vertices.length; i++) {
  80953. var j = (i + 1) % polygon.vertices.length;
  80954. var ti = types[i], tj = types[j];
  80955. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80956. if (ti !== BACK)
  80957. f.push(vi);
  80958. if (ti !== FRONT)
  80959. b.push(ti !== BACK ? vi.clone() : vi);
  80960. if ((ti | tj) === SPANNING) {
  80961. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80962. var v = vi.interpolate(vj, t);
  80963. f.push(v);
  80964. b.push(v.clone());
  80965. }
  80966. }
  80967. var poly;
  80968. if (f.length >= 3) {
  80969. poly = new Polygon(f, polygon.shared);
  80970. if (poly.plane)
  80971. front.push(poly);
  80972. }
  80973. if (b.length >= 3) {
  80974. poly = new Polygon(b, polygon.shared);
  80975. if (poly.plane)
  80976. back.push(poly);
  80977. }
  80978. break;
  80979. }
  80980. };
  80981. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80982. // point is on the plane.
  80983. Plane.EPSILON = 1e-5;
  80984. return Plane;
  80985. }());
  80986. // # class Polygon
  80987. // Represents a convex polygon. The vertices used to initialize a polygon must
  80988. // be coplanar and form a convex loop.
  80989. //
  80990. // Each convex polygon has a `shared` property, which is shared between all
  80991. // polygons that are clones of each other or were split from the same polygon.
  80992. // This can be used to define per-polygon properties (such as surface color).
  80993. var Polygon = /** @class */ (function () {
  80994. function Polygon(vertices, shared) {
  80995. this.vertices = vertices;
  80996. this.shared = shared;
  80997. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80998. }
  80999. Polygon.prototype.clone = function () {
  81000. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81001. return new Polygon(vertices, this.shared);
  81002. };
  81003. Polygon.prototype.flip = function () {
  81004. this.vertices.reverse().map(function (v) { v.flip(); });
  81005. this.plane.flip();
  81006. };
  81007. return Polygon;
  81008. }());
  81009. // # class Node
  81010. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81011. // by picking a polygon to split along. That polygon (and all other coplanar
  81012. // polygons) are added directly to that node and the other polygons are added to
  81013. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81014. // no distinction between internal and leaf nodes.
  81015. var Node = /** @class */ (function () {
  81016. function Node(polygons) {
  81017. this.plane = null;
  81018. this.front = null;
  81019. this.back = null;
  81020. this.polygons = new Array();
  81021. if (polygons) {
  81022. this.build(polygons);
  81023. }
  81024. }
  81025. Node.prototype.clone = function () {
  81026. var node = new Node();
  81027. node.plane = this.plane && this.plane.clone();
  81028. node.front = this.front && this.front.clone();
  81029. node.back = this.back && this.back.clone();
  81030. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81031. return node;
  81032. };
  81033. // Convert solid space to empty space and empty space to solid space.
  81034. Node.prototype.invert = function () {
  81035. for (var i = 0; i < this.polygons.length; i++) {
  81036. this.polygons[i].flip();
  81037. }
  81038. if (this.plane) {
  81039. this.plane.flip();
  81040. }
  81041. if (this.front) {
  81042. this.front.invert();
  81043. }
  81044. if (this.back) {
  81045. this.back.invert();
  81046. }
  81047. var temp = this.front;
  81048. this.front = this.back;
  81049. this.back = temp;
  81050. };
  81051. // Recursively remove all polygons in `polygons` that are inside this BSP
  81052. // tree.
  81053. Node.prototype.clipPolygons = function (polygons) {
  81054. if (!this.plane)
  81055. return polygons.slice();
  81056. var front = new Array(), back = new Array();
  81057. for (var i = 0; i < polygons.length; i++) {
  81058. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81059. }
  81060. if (this.front) {
  81061. front = this.front.clipPolygons(front);
  81062. }
  81063. if (this.back) {
  81064. back = this.back.clipPolygons(back);
  81065. }
  81066. else {
  81067. back = [];
  81068. }
  81069. return front.concat(back);
  81070. };
  81071. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81072. // `bsp`.
  81073. Node.prototype.clipTo = function (bsp) {
  81074. this.polygons = bsp.clipPolygons(this.polygons);
  81075. if (this.front)
  81076. this.front.clipTo(bsp);
  81077. if (this.back)
  81078. this.back.clipTo(bsp);
  81079. };
  81080. // Return a list of all polygons in this BSP tree.
  81081. Node.prototype.allPolygons = function () {
  81082. var polygons = this.polygons.slice();
  81083. if (this.front)
  81084. polygons = polygons.concat(this.front.allPolygons());
  81085. if (this.back)
  81086. polygons = polygons.concat(this.back.allPolygons());
  81087. return polygons;
  81088. };
  81089. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81090. // new polygons are filtered down to the bottom of the tree and become new
  81091. // nodes there. Each set of polygons is partitioned using the first polygon
  81092. // (no heuristic is used to pick a good split).
  81093. Node.prototype.build = function (polygons) {
  81094. if (!polygons.length)
  81095. return;
  81096. if (!this.plane)
  81097. this.plane = polygons[0].plane.clone();
  81098. var front = new Array(), back = new Array();
  81099. for (var i = 0; i < polygons.length; i++) {
  81100. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81101. }
  81102. if (front.length) {
  81103. if (!this.front)
  81104. this.front = new Node();
  81105. this.front.build(front);
  81106. }
  81107. if (back.length) {
  81108. if (!this.back)
  81109. this.back = new Node();
  81110. this.back.build(back);
  81111. }
  81112. };
  81113. return Node;
  81114. }());
  81115. var CSG = /** @class */ (function () {
  81116. function CSG() {
  81117. this.polygons = new Array();
  81118. }
  81119. // Convert BABYLON.Mesh to BABYLON.CSG
  81120. CSG.FromMesh = function (mesh) {
  81121. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81122. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81123. if (mesh instanceof BABYLON.Mesh) {
  81124. mesh.computeWorldMatrix(true);
  81125. matrix = mesh.getWorldMatrix();
  81126. meshPosition = mesh.position.clone();
  81127. meshRotation = mesh.rotation.clone();
  81128. if (mesh.rotationQuaternion) {
  81129. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81130. }
  81131. meshScaling = mesh.scaling.clone();
  81132. }
  81133. else {
  81134. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81135. }
  81136. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81137. var subMeshes = mesh.subMeshes;
  81138. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81139. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81140. vertices = [];
  81141. for (var j = 0; j < 3; j++) {
  81142. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81143. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81144. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81145. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81146. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81147. vertex = new Vertex(position, normal, uv);
  81148. vertices.push(vertex);
  81149. }
  81150. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81151. // To handle the case of degenerated triangle
  81152. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81153. if (polygon.plane)
  81154. polygons.push(polygon);
  81155. }
  81156. }
  81157. var csg = CSG.FromPolygons(polygons);
  81158. csg.matrix = matrix;
  81159. csg.position = meshPosition;
  81160. csg.rotation = meshRotation;
  81161. csg.scaling = meshScaling;
  81162. csg.rotationQuaternion = meshRotationQuaternion;
  81163. currentCSGMeshId++;
  81164. return csg;
  81165. };
  81166. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81167. CSG.FromPolygons = function (polygons) {
  81168. var csg = new CSG();
  81169. csg.polygons = polygons;
  81170. return csg;
  81171. };
  81172. CSG.prototype.clone = function () {
  81173. var csg = new CSG();
  81174. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81175. csg.copyTransformAttributes(this);
  81176. return csg;
  81177. };
  81178. CSG.prototype.union = function (csg) {
  81179. var a = new Node(this.clone().polygons);
  81180. var b = new Node(csg.clone().polygons);
  81181. a.clipTo(b);
  81182. b.clipTo(a);
  81183. b.invert();
  81184. b.clipTo(a);
  81185. b.invert();
  81186. a.build(b.allPolygons());
  81187. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81188. };
  81189. CSG.prototype.unionInPlace = function (csg) {
  81190. var a = new Node(this.polygons);
  81191. var b = new Node(csg.polygons);
  81192. a.clipTo(b);
  81193. b.clipTo(a);
  81194. b.invert();
  81195. b.clipTo(a);
  81196. b.invert();
  81197. a.build(b.allPolygons());
  81198. this.polygons = a.allPolygons();
  81199. };
  81200. CSG.prototype.subtract = function (csg) {
  81201. var a = new Node(this.clone().polygons);
  81202. var b = new Node(csg.clone().polygons);
  81203. a.invert();
  81204. a.clipTo(b);
  81205. b.clipTo(a);
  81206. b.invert();
  81207. b.clipTo(a);
  81208. b.invert();
  81209. a.build(b.allPolygons());
  81210. a.invert();
  81211. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81212. };
  81213. CSG.prototype.subtractInPlace = function (csg) {
  81214. var a = new Node(this.polygons);
  81215. var b = new Node(csg.polygons);
  81216. a.invert();
  81217. a.clipTo(b);
  81218. b.clipTo(a);
  81219. b.invert();
  81220. b.clipTo(a);
  81221. b.invert();
  81222. a.build(b.allPolygons());
  81223. a.invert();
  81224. this.polygons = a.allPolygons();
  81225. };
  81226. CSG.prototype.intersect = function (csg) {
  81227. var a = new Node(this.clone().polygons);
  81228. var b = new Node(csg.clone().polygons);
  81229. a.invert();
  81230. b.clipTo(a);
  81231. b.invert();
  81232. a.clipTo(b);
  81233. b.clipTo(a);
  81234. a.build(b.allPolygons());
  81235. a.invert();
  81236. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81237. };
  81238. CSG.prototype.intersectInPlace = function (csg) {
  81239. var a = new Node(this.polygons);
  81240. var b = new Node(csg.polygons);
  81241. a.invert();
  81242. b.clipTo(a);
  81243. b.invert();
  81244. a.clipTo(b);
  81245. b.clipTo(a);
  81246. a.build(b.allPolygons());
  81247. a.invert();
  81248. this.polygons = a.allPolygons();
  81249. };
  81250. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81251. // not modified.
  81252. CSG.prototype.inverse = function () {
  81253. var csg = this.clone();
  81254. csg.inverseInPlace();
  81255. return csg;
  81256. };
  81257. CSG.prototype.inverseInPlace = function () {
  81258. this.polygons.map(function (p) { p.flip(); });
  81259. };
  81260. // This is used to keep meshes transformations so they can be restored
  81261. // when we build back a Babylon Mesh
  81262. // NB : All CSG operations are performed in world coordinates
  81263. CSG.prototype.copyTransformAttributes = function (csg) {
  81264. this.matrix = csg.matrix;
  81265. this.position = csg.position;
  81266. this.rotation = csg.rotation;
  81267. this.scaling = csg.scaling;
  81268. this.rotationQuaternion = csg.rotationQuaternion;
  81269. return this;
  81270. };
  81271. // Build Raw mesh from CSG
  81272. // Coordinates here are in world space
  81273. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81274. var matrix = this.matrix.clone();
  81275. matrix.invert();
  81276. 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;
  81277. if (keepSubMeshes) {
  81278. // Sort Polygons, since subMeshes are indices range
  81279. polygons.sort(function (a, b) {
  81280. if (a.shared.meshId === b.shared.meshId) {
  81281. return a.shared.subMeshId - b.shared.subMeshId;
  81282. }
  81283. else {
  81284. return a.shared.meshId - b.shared.meshId;
  81285. }
  81286. });
  81287. }
  81288. for (var i = 0, il = polygons.length; i < il; i++) {
  81289. polygon = polygons[i];
  81290. // Building SubMeshes
  81291. if (!subMesh_dict[polygon.shared.meshId]) {
  81292. subMesh_dict[polygon.shared.meshId] = {};
  81293. }
  81294. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81295. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81296. indexStart: +Infinity,
  81297. indexEnd: -Infinity,
  81298. materialIndex: polygon.shared.materialIndex
  81299. };
  81300. }
  81301. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81302. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81303. polygonIndices[0] = 0;
  81304. polygonIndices[1] = j - 1;
  81305. polygonIndices[2] = j;
  81306. for (var k = 0; k < 3; k++) {
  81307. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81308. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81309. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81310. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81311. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81312. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81313. // Check if 2 points can be merged
  81314. if (!(typeof vertex_idx !== 'undefined' &&
  81315. normals[vertex_idx * 3] === localNormal.x &&
  81316. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81317. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81318. uvs[vertex_idx * 2] === uv.x &&
  81319. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81320. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81321. uvs.push(uv.x, uv.y);
  81322. normals.push(normal.x, normal.y, normal.z);
  81323. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81324. }
  81325. indices.push(vertex_idx);
  81326. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81327. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81328. currentIndex++;
  81329. }
  81330. }
  81331. }
  81332. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81333. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81334. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81335. mesh.setIndices(indices, null);
  81336. if (keepSubMeshes) {
  81337. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81338. var materialIndexOffset = 0, materialMaxIndex;
  81339. mesh.subMeshes = new Array();
  81340. for (var m in subMesh_dict) {
  81341. materialMaxIndex = -1;
  81342. for (var sm in subMesh_dict[m]) {
  81343. subMesh_obj = subMesh_dict[m][sm];
  81344. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81345. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81346. }
  81347. materialIndexOffset += ++materialMaxIndex;
  81348. }
  81349. }
  81350. return mesh;
  81351. };
  81352. // Build Mesh from CSG taking material and transforms into account
  81353. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81354. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81355. mesh.material = material;
  81356. mesh.position.copyFrom(this.position);
  81357. mesh.rotation.copyFrom(this.rotation);
  81358. if (this.rotationQuaternion) {
  81359. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81360. }
  81361. mesh.scaling.copyFrom(this.scaling);
  81362. mesh.computeWorldMatrix(true);
  81363. return mesh;
  81364. };
  81365. return CSG;
  81366. }());
  81367. BABYLON.CSG = CSG;
  81368. })(BABYLON || (BABYLON = {}));
  81369. //# sourceMappingURL=babylon.csg.js.map
  81370. var BABYLON;
  81371. (function (BABYLON) {
  81372. var LensFlare = /** @class */ (function () {
  81373. function LensFlare(size, position, color, imgUrl, system) {
  81374. this.size = size;
  81375. this.position = position;
  81376. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81377. this.color = color || new BABYLON.Color3(1, 1, 1);
  81378. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81379. this._system = system;
  81380. system.lensFlares.push(this);
  81381. }
  81382. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81383. return new LensFlare(size, position, color, imgUrl, system);
  81384. };
  81385. LensFlare.prototype.dispose = function () {
  81386. if (this.texture) {
  81387. this.texture.dispose();
  81388. }
  81389. // Remove from scene
  81390. var index = this._system.lensFlares.indexOf(this);
  81391. this._system.lensFlares.splice(index, 1);
  81392. };
  81393. ;
  81394. return LensFlare;
  81395. }());
  81396. BABYLON.LensFlare = LensFlare;
  81397. })(BABYLON || (BABYLON = {}));
  81398. //# sourceMappingURL=babylon.lensFlare.js.map
  81399. var BABYLON;
  81400. (function (BABYLON) {
  81401. var LensFlareSystem = /** @class */ (function () {
  81402. function LensFlareSystem(name, emitter, scene) {
  81403. this.name = name;
  81404. this.lensFlares = new Array();
  81405. this.borderLimit = 300;
  81406. this.viewportBorder = 0;
  81407. this.layerMask = 0x0FFFFFFF;
  81408. this._vertexBuffers = {};
  81409. this._isEnabled = true;
  81410. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81411. this._emitter = emitter;
  81412. this.id = name;
  81413. scene.lensFlareSystems.push(this);
  81414. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81415. var engine = scene.getEngine();
  81416. // VBO
  81417. var vertices = [];
  81418. vertices.push(1, 1);
  81419. vertices.push(-1, 1);
  81420. vertices.push(-1, -1);
  81421. vertices.push(1, -1);
  81422. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81423. // Indices
  81424. var indices = [];
  81425. indices.push(0);
  81426. indices.push(1);
  81427. indices.push(2);
  81428. indices.push(0);
  81429. indices.push(2);
  81430. indices.push(3);
  81431. this._indexBuffer = engine.createIndexBuffer(indices);
  81432. // Effects
  81433. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81434. }
  81435. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81436. get: function () {
  81437. return this._isEnabled;
  81438. },
  81439. set: function (value) {
  81440. this._isEnabled = value;
  81441. },
  81442. enumerable: true,
  81443. configurable: true
  81444. });
  81445. LensFlareSystem.prototype.getScene = function () {
  81446. return this._scene;
  81447. };
  81448. LensFlareSystem.prototype.getEmitter = function () {
  81449. return this._emitter;
  81450. };
  81451. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81452. this._emitter = newEmitter;
  81453. };
  81454. LensFlareSystem.prototype.getEmitterPosition = function () {
  81455. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81456. };
  81457. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81458. var position = this.getEmitterPosition();
  81459. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81460. this._positionX = position.x;
  81461. this._positionY = position.y;
  81462. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81463. if (this.viewportBorder > 0) {
  81464. globalViewport.x -= this.viewportBorder;
  81465. globalViewport.y -= this.viewportBorder;
  81466. globalViewport.width += this.viewportBorder * 2;
  81467. globalViewport.height += this.viewportBorder * 2;
  81468. position.x += this.viewportBorder;
  81469. position.y += this.viewportBorder;
  81470. this._positionX += this.viewportBorder;
  81471. this._positionY += this.viewportBorder;
  81472. }
  81473. if (position.z > 0) {
  81474. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81475. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81476. return true;
  81477. }
  81478. return true;
  81479. }
  81480. return false;
  81481. };
  81482. LensFlareSystem.prototype._isVisible = function () {
  81483. if (!this._isEnabled || !this._scene.activeCamera) {
  81484. return false;
  81485. }
  81486. var emitterPosition = this.getEmitterPosition();
  81487. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81488. var distance = direction.length();
  81489. direction.normalize();
  81490. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81491. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81492. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81493. };
  81494. LensFlareSystem.prototype.render = function () {
  81495. if (!this._effect.isReady() || !this._scene.activeCamera)
  81496. return false;
  81497. var engine = this._scene.getEngine();
  81498. var viewport = this._scene.activeCamera.viewport;
  81499. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81500. // Position
  81501. if (!this.computeEffectivePosition(globalViewport)) {
  81502. return false;
  81503. }
  81504. // Visibility
  81505. if (!this._isVisible()) {
  81506. return false;
  81507. }
  81508. // Intensity
  81509. var awayX;
  81510. var awayY;
  81511. if (this._positionX < this.borderLimit + globalViewport.x) {
  81512. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81513. }
  81514. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81515. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81516. }
  81517. else {
  81518. awayX = 0;
  81519. }
  81520. if (this._positionY < this.borderLimit + globalViewport.y) {
  81521. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81522. }
  81523. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81524. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81525. }
  81526. else {
  81527. awayY = 0;
  81528. }
  81529. var away = (awayX > awayY) ? awayX : awayY;
  81530. away -= this.viewportBorder;
  81531. if (away > this.borderLimit) {
  81532. away = this.borderLimit;
  81533. }
  81534. var intensity = 1.0 - (away / this.borderLimit);
  81535. if (intensity < 0) {
  81536. return false;
  81537. }
  81538. if (intensity > 1.0) {
  81539. intensity = 1.0;
  81540. }
  81541. if (this.viewportBorder > 0) {
  81542. globalViewport.x += this.viewportBorder;
  81543. globalViewport.y += this.viewportBorder;
  81544. globalViewport.width -= this.viewportBorder * 2;
  81545. globalViewport.height -= this.viewportBorder * 2;
  81546. this._positionX -= this.viewportBorder;
  81547. this._positionY -= this.viewportBorder;
  81548. }
  81549. // Position
  81550. var centerX = globalViewport.x + globalViewport.width / 2;
  81551. var centerY = globalViewport.y + globalViewport.height / 2;
  81552. var distX = centerX - this._positionX;
  81553. var distY = centerY - this._positionY;
  81554. // Effects
  81555. engine.enableEffect(this._effect);
  81556. engine.setState(false);
  81557. engine.setDepthBuffer(false);
  81558. // VBOs
  81559. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81560. // Flares
  81561. for (var index = 0; index < this.lensFlares.length; index++) {
  81562. var flare = this.lensFlares[index];
  81563. engine.setAlphaMode(flare.alphaMode);
  81564. var x = centerX - (distX * flare.position);
  81565. var y = centerY - (distY * flare.position);
  81566. var cw = flare.size;
  81567. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81568. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81569. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81570. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81571. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81572. // Texture
  81573. this._effect.setTexture("textureSampler", flare.texture);
  81574. // Color
  81575. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81576. // Draw order
  81577. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81578. }
  81579. engine.setDepthBuffer(true);
  81580. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81581. return true;
  81582. };
  81583. LensFlareSystem.prototype.dispose = function () {
  81584. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81585. if (vertexBuffer) {
  81586. vertexBuffer.dispose();
  81587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81588. }
  81589. if (this._indexBuffer) {
  81590. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81591. this._indexBuffer = null;
  81592. }
  81593. while (this.lensFlares.length) {
  81594. this.lensFlares[0].dispose();
  81595. }
  81596. // Remove from scene
  81597. var index = this._scene.lensFlareSystems.indexOf(this);
  81598. this._scene.lensFlareSystems.splice(index, 1);
  81599. };
  81600. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81601. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81602. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81603. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81604. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81605. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81606. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81607. var parsedFlare = parsedLensFlareSystem.flares[index];
  81608. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81609. }
  81610. return lensFlareSystem;
  81611. };
  81612. LensFlareSystem.prototype.serialize = function () {
  81613. var serializationObject = {};
  81614. serializationObject.id = this.id;
  81615. serializationObject.name = this.name;
  81616. serializationObject.emitterId = this.getEmitter().id;
  81617. serializationObject.borderLimit = this.borderLimit;
  81618. serializationObject.flares = [];
  81619. for (var index = 0; index < this.lensFlares.length; index++) {
  81620. var flare = this.lensFlares[index];
  81621. serializationObject.flares.push({
  81622. size: flare.size,
  81623. position: flare.position,
  81624. color: flare.color.asArray(),
  81625. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81626. });
  81627. }
  81628. return serializationObject;
  81629. };
  81630. return LensFlareSystem;
  81631. }());
  81632. BABYLON.LensFlareSystem = LensFlareSystem;
  81633. })(BABYLON || (BABYLON = {}));
  81634. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81635. var BABYLON;
  81636. (function (BABYLON) {
  81637. /**
  81638. * This is a holder class for the physics joint created by the physics plugin.
  81639. * It holds a set of functions to control the underlying joint.
  81640. */
  81641. var PhysicsJoint = /** @class */ (function () {
  81642. function PhysicsJoint(type, jointData) {
  81643. this.type = type;
  81644. this.jointData = jointData;
  81645. jointData.nativeParams = jointData.nativeParams || {};
  81646. }
  81647. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81648. get: function () {
  81649. return this._physicsJoint;
  81650. },
  81651. set: function (newJoint) {
  81652. if (this._physicsJoint) {
  81653. //remove from the wolrd
  81654. }
  81655. this._physicsJoint = newJoint;
  81656. },
  81657. enumerable: true,
  81658. configurable: true
  81659. });
  81660. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81661. set: function (physicsPlugin) {
  81662. this._physicsPlugin = physicsPlugin;
  81663. },
  81664. enumerable: true,
  81665. configurable: true
  81666. });
  81667. /**
  81668. * Execute a function that is physics-plugin specific.
  81669. * @param {Function} func the function that will be executed.
  81670. * It accepts two parameters: the physics world and the physics joint.
  81671. */
  81672. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81673. func(this._physicsPlugin.world, this._physicsJoint);
  81674. };
  81675. //TODO check if the native joints are the same
  81676. //Joint Types
  81677. PhysicsJoint.DistanceJoint = 0;
  81678. PhysicsJoint.HingeJoint = 1;
  81679. PhysicsJoint.BallAndSocketJoint = 2;
  81680. PhysicsJoint.WheelJoint = 3;
  81681. PhysicsJoint.SliderJoint = 4;
  81682. //OIMO
  81683. PhysicsJoint.PrismaticJoint = 5;
  81684. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81685. PhysicsJoint.UniversalJoint = 6;
  81686. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81687. //Cannon
  81688. //Similar to a Ball-Joint. Different in params
  81689. PhysicsJoint.PointToPointJoint = 8;
  81690. //Cannon only at the moment
  81691. PhysicsJoint.SpringJoint = 9;
  81692. PhysicsJoint.LockJoint = 10;
  81693. return PhysicsJoint;
  81694. }());
  81695. BABYLON.PhysicsJoint = PhysicsJoint;
  81696. /**
  81697. * A class representing a physics distance joint.
  81698. */
  81699. var DistanceJoint = /** @class */ (function (_super) {
  81700. __extends(DistanceJoint, _super);
  81701. function DistanceJoint(jointData) {
  81702. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81703. }
  81704. /**
  81705. * Update the predefined distance.
  81706. */
  81707. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81708. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81709. };
  81710. return DistanceJoint;
  81711. }(PhysicsJoint));
  81712. BABYLON.DistanceJoint = DistanceJoint;
  81713. var MotorEnabledJoint = /** @class */ (function (_super) {
  81714. __extends(MotorEnabledJoint, _super);
  81715. function MotorEnabledJoint(type, jointData) {
  81716. return _super.call(this, type, jointData) || this;
  81717. }
  81718. /**
  81719. * Set the motor values.
  81720. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81721. * @param {number} force the force to apply
  81722. * @param {number} maxForce max force for this motor.
  81723. */
  81724. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81725. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81726. };
  81727. /**
  81728. * Set the motor's limits.
  81729. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81730. */
  81731. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81732. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81733. };
  81734. return MotorEnabledJoint;
  81735. }(PhysicsJoint));
  81736. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81737. /**
  81738. * This class represents a single hinge physics joint
  81739. */
  81740. var HingeJoint = /** @class */ (function (_super) {
  81741. __extends(HingeJoint, _super);
  81742. function HingeJoint(jointData) {
  81743. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81744. }
  81745. /**
  81746. * Set the motor values.
  81747. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81748. * @param {number} force the force to apply
  81749. * @param {number} maxForce max force for this motor.
  81750. */
  81751. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81752. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81753. };
  81754. /**
  81755. * Set the motor's limits.
  81756. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81757. */
  81758. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81759. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81760. };
  81761. return HingeJoint;
  81762. }(MotorEnabledJoint));
  81763. BABYLON.HingeJoint = HingeJoint;
  81764. /**
  81765. * This class represents a dual hinge physics joint (same as wheel joint)
  81766. */
  81767. var Hinge2Joint = /** @class */ (function (_super) {
  81768. __extends(Hinge2Joint, _super);
  81769. function Hinge2Joint(jointData) {
  81770. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81771. }
  81772. /**
  81773. * Set the motor values.
  81774. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81775. * @param {number} force the force to apply
  81776. * @param {number} maxForce max force for this motor.
  81777. * @param {motorIndex} the motor's index, 0 or 1.
  81778. */
  81779. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81780. if (motorIndex === void 0) { motorIndex = 0; }
  81781. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81782. };
  81783. /**
  81784. * Set the motor limits.
  81785. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81786. * @param {number} upperLimit the upper limit
  81787. * @param {number} lowerLimit lower limit
  81788. * @param {motorIndex} the motor's index, 0 or 1.
  81789. */
  81790. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81791. if (motorIndex === void 0) { motorIndex = 0; }
  81792. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81793. };
  81794. return Hinge2Joint;
  81795. }(MotorEnabledJoint));
  81796. BABYLON.Hinge2Joint = Hinge2Joint;
  81797. })(BABYLON || (BABYLON = {}));
  81798. //# sourceMappingURL=babylon.physicsJoint.js.map
  81799. var BABYLON;
  81800. (function (BABYLON) {
  81801. var PhysicsImpostor = /** @class */ (function () {
  81802. function PhysicsImpostor(object, type, _options, _scene) {
  81803. if (_options === void 0) { _options = { mass: 0 }; }
  81804. var _this = this;
  81805. this.object = object;
  81806. this.type = type;
  81807. this._options = _options;
  81808. this._scene = _scene;
  81809. this._bodyUpdateRequired = false;
  81810. this._onBeforePhysicsStepCallbacks = new Array();
  81811. this._onAfterPhysicsStepCallbacks = new Array();
  81812. this._onPhysicsCollideCallbacks = [];
  81813. this._deltaPosition = BABYLON.Vector3.Zero();
  81814. this._isDisposed = false;
  81815. //temp variables for parent rotation calculations
  81816. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81817. this._tmpQuat = new BABYLON.Quaternion();
  81818. this._tmpQuat2 = new BABYLON.Quaternion();
  81819. /**
  81820. * this function is executed by the physics engine.
  81821. */
  81822. this.beforeStep = function () {
  81823. if (!_this._physicsEngine) {
  81824. return;
  81825. }
  81826. _this.object.translate(_this._deltaPosition, -1);
  81827. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81828. _this.object.computeWorldMatrix(false);
  81829. if (_this.object.parent && _this.object.rotationQuaternion) {
  81830. _this.getParentsRotation();
  81831. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81832. }
  81833. else {
  81834. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81835. }
  81836. if (!_this._options.disableBidirectionalTransformation) {
  81837. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81838. }
  81839. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81840. func(_this);
  81841. });
  81842. };
  81843. /**
  81844. * this function is executed by the physics engine.
  81845. */
  81846. this.afterStep = function () {
  81847. if (!_this._physicsEngine) {
  81848. return;
  81849. }
  81850. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81851. func(_this);
  81852. });
  81853. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81854. // object has now its world rotation. needs to be converted to local.
  81855. if (_this.object.parent && _this.object.rotationQuaternion) {
  81856. _this.getParentsRotation();
  81857. _this._tmpQuat.conjugateInPlace();
  81858. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81859. }
  81860. // take the position set and make it the absolute position of this object.
  81861. _this.object.setAbsolutePosition(_this.object.position);
  81862. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81863. _this.object.translate(_this._deltaPosition, 1);
  81864. };
  81865. /**
  81866. * Legacy collision detection event support
  81867. */
  81868. this.onCollideEvent = null;
  81869. //event and body object due to cannon's event-based architecture.
  81870. this.onCollide = function (e) {
  81871. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81872. return;
  81873. }
  81874. if (!_this._physicsEngine) {
  81875. return;
  81876. }
  81877. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81878. if (otherImpostor) {
  81879. // Legacy collision detection event support
  81880. if (_this.onCollideEvent) {
  81881. _this.onCollideEvent(_this, otherImpostor);
  81882. }
  81883. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81884. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81885. }).forEach(function (obj) {
  81886. obj.callback(_this, otherImpostor);
  81887. });
  81888. }
  81889. };
  81890. //sanity check!
  81891. if (!this.object) {
  81892. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81893. return;
  81894. }
  81895. //legacy support for old syntax.
  81896. if (!this._scene && object.getScene) {
  81897. this._scene = object.getScene();
  81898. }
  81899. if (!this._scene) {
  81900. return;
  81901. }
  81902. this._physicsEngine = this._scene.getPhysicsEngine();
  81903. if (!this._physicsEngine) {
  81904. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81905. }
  81906. else {
  81907. //set the object's quaternion, if not set
  81908. if (!this.object.rotationQuaternion) {
  81909. if (this.object.rotation) {
  81910. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81911. }
  81912. else {
  81913. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81914. }
  81915. }
  81916. //default options params
  81917. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81918. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81919. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81920. this._joints = [];
  81921. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81922. if (!this.object.parent || this._options.ignoreParent) {
  81923. this._init();
  81924. }
  81925. else if (this.object.parent.physicsImpostor) {
  81926. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81927. }
  81928. }
  81929. }
  81930. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81931. get: function () {
  81932. return this._isDisposed;
  81933. },
  81934. enumerable: true,
  81935. configurable: true
  81936. });
  81937. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81938. get: function () {
  81939. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81940. },
  81941. set: function (value) {
  81942. this.setMass(value);
  81943. },
  81944. enumerable: true,
  81945. configurable: true
  81946. });
  81947. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81948. get: function () {
  81949. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81950. },
  81951. set: function (value) {
  81952. if (!this._physicsEngine) {
  81953. return;
  81954. }
  81955. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81956. },
  81957. enumerable: true,
  81958. configurable: true
  81959. });
  81960. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81961. get: function () {
  81962. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81963. },
  81964. set: function (value) {
  81965. if (!this._physicsEngine) {
  81966. return;
  81967. }
  81968. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81969. },
  81970. enumerable: true,
  81971. configurable: true
  81972. });
  81973. /**
  81974. * This function will completly initialize this impostor.
  81975. * It will create a new body - but only if this mesh has no parent.
  81976. * If it has, this impostor will not be used other than to define the impostor
  81977. * of the child mesh.
  81978. */
  81979. PhysicsImpostor.prototype._init = function () {
  81980. if (!this._physicsEngine) {
  81981. return;
  81982. }
  81983. this._physicsEngine.removeImpostor(this);
  81984. this.physicsBody = null;
  81985. this._parent = this._parent || this._getPhysicsParent();
  81986. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81987. this._physicsEngine.addImpostor(this);
  81988. }
  81989. };
  81990. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81991. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81992. var parentMesh = this.object.parent;
  81993. return parentMesh.physicsImpostor;
  81994. }
  81995. return null;
  81996. };
  81997. /**
  81998. * Should a new body be generated.
  81999. */
  82000. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82001. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82002. };
  82003. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82004. this.forceUpdate();
  82005. };
  82006. /**
  82007. * Force a regeneration of this or the parent's impostor's body.
  82008. * Use under cautious - This will remove all joints already implemented.
  82009. */
  82010. PhysicsImpostor.prototype.forceUpdate = function () {
  82011. this._init();
  82012. if (this.parent && !this._options.ignoreParent) {
  82013. this.parent.forceUpdate();
  82014. }
  82015. };
  82016. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82017. /*public get mesh(): AbstractMesh {
  82018. return this._mesh;
  82019. }*/
  82020. /**
  82021. * Gets the body that holds this impostor. Either its own, or its parent.
  82022. */
  82023. get: function () {
  82024. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82025. },
  82026. /**
  82027. * Set the physics body. Used mainly by the physics engine/plugin
  82028. */
  82029. set: function (physicsBody) {
  82030. if (this._physicsBody && this._physicsEngine) {
  82031. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82032. }
  82033. this._physicsBody = physicsBody;
  82034. this.resetUpdateFlags();
  82035. },
  82036. enumerable: true,
  82037. configurable: true
  82038. });
  82039. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82040. get: function () {
  82041. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82042. },
  82043. set: function (value) {
  82044. this._parent = value;
  82045. },
  82046. enumerable: true,
  82047. configurable: true
  82048. });
  82049. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82050. this._bodyUpdateRequired = false;
  82051. };
  82052. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82053. if (this.object.getBoundingInfo) {
  82054. var q = this.object.rotationQuaternion;
  82055. //reset rotation
  82056. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82057. //calculate the world matrix with no rotation
  82058. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82059. var boundingInfo = this.object.getBoundingInfo();
  82060. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82061. //bring back the rotation
  82062. this.object.rotationQuaternion = q;
  82063. //calculate the world matrix with the new rotation
  82064. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82065. return size;
  82066. }
  82067. else {
  82068. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82069. }
  82070. };
  82071. PhysicsImpostor.prototype.getObjectCenter = function () {
  82072. if (this.object.getBoundingInfo) {
  82073. var boundingInfo = this.object.getBoundingInfo();
  82074. return boundingInfo.boundingBox.centerWorld;
  82075. }
  82076. else {
  82077. return this.object.position;
  82078. }
  82079. };
  82080. /**
  82081. * Get a specific parametes from the options parameter.
  82082. */
  82083. PhysicsImpostor.prototype.getParam = function (paramName) {
  82084. return this._options[paramName];
  82085. };
  82086. /**
  82087. * Sets a specific parameter in the options given to the physics plugin
  82088. */
  82089. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82090. this._options[paramName] = value;
  82091. this._bodyUpdateRequired = true;
  82092. };
  82093. /**
  82094. * Specifically change the body's mass option. Won't recreate the physics body object
  82095. */
  82096. PhysicsImpostor.prototype.setMass = function (mass) {
  82097. if (this.getParam("mass") !== mass) {
  82098. this.setParam("mass", mass);
  82099. }
  82100. if (this._physicsEngine) {
  82101. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82102. }
  82103. };
  82104. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82105. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82106. };
  82107. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82108. if (this._physicsEngine) {
  82109. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82110. }
  82111. };
  82112. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82113. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82114. };
  82115. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82116. if (this._physicsEngine) {
  82117. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82118. }
  82119. };
  82120. /**
  82121. * Execute a function with the physics plugin native code.
  82122. * Provide a function the will have two variables - the world object and the physics body object.
  82123. */
  82124. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82125. if (this._physicsEngine) {
  82126. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82127. }
  82128. };
  82129. /**
  82130. * Register a function that will be executed before the physics world is stepping forward.
  82131. */
  82132. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82133. this._onBeforePhysicsStepCallbacks.push(func);
  82134. };
  82135. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82136. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82137. if (index > -1) {
  82138. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82139. }
  82140. else {
  82141. BABYLON.Tools.Warn("Function to remove was not found");
  82142. }
  82143. };
  82144. /**
  82145. * Register a function that will be executed after the physics step
  82146. */
  82147. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82148. this._onAfterPhysicsStepCallbacks.push(func);
  82149. };
  82150. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82151. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82152. if (index > -1) {
  82153. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82154. }
  82155. else {
  82156. BABYLON.Tools.Warn("Function to remove was not found");
  82157. }
  82158. };
  82159. /**
  82160. * register a function that will be executed when this impostor collides against a different body.
  82161. */
  82162. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82163. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82164. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82165. };
  82166. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82167. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82168. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82169. if (index > -1) {
  82170. this._onPhysicsCollideCallbacks.splice(index, 1);
  82171. }
  82172. else {
  82173. BABYLON.Tools.Warn("Function to remove was not found");
  82174. }
  82175. };
  82176. PhysicsImpostor.prototype.getParentsRotation = function () {
  82177. var parent = this.object.parent;
  82178. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82179. while (parent) {
  82180. if (parent.rotationQuaternion) {
  82181. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82182. }
  82183. else {
  82184. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82185. }
  82186. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82187. parent = parent.parent;
  82188. }
  82189. return this._tmpQuat;
  82190. };
  82191. /**
  82192. * Apply a force
  82193. */
  82194. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82195. if (this._physicsEngine) {
  82196. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82197. }
  82198. return this;
  82199. };
  82200. /**
  82201. * Apply an impulse
  82202. */
  82203. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82204. if (this._physicsEngine) {
  82205. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82206. }
  82207. return this;
  82208. };
  82209. /**
  82210. * A help function to create a joint.
  82211. */
  82212. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82213. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82214. this.addJoint(otherImpostor, joint);
  82215. return this;
  82216. };
  82217. /**
  82218. * Add a joint to this impostor with a different impostor.
  82219. */
  82220. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82221. this._joints.push({
  82222. otherImpostor: otherImpostor,
  82223. joint: joint
  82224. });
  82225. if (this._physicsEngine) {
  82226. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82227. }
  82228. return this;
  82229. };
  82230. /**
  82231. * Will keep this body still, in a sleep mode.
  82232. */
  82233. PhysicsImpostor.prototype.sleep = function () {
  82234. if (this._physicsEngine) {
  82235. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82236. }
  82237. return this;
  82238. };
  82239. /**
  82240. * Wake the body up.
  82241. */
  82242. PhysicsImpostor.prototype.wakeUp = function () {
  82243. if (this._physicsEngine) {
  82244. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82245. }
  82246. return this;
  82247. };
  82248. PhysicsImpostor.prototype.clone = function (newObject) {
  82249. if (!newObject)
  82250. return null;
  82251. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82252. };
  82253. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82254. var _this = this;
  82255. //no dispose if no physics engine is available.
  82256. if (!this._physicsEngine) {
  82257. return;
  82258. }
  82259. this._joints.forEach(function (j) {
  82260. if (_this._physicsEngine) {
  82261. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82262. }
  82263. });
  82264. //dispose the physics body
  82265. this._physicsEngine.removeImpostor(this);
  82266. if (this.parent) {
  82267. this.parent.forceUpdate();
  82268. }
  82269. else {
  82270. /*this._object.getChildMeshes().forEach(function(mesh) {
  82271. if (mesh.physicsImpostor) {
  82272. if (disposeChildren) {
  82273. mesh.physicsImpostor.dispose();
  82274. mesh.physicsImpostor = null;
  82275. }
  82276. }
  82277. })*/
  82278. }
  82279. this._isDisposed = true;
  82280. };
  82281. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82282. this._deltaPosition.copyFrom(position);
  82283. };
  82284. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82285. if (!this._deltaRotation) {
  82286. this._deltaRotation = new BABYLON.Quaternion();
  82287. }
  82288. this._deltaRotation.copyFrom(rotation);
  82289. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82290. };
  82291. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82292. if (this._physicsEngine) {
  82293. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82294. }
  82295. return this;
  82296. };
  82297. PhysicsImpostor.prototype.getRadius = function () {
  82298. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82299. };
  82300. /**
  82301. * Sync a bone with this impostor
  82302. * @param bone The bone to sync to the impostor.
  82303. * @param boneMesh The mesh that the bone is influencing.
  82304. * @param jointPivot The pivot of the joint / bone in local space.
  82305. * @param distToJoint Optional distance from the impostor to the joint.
  82306. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82307. */
  82308. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82309. var tempVec = PhysicsImpostor._tmpVecs[0];
  82310. var mesh = this.object;
  82311. if (mesh.rotationQuaternion) {
  82312. if (adjustRotation) {
  82313. var tempQuat = PhysicsImpostor._tmpQuat;
  82314. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82315. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82316. }
  82317. else {
  82318. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82319. }
  82320. }
  82321. tempVec.x = 0;
  82322. tempVec.y = 0;
  82323. tempVec.z = 0;
  82324. if (jointPivot) {
  82325. tempVec.x = jointPivot.x;
  82326. tempVec.y = jointPivot.y;
  82327. tempVec.z = jointPivot.z;
  82328. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82329. if (distToJoint === undefined || distToJoint === null) {
  82330. distToJoint = jointPivot.length();
  82331. }
  82332. tempVec.x *= distToJoint;
  82333. tempVec.y *= distToJoint;
  82334. tempVec.z *= distToJoint;
  82335. }
  82336. if (bone.getParent()) {
  82337. tempVec.addInPlace(mesh.getAbsolutePosition());
  82338. bone.setAbsolutePosition(tempVec, boneMesh);
  82339. }
  82340. else {
  82341. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82342. boneMesh.position.x -= tempVec.x;
  82343. boneMesh.position.y -= tempVec.y;
  82344. boneMesh.position.z -= tempVec.z;
  82345. }
  82346. };
  82347. /**
  82348. * Sync impostor to a bone
  82349. * @param bone The bone that the impostor will be synced to.
  82350. * @param boneMesh The mesh that the bone is influencing.
  82351. * @param jointPivot The pivot of the joint / bone in local space.
  82352. * @param distToJoint Optional distance from the impostor to the joint.
  82353. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82354. * @param boneAxis Optional vector3 axis the bone is aligned with
  82355. */
  82356. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82357. var mesh = this.object;
  82358. if (mesh.rotationQuaternion) {
  82359. if (adjustRotation) {
  82360. var tempQuat = PhysicsImpostor._tmpQuat;
  82361. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82362. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82363. }
  82364. else {
  82365. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82366. }
  82367. }
  82368. var pos = PhysicsImpostor._tmpVecs[0];
  82369. var boneDir = PhysicsImpostor._tmpVecs[1];
  82370. if (!boneAxis) {
  82371. boneAxis = PhysicsImpostor._tmpVecs[2];
  82372. boneAxis.x = 0;
  82373. boneAxis.y = 1;
  82374. boneAxis.z = 0;
  82375. }
  82376. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82377. bone.getAbsolutePositionToRef(boneMesh, pos);
  82378. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82379. distToJoint = jointPivot.length();
  82380. }
  82381. if (distToJoint !== undefined && distToJoint !== null) {
  82382. pos.x += boneDir.x * distToJoint;
  82383. pos.y += boneDir.y * distToJoint;
  82384. pos.z += boneDir.z * distToJoint;
  82385. }
  82386. mesh.setAbsolutePosition(pos);
  82387. };
  82388. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82389. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82390. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82391. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82392. //Impostor types
  82393. PhysicsImpostor.NoImpostor = 0;
  82394. PhysicsImpostor.SphereImpostor = 1;
  82395. PhysicsImpostor.BoxImpostor = 2;
  82396. PhysicsImpostor.PlaneImpostor = 3;
  82397. PhysicsImpostor.MeshImpostor = 4;
  82398. PhysicsImpostor.CylinderImpostor = 7;
  82399. PhysicsImpostor.ParticleImpostor = 8;
  82400. PhysicsImpostor.HeightmapImpostor = 9;
  82401. return PhysicsImpostor;
  82402. }());
  82403. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82404. })(BABYLON || (BABYLON = {}));
  82405. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82406. var BABYLON;
  82407. (function (BABYLON) {
  82408. var PhysicsEngine = /** @class */ (function () {
  82409. function PhysicsEngine(gravity, _physicsPlugin) {
  82410. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82411. this._physicsPlugin = _physicsPlugin;
  82412. //new methods and parameters
  82413. this._impostors = [];
  82414. this._joints = [];
  82415. if (!this._physicsPlugin.isSupported()) {
  82416. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82417. + "Please make sure it is included.");
  82418. }
  82419. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82420. this.setGravity(gravity);
  82421. this.setTimeStep();
  82422. }
  82423. PhysicsEngine.prototype.setGravity = function (gravity) {
  82424. this.gravity = gravity;
  82425. this._physicsPlugin.setGravity(this.gravity);
  82426. };
  82427. /**
  82428. * Set the time step of the physics engine.
  82429. * default is 1/60.
  82430. * To slow it down, enter 1/600 for example.
  82431. * To speed it up, 1/30
  82432. * @param {number} newTimeStep the new timestep to apply to this world.
  82433. */
  82434. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82435. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82436. this._physicsPlugin.setTimeStep(newTimeStep);
  82437. };
  82438. /**
  82439. * Get the time step of the physics engine.
  82440. */
  82441. PhysicsEngine.prototype.getTimeStep = function () {
  82442. return this._physicsPlugin.getTimeStep();
  82443. };
  82444. PhysicsEngine.prototype.dispose = function () {
  82445. this._impostors.forEach(function (impostor) {
  82446. impostor.dispose();
  82447. });
  82448. this._physicsPlugin.dispose();
  82449. };
  82450. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82451. return this._physicsPlugin.name;
  82452. };
  82453. /**
  82454. * Adding a new impostor for the impostor tracking.
  82455. * This will be done by the impostor itself.
  82456. * @param {PhysicsImpostor} impostor the impostor to add
  82457. */
  82458. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82459. impostor.uniqueId = this._impostors.push(impostor);
  82460. //if no parent, generate the body
  82461. if (!impostor.parent) {
  82462. this._physicsPlugin.generatePhysicsBody(impostor);
  82463. }
  82464. };
  82465. /**
  82466. * Remove an impostor from the engine.
  82467. * This impostor and its mesh will not longer be updated by the physics engine.
  82468. * @param {PhysicsImpostor} impostor the impostor to remove
  82469. */
  82470. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82471. var index = this._impostors.indexOf(impostor);
  82472. if (index > -1) {
  82473. var removed = this._impostors.splice(index, 1);
  82474. //Is it needed?
  82475. if (removed.length) {
  82476. //this will also remove it from the world.
  82477. removed[0].physicsBody = null;
  82478. }
  82479. }
  82480. };
  82481. /**
  82482. * Add a joint to the physics engine
  82483. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82484. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82485. * @param {PhysicsJoint} the joint that will connect both impostors.
  82486. */
  82487. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82488. var impostorJoint = {
  82489. mainImpostor: mainImpostor,
  82490. connectedImpostor: connectedImpostor,
  82491. joint: joint
  82492. };
  82493. joint.physicsPlugin = this._physicsPlugin;
  82494. this._joints.push(impostorJoint);
  82495. this._physicsPlugin.generateJoint(impostorJoint);
  82496. };
  82497. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82498. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82499. return (impostorJoint.connectedImpostor === connectedImpostor
  82500. && impostorJoint.joint === joint
  82501. && impostorJoint.mainImpostor === mainImpostor);
  82502. });
  82503. if (matchingJoints.length) {
  82504. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82505. //TODO remove it from the list as well
  82506. }
  82507. };
  82508. /**
  82509. * Called by the scene. no need to call it.
  82510. */
  82511. PhysicsEngine.prototype._step = function (delta) {
  82512. var _this = this;
  82513. //check if any mesh has no body / requires an update
  82514. this._impostors.forEach(function (impostor) {
  82515. if (impostor.isBodyInitRequired()) {
  82516. _this._physicsPlugin.generatePhysicsBody(impostor);
  82517. }
  82518. });
  82519. if (delta > 0.1) {
  82520. delta = 0.1;
  82521. }
  82522. else if (delta <= 0) {
  82523. delta = 1.0 / 60.0;
  82524. }
  82525. this._physicsPlugin.executeStep(delta, this._impostors);
  82526. };
  82527. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82528. return this._physicsPlugin;
  82529. };
  82530. PhysicsEngine.prototype.getImpostors = function () {
  82531. return this._impostors;
  82532. };
  82533. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82534. for (var i = 0; i < this._impostors.length; ++i) {
  82535. if (this._impostors[i].object === object) {
  82536. return this._impostors[i];
  82537. }
  82538. }
  82539. return null;
  82540. };
  82541. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82542. for (var i = 0; i < this._impostors.length; ++i) {
  82543. if (this._impostors[i].physicsBody === body) {
  82544. return this._impostors[i];
  82545. }
  82546. }
  82547. return null;
  82548. };
  82549. // Statics
  82550. PhysicsEngine.Epsilon = 0.001;
  82551. return PhysicsEngine;
  82552. }());
  82553. BABYLON.PhysicsEngine = PhysicsEngine;
  82554. })(BABYLON || (BABYLON = {}));
  82555. //# sourceMappingURL=babylon.physicsEngine.js.map
  82556. var BABYLON;
  82557. (function (BABYLON) {
  82558. var PhysicsHelper = /** @class */ (function () {
  82559. function PhysicsHelper(scene) {
  82560. this._scene = scene;
  82561. this._physicsEngine = this._scene.getPhysicsEngine();
  82562. if (!this._physicsEngine) {
  82563. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82564. }
  82565. }
  82566. /**
  82567. * @param {Vector3} origin the origin of the explosion
  82568. * @param {number} radius the explosion radius
  82569. * @param {number} strength the explosion strength
  82570. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82571. */
  82572. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82573. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82574. if (!this._physicsEngine) {
  82575. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82576. return null;
  82577. }
  82578. var impostors = this._physicsEngine.getImpostors();
  82579. if (impostors.length === 0) {
  82580. return null;
  82581. }
  82582. var event = new PhysicsRadialExplosionEvent(this._scene);
  82583. impostors.forEach(function (impostor) {
  82584. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82585. if (!impostorForceAndContactPoint) {
  82586. return;
  82587. }
  82588. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82589. });
  82590. event.dispose(false);
  82591. return event;
  82592. };
  82593. /**
  82594. * @param {Vector3} origin the origin of the explosion
  82595. * @param {number} radius the explosion radius
  82596. * @param {number} strength the explosion strength
  82597. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82598. */
  82599. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82600. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82601. if (!this._physicsEngine) {
  82602. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82603. return null;
  82604. }
  82605. var impostors = this._physicsEngine.getImpostors();
  82606. if (impostors.length === 0) {
  82607. return null;
  82608. }
  82609. var event = new PhysicsRadialExplosionEvent(this._scene);
  82610. impostors.forEach(function (impostor) {
  82611. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82612. if (!impostorForceAndContactPoint) {
  82613. return;
  82614. }
  82615. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82616. });
  82617. event.dispose(false);
  82618. return event;
  82619. };
  82620. /**
  82621. * @param {Vector3} origin the origin of the explosion
  82622. * @param {number} radius the explosion radius
  82623. * @param {number} strength the explosion strength
  82624. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82625. */
  82626. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82627. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82628. if (!this._physicsEngine) {
  82629. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82630. return null;
  82631. }
  82632. var impostors = this._physicsEngine.getImpostors();
  82633. if (impostors.length === 0) {
  82634. return null;
  82635. }
  82636. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82637. event.dispose(false);
  82638. return event;
  82639. };
  82640. /**
  82641. * @param {Vector3} origin the origin of the updraft
  82642. * @param {number} radius the radius of the updraft
  82643. * @param {number} strength the strength of the updraft
  82644. * @param {number} height the height of the updraft
  82645. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82646. */
  82647. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82648. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82649. if (!this._physicsEngine) {
  82650. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82651. return null;
  82652. }
  82653. if (this._physicsEngine.getImpostors().length === 0) {
  82654. return null;
  82655. }
  82656. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82657. event.dispose(false);
  82658. return event;
  82659. };
  82660. /**
  82661. * @param {Vector3} origin the of the vortex
  82662. * @param {number} radius the radius of the vortex
  82663. * @param {number} strength the strength of the vortex
  82664. * @param {number} height the height of the vortex
  82665. */
  82666. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82667. if (!this._physicsEngine) {
  82668. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82669. return null;
  82670. }
  82671. if (this._physicsEngine.getImpostors().length === 0) {
  82672. return null;
  82673. }
  82674. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82675. event.dispose(false);
  82676. return event;
  82677. };
  82678. return PhysicsHelper;
  82679. }());
  82680. BABYLON.PhysicsHelper = PhysicsHelper;
  82681. /***** Radial explosion *****/
  82682. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82683. function PhysicsRadialExplosionEvent(scene) {
  82684. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82685. this._rays = [];
  82686. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82687. this._scene = scene;
  82688. }
  82689. /**
  82690. * Returns the data related to the radial explosion event (sphere & rays).
  82691. * @returns {PhysicsRadialExplosionEventData}
  82692. */
  82693. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82694. this._dataFetched = true;
  82695. return {
  82696. sphere: this._sphere,
  82697. rays: this._rays,
  82698. };
  82699. };
  82700. /**
  82701. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82702. * @param impostor
  82703. * @param {Vector3} origin the origin of the explosion
  82704. * @param {number} radius the explosion radius
  82705. * @param {number} strength the explosion strength
  82706. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82707. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82708. */
  82709. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82710. if (impostor.mass === 0) {
  82711. return null;
  82712. }
  82713. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82714. return null;
  82715. }
  82716. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82717. return null;
  82718. }
  82719. var impostorObjectCenter = impostor.getObjectCenter();
  82720. var direction = impostorObjectCenter.subtract(origin);
  82721. var ray = new BABYLON.Ray(origin, direction, radius);
  82722. this._rays.push(ray);
  82723. var hit = ray.intersectsMesh(impostor.object);
  82724. var contactPoint = hit.pickedPoint;
  82725. if (!contactPoint) {
  82726. return null;
  82727. }
  82728. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82729. if (distanceFromOrigin > radius) {
  82730. return null;
  82731. }
  82732. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82733. ? strength
  82734. : strength * (1 - (distanceFromOrigin / radius));
  82735. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82736. return { force: force, contactPoint: contactPoint };
  82737. };
  82738. /**
  82739. * Disposes the sphere.
  82740. * @param {bolean} force
  82741. */
  82742. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82743. var _this = this;
  82744. if (force === void 0) { force = true; }
  82745. if (force) {
  82746. this._sphere.dispose();
  82747. }
  82748. else {
  82749. setTimeout(function () {
  82750. if (!_this._dataFetched) {
  82751. _this._sphere.dispose();
  82752. }
  82753. }, 0);
  82754. }
  82755. };
  82756. /*** Helpers ***/
  82757. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82758. if (!this._sphere) {
  82759. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82760. this._sphere.isVisible = false;
  82761. }
  82762. };
  82763. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82764. var impostorObject = impostor.object;
  82765. this._prepareSphere();
  82766. this._sphere.position = origin;
  82767. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82768. this._sphere._updateBoundingInfo();
  82769. this._sphere.computeWorldMatrix(true);
  82770. return this._sphere.intersectsMesh(impostorObject, true);
  82771. };
  82772. return PhysicsRadialExplosionEvent;
  82773. }());
  82774. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82775. /***** Gravitational Field *****/
  82776. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82777. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82778. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82779. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82780. this._physicsHelper = physicsHelper;
  82781. this._scene = scene;
  82782. this._origin = origin;
  82783. this._radius = radius;
  82784. this._strength = strength;
  82785. this._falloff = falloff;
  82786. this._tickCallback = this._tick.bind(this);
  82787. }
  82788. /**
  82789. * Returns the data related to the gravitational field event (sphere).
  82790. * @returns {PhysicsGravitationalFieldEventData}
  82791. */
  82792. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82793. this._dataFetched = true;
  82794. return {
  82795. sphere: this._sphere,
  82796. };
  82797. };
  82798. /**
  82799. * Enables the gravitational field.
  82800. */
  82801. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82802. this._tickCallback.call(this);
  82803. this._scene.registerBeforeRender(this._tickCallback);
  82804. };
  82805. /**
  82806. * Disables the gravitational field.
  82807. */
  82808. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82809. this._scene.unregisterBeforeRender(this._tickCallback);
  82810. };
  82811. /**
  82812. * Disposes the sphere.
  82813. * @param {bolean} force
  82814. */
  82815. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82816. var _this = this;
  82817. if (force === void 0) { force = true; }
  82818. if (force) {
  82819. this._sphere.dispose();
  82820. }
  82821. else {
  82822. setTimeout(function () {
  82823. if (!_this._dataFetched) {
  82824. _this._sphere.dispose();
  82825. }
  82826. }, 0);
  82827. }
  82828. };
  82829. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82830. // Since the params won't change, we fetch the event only once
  82831. if (this._sphere) {
  82832. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82833. }
  82834. else {
  82835. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82836. if (radialExplosionEvent) {
  82837. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82838. }
  82839. }
  82840. };
  82841. return PhysicsGravitationalFieldEvent;
  82842. }());
  82843. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82844. /***** Updraft *****/
  82845. var PhysicsUpdraftEvent = /** @class */ (function () {
  82846. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82847. this._scene = _scene;
  82848. this._origin = _origin;
  82849. this._radius = _radius;
  82850. this._strength = _strength;
  82851. this._height = _height;
  82852. this._updraftMode = _updraftMode;
  82853. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82854. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82855. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82856. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82857. this._physicsEngine = this._scene.getPhysicsEngine();
  82858. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82859. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82860. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82861. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82862. }
  82863. this._tickCallback = this._tick.bind(this);
  82864. }
  82865. /**
  82866. * Returns the data related to the updraft event (cylinder).
  82867. * @returns {PhysicsUpdraftEventData}
  82868. */
  82869. PhysicsUpdraftEvent.prototype.getData = function () {
  82870. this._dataFetched = true;
  82871. return {
  82872. cylinder: this._cylinder,
  82873. };
  82874. };
  82875. /**
  82876. * Enables the updraft.
  82877. */
  82878. PhysicsUpdraftEvent.prototype.enable = function () {
  82879. this._tickCallback.call(this);
  82880. this._scene.registerBeforeRender(this._tickCallback);
  82881. };
  82882. /**
  82883. * Disables the cortex.
  82884. */
  82885. PhysicsUpdraftEvent.prototype.disable = function () {
  82886. this._scene.unregisterBeforeRender(this._tickCallback);
  82887. };
  82888. /**
  82889. * Disposes the sphere.
  82890. * @param {bolean} force
  82891. */
  82892. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82893. var _this = this;
  82894. if (force === void 0) { force = true; }
  82895. if (force) {
  82896. this._cylinder.dispose();
  82897. }
  82898. else {
  82899. setTimeout(function () {
  82900. if (!_this._dataFetched) {
  82901. _this._cylinder.dispose();
  82902. }
  82903. }, 0);
  82904. }
  82905. };
  82906. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82907. if (impostor.mass === 0) {
  82908. return null;
  82909. }
  82910. if (!this._intersectsWithCylinder(impostor)) {
  82911. return null;
  82912. }
  82913. var impostorObjectCenter = impostor.getObjectCenter();
  82914. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82915. var direction = this._originDirection;
  82916. }
  82917. else {
  82918. var direction = impostorObjectCenter.subtract(this._originTop);
  82919. }
  82920. var multiplier = this._strength * -1;
  82921. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82922. return { force: force, contactPoint: impostorObjectCenter };
  82923. };
  82924. PhysicsUpdraftEvent.prototype._tick = function () {
  82925. var _this = this;
  82926. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82927. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82928. if (!impostorForceAndContactPoint) {
  82929. return;
  82930. }
  82931. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82932. });
  82933. };
  82934. /*** Helpers ***/
  82935. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82936. if (!this._cylinder) {
  82937. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82938. height: this._height,
  82939. diameter: this._radius * 2,
  82940. }, this._scene);
  82941. this._cylinder.isVisible = false;
  82942. }
  82943. };
  82944. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82945. var impostorObject = impostor.object;
  82946. this._prepareCylinder();
  82947. this._cylinder.position = this._cylinderPosition;
  82948. return this._cylinder.intersectsMesh(impostorObject, true);
  82949. };
  82950. return PhysicsUpdraftEvent;
  82951. }());
  82952. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82953. /***** Vortex *****/
  82954. var PhysicsVortexEvent = /** @class */ (function () {
  82955. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82956. this._scene = _scene;
  82957. this._origin = _origin;
  82958. this._radius = _radius;
  82959. this._strength = _strength;
  82960. this._height = _height;
  82961. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82962. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82963. this._updraftMultiplier = 0.02;
  82964. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82965. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82966. this._physicsEngine = this._scene.getPhysicsEngine();
  82967. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82968. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82969. this._tickCallback = this._tick.bind(this);
  82970. }
  82971. /**
  82972. * Returns the data related to the vortex event (cylinder).
  82973. * @returns {PhysicsVortexEventData}
  82974. */
  82975. PhysicsVortexEvent.prototype.getData = function () {
  82976. this._dataFetched = true;
  82977. return {
  82978. cylinder: this._cylinder,
  82979. };
  82980. };
  82981. /**
  82982. * Enables the vortex.
  82983. */
  82984. PhysicsVortexEvent.prototype.enable = function () {
  82985. this._tickCallback.call(this);
  82986. this._scene.registerBeforeRender(this._tickCallback);
  82987. };
  82988. /**
  82989. * Disables the cortex.
  82990. */
  82991. PhysicsVortexEvent.prototype.disable = function () {
  82992. this._scene.unregisterBeforeRender(this._tickCallback);
  82993. };
  82994. /**
  82995. * Disposes the sphere.
  82996. * @param {bolean} force
  82997. */
  82998. PhysicsVortexEvent.prototype.dispose = function (force) {
  82999. var _this = this;
  83000. if (force === void 0) { force = true; }
  83001. if (force) {
  83002. this._cylinder.dispose();
  83003. }
  83004. else {
  83005. setTimeout(function () {
  83006. if (!_this._dataFetched) {
  83007. _this._cylinder.dispose();
  83008. }
  83009. }, 0);
  83010. }
  83011. };
  83012. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83013. if (impostor.mass === 0) {
  83014. return null;
  83015. }
  83016. if (!this._intersectsWithCylinder(impostor)) {
  83017. return null;
  83018. }
  83019. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83020. return null;
  83021. }
  83022. var impostorObjectCenter = impostor.getObjectCenter();
  83023. 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)
  83024. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83025. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83026. var hit = ray.intersectsMesh(impostor.object);
  83027. var contactPoint = hit.pickedPoint;
  83028. if (!contactPoint) {
  83029. return null;
  83030. }
  83031. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83032. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83033. var directionToOrigin = contactPoint.normalize();
  83034. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83035. directionToOrigin = directionToOrigin.negate();
  83036. }
  83037. // TODO: find a more physically based solution
  83038. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83039. var forceX = directionToOrigin.x * this._strength / 8;
  83040. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83041. var forceZ = directionToOrigin.z * this._strength / 8;
  83042. }
  83043. else {
  83044. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83045. var forceY = this._originTop.y * this._updraftMultiplier;
  83046. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83047. }
  83048. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83049. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83050. return { force: force, contactPoint: impostorObjectCenter };
  83051. };
  83052. PhysicsVortexEvent.prototype._tick = function () {
  83053. var _this = this;
  83054. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83055. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83056. if (!impostorForceAndContactPoint) {
  83057. return;
  83058. }
  83059. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83060. });
  83061. };
  83062. /*** Helpers ***/
  83063. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83064. if (!this._cylinder) {
  83065. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83066. height: this._height,
  83067. diameter: this._radius * 2,
  83068. }, this._scene);
  83069. this._cylinder.isVisible = false;
  83070. }
  83071. };
  83072. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83073. var impostorObject = impostor.object;
  83074. this._prepareCylinder();
  83075. this._cylinder.position = this._cylinderPosition;
  83076. return this._cylinder.intersectsMesh(impostorObject, true);
  83077. };
  83078. return PhysicsVortexEvent;
  83079. }());
  83080. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83081. /***** Enums *****/
  83082. /**
  83083. * The strenght of the force in correspondence to the distance of the affected object
  83084. */
  83085. var PhysicsRadialImpulseFalloff;
  83086. (function (PhysicsRadialImpulseFalloff) {
  83087. /** Defines that impulse is constant in strength across it's whole radius */
  83088. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83089. /** DEfines that impulse gets weaker if it's further from the origin */
  83090. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83091. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83092. /**
  83093. * The strenght of the force in correspondence to the distance of the affected object
  83094. */
  83095. var PhysicsUpdraftMode;
  83096. (function (PhysicsUpdraftMode) {
  83097. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83098. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83099. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83100. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83101. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83102. })(BABYLON || (BABYLON = {}));
  83103. //# sourceMappingURL=babylon.physicsHelper.js.map
  83104. var BABYLON;
  83105. (function (BABYLON) {
  83106. var CannonJSPlugin = /** @class */ (function () {
  83107. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83108. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83109. if (iterations === void 0) { iterations = 10; }
  83110. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83111. this.name = "CannonJSPlugin";
  83112. this._physicsMaterials = new Array();
  83113. this._fixedTimeStep = 1 / 60;
  83114. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83115. this.BJSCANNON = CANNON;
  83116. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83117. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83118. this._tmpPosition = BABYLON.Vector3.Zero();
  83119. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83120. this._tmpUnityRotation = new BABYLON.Quaternion();
  83121. if (!this.isSupported()) {
  83122. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83123. return;
  83124. }
  83125. this._extendNamespace();
  83126. this.world = new this.BJSCANNON.World();
  83127. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83128. this.world.solver.iterations = iterations;
  83129. }
  83130. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83131. this.world.gravity.copy(gravity);
  83132. };
  83133. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83134. this._fixedTimeStep = timeStep;
  83135. };
  83136. CannonJSPlugin.prototype.getTimeStep = function () {
  83137. return this._fixedTimeStep;
  83138. };
  83139. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83140. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83141. };
  83142. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83143. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83144. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83145. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83146. };
  83147. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83148. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83149. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83150. impostor.physicsBody.applyForce(impulse, worldPoint);
  83151. };
  83152. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83153. //parent-child relationship. Does this impostor has a parent impostor?
  83154. if (impostor.parent) {
  83155. if (impostor.physicsBody) {
  83156. this.removePhysicsBody(impostor);
  83157. //TODO is that needed?
  83158. impostor.forceUpdate();
  83159. }
  83160. return;
  83161. }
  83162. //should a new body be created for this impostor?
  83163. if (impostor.isBodyInitRequired()) {
  83164. var shape = this._createShape(impostor);
  83165. //unregister events, if body is being changed
  83166. var oldBody = impostor.physicsBody;
  83167. if (oldBody) {
  83168. this.removePhysicsBody(impostor);
  83169. }
  83170. //create the body and material
  83171. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83172. var bodyCreationObject = {
  83173. mass: impostor.getParam("mass"),
  83174. material: material
  83175. };
  83176. // A simple extend, in case native options were used.
  83177. var nativeOptions = impostor.getParam("nativeOptions");
  83178. for (var key in nativeOptions) {
  83179. if (nativeOptions.hasOwnProperty(key)) {
  83180. bodyCreationObject[key] = nativeOptions[key];
  83181. }
  83182. }
  83183. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83184. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83185. this.world.addEventListener("preStep", impostor.beforeStep);
  83186. this.world.addEventListener("postStep", impostor.afterStep);
  83187. impostor.physicsBody.addShape(shape);
  83188. this.world.add(impostor.physicsBody);
  83189. //try to keep the body moving in the right direction by taking old properties.
  83190. //Should be tested!
  83191. if (oldBody) {
  83192. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83193. impostor.physicsBody[param].copy(oldBody[param]);
  83194. });
  83195. }
  83196. this._processChildMeshes(impostor);
  83197. }
  83198. //now update the body's transformation
  83199. this._updatePhysicsBodyTransformation(impostor);
  83200. };
  83201. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83202. var _this = this;
  83203. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83204. var currentRotation = mainImpostor.object.rotationQuaternion;
  83205. if (meshChildren.length) {
  83206. var processMesh = function (localPosition, mesh) {
  83207. if (!currentRotation || !mesh.rotationQuaternion) {
  83208. return;
  83209. }
  83210. var childImpostor = mesh.getPhysicsImpostor();
  83211. if (childImpostor) {
  83212. var parent = childImpostor.parent;
  83213. if (parent !== mainImpostor) {
  83214. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83215. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83216. if (childImpostor.physicsBody) {
  83217. _this.removePhysicsBody(childImpostor);
  83218. childImpostor.physicsBody = null;
  83219. }
  83220. childImpostor.parent = mainImpostor;
  83221. childImpostor.resetUpdateFlags();
  83222. 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));
  83223. //Add the mass of the children.
  83224. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83225. }
  83226. }
  83227. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83228. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83229. };
  83230. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83231. }
  83232. };
  83233. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83234. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83235. this.world.removeEventListener("preStep", impostor.beforeStep);
  83236. this.world.removeEventListener("postStep", impostor.afterStep);
  83237. this.world.remove(impostor.physicsBody);
  83238. };
  83239. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83240. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83241. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83242. if (!mainBody || !connectedBody) {
  83243. return;
  83244. }
  83245. var constraint;
  83246. var jointData = impostorJoint.joint.jointData;
  83247. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83248. var constraintData = {
  83249. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83250. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83251. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83252. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83253. maxForce: jointData.nativeParams.maxForce,
  83254. collideConnected: !!jointData.collision
  83255. };
  83256. switch (impostorJoint.joint.type) {
  83257. case BABYLON.PhysicsJoint.HingeJoint:
  83258. case BABYLON.PhysicsJoint.Hinge2Joint:
  83259. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83260. break;
  83261. case BABYLON.PhysicsJoint.DistanceJoint:
  83262. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83263. break;
  83264. case BABYLON.PhysicsJoint.SpringJoint:
  83265. var springData = jointData;
  83266. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83267. restLength: springData.length,
  83268. stiffness: springData.stiffness,
  83269. damping: springData.damping,
  83270. localAnchorA: constraintData.pivotA,
  83271. localAnchorB: constraintData.pivotB
  83272. });
  83273. break;
  83274. case BABYLON.PhysicsJoint.LockJoint:
  83275. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83276. break;
  83277. case BABYLON.PhysicsJoint.PointToPointJoint:
  83278. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83279. default:
  83280. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83281. break;
  83282. }
  83283. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83284. constraint.collideConnected = !!jointData.collision;
  83285. impostorJoint.joint.physicsJoint = constraint;
  83286. //don't add spring as constraint, as it is not one.
  83287. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83288. this.world.addConstraint(constraint);
  83289. }
  83290. else {
  83291. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83292. constraint.applyForce();
  83293. });
  83294. }
  83295. };
  83296. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83297. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83298. };
  83299. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83300. var index;
  83301. var mat;
  83302. for (index = 0; index < this._physicsMaterials.length; index++) {
  83303. mat = this._physicsMaterials[index];
  83304. if (mat.friction === friction && mat.restitution === restitution) {
  83305. return mat;
  83306. }
  83307. }
  83308. var currentMat = new this.BJSCANNON.Material(name);
  83309. currentMat.friction = friction;
  83310. currentMat.restitution = restitution;
  83311. this._physicsMaterials.push(currentMat);
  83312. return currentMat;
  83313. };
  83314. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83315. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83316. };
  83317. CannonJSPlugin.prototype._createShape = function (impostor) {
  83318. var object = impostor.object;
  83319. var returnValue;
  83320. var extendSize = impostor.getObjectExtendSize();
  83321. switch (impostor.type) {
  83322. case BABYLON.PhysicsImpostor.SphereImpostor:
  83323. var radiusX = extendSize.x;
  83324. var radiusY = extendSize.y;
  83325. var radiusZ = extendSize.z;
  83326. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83327. break;
  83328. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83329. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83330. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83331. break;
  83332. case BABYLON.PhysicsImpostor.BoxImpostor:
  83333. var box = extendSize.scale(0.5);
  83334. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83335. break;
  83336. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83337. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83338. returnValue = new this.BJSCANNON.Plane();
  83339. break;
  83340. case BABYLON.PhysicsImpostor.MeshImpostor:
  83341. // should transform the vertex data to world coordinates!!
  83342. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83343. var rawFaces = object.getIndices ? object.getIndices() : [];
  83344. if (!rawVerts)
  83345. return;
  83346. // get only scale! so the object could transform correctly.
  83347. var oldPosition = object.position.clone();
  83348. var oldRotation = object.rotation && object.rotation.clone();
  83349. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83350. object.position.copyFromFloats(0, 0, 0);
  83351. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83352. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83353. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83354. var transform = object.computeWorldMatrix(true);
  83355. // convert rawVerts to object space
  83356. var temp = new Array();
  83357. var index;
  83358. for (index = 0; index < rawVerts.length; index += 3) {
  83359. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83360. }
  83361. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83362. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83363. //now set back the transformation!
  83364. object.position.copyFrom(oldPosition);
  83365. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83366. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83367. break;
  83368. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83369. var oldPosition2 = object.position.clone();
  83370. var oldRotation2 = object.rotation && object.rotation.clone();
  83371. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83372. object.position.copyFromFloats(0, 0, 0);
  83373. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83374. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83375. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83376. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83377. returnValue = this._createHeightmap(object);
  83378. object.position.copyFrom(oldPosition2);
  83379. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83380. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83381. object.computeWorldMatrix(true);
  83382. break;
  83383. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83384. returnValue = new this.BJSCANNON.Particle();
  83385. break;
  83386. }
  83387. return returnValue;
  83388. };
  83389. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83390. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83391. var transform = object.computeWorldMatrix(true);
  83392. // convert rawVerts to object space
  83393. var temp = new Array();
  83394. var index;
  83395. for (index = 0; index < pos.length; index += 3) {
  83396. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83397. }
  83398. pos = temp;
  83399. var matrix = new Array();
  83400. //For now pointDepth will not be used and will be automatically calculated.
  83401. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83402. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83403. var boundingInfo = object.getBoundingInfo();
  83404. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83405. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83406. var elementSize = dim * 2 / arraySize;
  83407. for (var i = 0; i < pos.length; i = i + 3) {
  83408. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83409. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83410. var y = -pos[i + 2] + minY;
  83411. if (!matrix[x]) {
  83412. matrix[x] = [];
  83413. }
  83414. if (!matrix[x][z]) {
  83415. matrix[x][z] = y;
  83416. }
  83417. matrix[x][z] = Math.max(y, matrix[x][z]);
  83418. }
  83419. for (var x = 0; x <= arraySize; ++x) {
  83420. if (!matrix[x]) {
  83421. var loc = 1;
  83422. while (!matrix[(x + loc) % arraySize]) {
  83423. loc++;
  83424. }
  83425. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83426. //console.log("missing x", x);
  83427. }
  83428. for (var z = 0; z <= arraySize; ++z) {
  83429. if (!matrix[x][z]) {
  83430. var loc = 1;
  83431. var newValue;
  83432. while (newValue === undefined) {
  83433. newValue = matrix[x][(z + loc++) % arraySize];
  83434. }
  83435. matrix[x][z] = newValue;
  83436. }
  83437. }
  83438. }
  83439. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83440. elementSize: elementSize
  83441. });
  83442. //For future reference, needed for body transformation
  83443. shape.minY = minY;
  83444. return shape;
  83445. };
  83446. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83447. var object = impostor.object;
  83448. //make sure it is updated...
  83449. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83450. // The delta between the mesh position and the mesh bounding box center
  83451. var bInfo = object.getBoundingInfo();
  83452. if (!bInfo)
  83453. return;
  83454. var center = impostor.getObjectCenter();
  83455. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83456. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83457. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83458. this._tmpPosition.copyFrom(center);
  83459. var quaternion = object.rotationQuaternion;
  83460. if (!quaternion) {
  83461. return;
  83462. }
  83463. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83464. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83465. //-90 DEG in X, precalculated
  83466. quaternion = quaternion.multiply(this._minus90X);
  83467. //Invert! (Precalculated, 90 deg in X)
  83468. //No need to clone. this will never change.
  83469. impostor.setDeltaRotation(this._plus90X);
  83470. }
  83471. //If it is a heightfield, if should be centered.
  83472. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83473. var mesh = object;
  83474. var boundingInfo = mesh.getBoundingInfo();
  83475. //calculate the correct body position:
  83476. var rotationQuaternion = mesh.rotationQuaternion;
  83477. mesh.rotationQuaternion = this._tmpUnityRotation;
  83478. mesh.computeWorldMatrix(true);
  83479. //get original center with no rotation
  83480. var c = center.clone();
  83481. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83482. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83483. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83484. mesh.setPreTransformMatrix(p);
  83485. mesh.computeWorldMatrix(true);
  83486. //calculate the translation
  83487. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83488. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83489. //add it inverted to the delta
  83490. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83491. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83492. //rotation is back
  83493. mesh.rotationQuaternion = rotationQuaternion;
  83494. mesh.setPreTransformMatrix(oldPivot);
  83495. mesh.computeWorldMatrix(true);
  83496. }
  83497. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83498. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83499. //this._tmpPosition.copyFrom(object.position);
  83500. }
  83501. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83502. //Now update the impostor object
  83503. impostor.physicsBody.position.copy(this._tmpPosition);
  83504. impostor.physicsBody.quaternion.copy(quaternion);
  83505. };
  83506. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83507. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83508. if (impostor.object.rotationQuaternion) {
  83509. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83510. }
  83511. };
  83512. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83513. impostor.physicsBody.position.copy(newPosition);
  83514. impostor.physicsBody.quaternion.copy(newRotation);
  83515. };
  83516. CannonJSPlugin.prototype.isSupported = function () {
  83517. return this.BJSCANNON !== undefined;
  83518. };
  83519. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83520. impostor.physicsBody.velocity.copy(velocity);
  83521. };
  83522. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83523. impostor.physicsBody.angularVelocity.copy(velocity);
  83524. };
  83525. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83526. var v = impostor.physicsBody.velocity;
  83527. if (!v) {
  83528. return null;
  83529. }
  83530. return new BABYLON.Vector3(v.x, v.y, v.z);
  83531. };
  83532. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83533. var v = impostor.physicsBody.angularVelocity;
  83534. if (!v) {
  83535. return null;
  83536. }
  83537. return new BABYLON.Vector3(v.x, v.y, v.z);
  83538. };
  83539. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83540. impostor.physicsBody.mass = mass;
  83541. impostor.physicsBody.updateMassProperties();
  83542. };
  83543. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83544. return impostor.physicsBody.mass;
  83545. };
  83546. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83547. return impostor.physicsBody.material.friction;
  83548. };
  83549. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83550. impostor.physicsBody.material.friction = friction;
  83551. };
  83552. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83553. return impostor.physicsBody.material.restitution;
  83554. };
  83555. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83556. impostor.physicsBody.material.restitution = restitution;
  83557. };
  83558. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83559. impostor.physicsBody.sleep();
  83560. };
  83561. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83562. impostor.physicsBody.wakeUp();
  83563. };
  83564. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83565. joint.physicsJoint.distance = maxDistance;
  83566. };
  83567. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83568. // if (!motorIndex) {
  83569. // joint.physicsJoint.enableMotor();
  83570. // }
  83571. // }
  83572. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83573. // if (!motorIndex) {
  83574. // joint.physicsJoint.disableMotor();
  83575. // }
  83576. // }
  83577. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83578. if (!motorIndex) {
  83579. joint.physicsJoint.enableMotor();
  83580. joint.physicsJoint.setMotorSpeed(speed);
  83581. if (maxForce) {
  83582. this.setLimit(joint, maxForce);
  83583. }
  83584. }
  83585. };
  83586. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83587. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83588. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83589. };
  83590. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83591. var body = impostor.physicsBody;
  83592. mesh.position.x = body.position.x;
  83593. mesh.position.y = body.position.y;
  83594. mesh.position.z = body.position.z;
  83595. if (mesh.rotationQuaternion) {
  83596. mesh.rotationQuaternion.x = body.quaternion.x;
  83597. mesh.rotationQuaternion.y = body.quaternion.y;
  83598. mesh.rotationQuaternion.z = body.quaternion.z;
  83599. mesh.rotationQuaternion.w = body.quaternion.w;
  83600. }
  83601. };
  83602. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83603. var shape = impostor.physicsBody.shapes[0];
  83604. return shape.boundingSphereRadius;
  83605. };
  83606. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83607. var shape = impostor.physicsBody.shapes[0];
  83608. result.x = shape.halfExtents.x * 2;
  83609. result.y = shape.halfExtents.y * 2;
  83610. result.z = shape.halfExtents.z * 2;
  83611. };
  83612. CannonJSPlugin.prototype.dispose = function () {
  83613. };
  83614. CannonJSPlugin.prototype._extendNamespace = function () {
  83615. //this will force cannon to execute at least one step when using interpolation
  83616. var step_tmp1 = new this.BJSCANNON.Vec3();
  83617. var Engine = this.BJSCANNON;
  83618. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83619. maxSubSteps = maxSubSteps || 10;
  83620. timeSinceLastCalled = timeSinceLastCalled || 0;
  83621. if (timeSinceLastCalled === 0) {
  83622. this.internalStep(dt);
  83623. this.time += dt;
  83624. }
  83625. else {
  83626. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83627. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83628. var t0 = performance.now();
  83629. for (var i = 0; i !== internalSteps; i++) {
  83630. this.internalStep(dt);
  83631. if (performance.now() - t0 > dt * 1000) {
  83632. break;
  83633. }
  83634. }
  83635. this.time += timeSinceLastCalled;
  83636. var h = this.time % dt;
  83637. var h_div_dt = h / dt;
  83638. var interpvelo = step_tmp1;
  83639. var bodies = this.bodies;
  83640. for (var j = 0; j !== bodies.length; j++) {
  83641. var b = bodies[j];
  83642. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83643. b.position.vsub(b.previousPosition, interpvelo);
  83644. interpvelo.scale(h_div_dt, interpvelo);
  83645. b.position.vadd(interpvelo, b.interpolatedPosition);
  83646. }
  83647. else {
  83648. b.interpolatedPosition.copy(b.position);
  83649. b.interpolatedQuaternion.copy(b.quaternion);
  83650. }
  83651. }
  83652. }
  83653. };
  83654. };
  83655. return CannonJSPlugin;
  83656. }());
  83657. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83658. })(BABYLON || (BABYLON = {}));
  83659. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83660. var BABYLON;
  83661. (function (BABYLON) {
  83662. var OimoJSPlugin = /** @class */ (function () {
  83663. function OimoJSPlugin(iterations) {
  83664. this.name = "OimoJSPlugin";
  83665. this._tmpImpostorsArray = [];
  83666. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83667. this.BJSOIMO = OIMO;
  83668. this.world = new this.BJSOIMO.World({
  83669. iterations: iterations
  83670. });
  83671. this.world.clear();
  83672. }
  83673. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83674. this.world.gravity.copy(gravity);
  83675. };
  83676. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83677. this.world.timeStep = timeStep;
  83678. };
  83679. OimoJSPlugin.prototype.getTimeStep = function () {
  83680. return this.world.timeStep;
  83681. };
  83682. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83683. var _this = this;
  83684. impostors.forEach(function (impostor) {
  83685. impostor.beforeStep();
  83686. });
  83687. this.world.step();
  83688. impostors.forEach(function (impostor) {
  83689. impostor.afterStep();
  83690. //update the ordered impostors array
  83691. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83692. });
  83693. //check for collisions
  83694. var contact = this.world.contacts;
  83695. while (contact !== null) {
  83696. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83697. contact = contact.next;
  83698. continue;
  83699. }
  83700. //is this body colliding with any other? get the impostor
  83701. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83702. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83703. if (!mainImpostor || !collidingImpostor) {
  83704. contact = contact.next;
  83705. continue;
  83706. }
  83707. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83708. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83709. contact = contact.next;
  83710. }
  83711. };
  83712. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83713. var mass = impostor.physicsBody.mass;
  83714. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83715. };
  83716. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83717. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83718. this.applyImpulse(impostor, force, contactPoint);
  83719. };
  83720. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83721. var _this = this;
  83722. //parent-child relationship. Does this impostor has a parent impostor?
  83723. if (impostor.parent) {
  83724. if (impostor.physicsBody) {
  83725. this.removePhysicsBody(impostor);
  83726. //TODO is that needed?
  83727. impostor.forceUpdate();
  83728. }
  83729. return;
  83730. }
  83731. if (impostor.isBodyInitRequired()) {
  83732. var bodyConfig = {
  83733. name: impostor.uniqueId,
  83734. //Oimo must have mass, also for static objects.
  83735. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83736. size: [],
  83737. type: [],
  83738. pos: [],
  83739. posShape: [],
  83740. rot: [],
  83741. rotShape: [],
  83742. move: impostor.getParam("mass") !== 0,
  83743. density: impostor.getParam("mass"),
  83744. friction: impostor.getParam("friction"),
  83745. restitution: impostor.getParam("restitution"),
  83746. //Supporting older versions of Oimo
  83747. world: this.world
  83748. };
  83749. var impostors = [impostor];
  83750. var addToArray = function (parent) {
  83751. if (!parent.getChildMeshes)
  83752. return;
  83753. parent.getChildMeshes().forEach(function (m) {
  83754. if (m.physicsImpostor) {
  83755. impostors.push(m.physicsImpostor);
  83756. //m.physicsImpostor._init();
  83757. }
  83758. });
  83759. };
  83760. addToArray(impostor.object);
  83761. var checkWithEpsilon_1 = function (value) {
  83762. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83763. };
  83764. impostors.forEach(function (i) {
  83765. if (!i.object.rotationQuaternion) {
  83766. return;
  83767. }
  83768. //get the correct bounding box
  83769. var oldQuaternion = i.object.rotationQuaternion;
  83770. var rot = oldQuaternion.toEulerAngles();
  83771. var extendSize = i.getObjectExtendSize();
  83772. var radToDeg = 57.295779513082320876;
  83773. if (i === impostor) {
  83774. var center = impostor.getObjectCenter();
  83775. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83776. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83777. //Can also use Array.prototype.push.apply
  83778. bodyConfig.pos.push(center.x);
  83779. bodyConfig.pos.push(center.y);
  83780. bodyConfig.pos.push(center.z);
  83781. bodyConfig.posShape.push(0, 0, 0);
  83782. //tmp solution
  83783. bodyConfig.rot.push(rot.x * radToDeg);
  83784. bodyConfig.rot.push(rot.y * radToDeg);
  83785. bodyConfig.rot.push(rot.z * radToDeg);
  83786. bodyConfig.rotShape.push(0, 0, 0);
  83787. }
  83788. else {
  83789. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83790. bodyConfig.posShape.push(localPosition.x);
  83791. bodyConfig.posShape.push(localPosition.y);
  83792. bodyConfig.posShape.push(localPosition.z);
  83793. bodyConfig.pos.push(0, 0, 0);
  83794. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83795. bodyConfig.rot.push(0);
  83796. bodyConfig.rot.push(0);
  83797. bodyConfig.rot.push(0);
  83798. bodyConfig.rotShape.push(rot.x * radToDeg);
  83799. bodyConfig.rotShape.push(rot.y * radToDeg);
  83800. bodyConfig.rotShape.push(rot.z * radToDeg);
  83801. }
  83802. // register mesh
  83803. switch (i.type) {
  83804. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83805. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83806. case BABYLON.PhysicsImpostor.SphereImpostor:
  83807. var radiusX = extendSize.x;
  83808. var radiusY = extendSize.y;
  83809. var radiusZ = extendSize.z;
  83810. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83811. bodyConfig.type.push('sphere');
  83812. //due to the way oimo works with compounds, add 3 times
  83813. bodyConfig.size.push(size);
  83814. bodyConfig.size.push(size);
  83815. bodyConfig.size.push(size);
  83816. break;
  83817. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83818. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83819. var sizeY = checkWithEpsilon_1(extendSize.y);
  83820. bodyConfig.type.push('cylinder');
  83821. bodyConfig.size.push(sizeX);
  83822. bodyConfig.size.push(sizeY);
  83823. //due to the way oimo works with compounds, add one more value.
  83824. bodyConfig.size.push(sizeY);
  83825. break;
  83826. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83827. case BABYLON.PhysicsImpostor.BoxImpostor:
  83828. default:
  83829. var sizeX = checkWithEpsilon_1(extendSize.x);
  83830. var sizeY = checkWithEpsilon_1(extendSize.y);
  83831. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83832. bodyConfig.type.push('box');
  83833. //if (i === impostor) {
  83834. bodyConfig.size.push(sizeX);
  83835. bodyConfig.size.push(sizeY);
  83836. bodyConfig.size.push(sizeZ);
  83837. //} else {
  83838. // bodyConfig.size.push(0,0,0);
  83839. //}
  83840. break;
  83841. }
  83842. //actually not needed, but hey...
  83843. i.object.rotationQuaternion = oldQuaternion;
  83844. });
  83845. impostor.physicsBody = this.world.add(bodyConfig);
  83846. }
  83847. else {
  83848. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83849. }
  83850. impostor.setDeltaPosition(this._tmpPositionVector);
  83851. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83852. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83853. };
  83854. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83855. //impostor.physicsBody.dispose();
  83856. //Same as : (older oimo versions)
  83857. this.world.removeRigidBody(impostor.physicsBody);
  83858. };
  83859. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83860. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83861. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83862. if (!mainBody || !connectedBody) {
  83863. return;
  83864. }
  83865. var jointData = impostorJoint.joint.jointData;
  83866. var options = jointData.nativeParams || {};
  83867. var type;
  83868. var nativeJointData = {
  83869. body1: mainBody,
  83870. body2: connectedBody,
  83871. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83872. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83873. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83874. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83875. min: options.min,
  83876. max: options.max,
  83877. collision: options.collision || jointData.collision,
  83878. spring: options.spring,
  83879. //supporting older version of Oimo
  83880. world: this.world
  83881. };
  83882. switch (impostorJoint.joint.type) {
  83883. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83884. type = "jointBall";
  83885. break;
  83886. case BABYLON.PhysicsJoint.SpringJoint:
  83887. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83888. var springData = jointData;
  83889. nativeJointData.min = springData.length || nativeJointData.min;
  83890. //Max should also be set, just make sure it is at least min
  83891. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83892. case BABYLON.PhysicsJoint.DistanceJoint:
  83893. type = "jointDistance";
  83894. nativeJointData.max = jointData.maxDistance;
  83895. break;
  83896. case BABYLON.PhysicsJoint.PrismaticJoint:
  83897. type = "jointPrisme";
  83898. break;
  83899. case BABYLON.PhysicsJoint.SliderJoint:
  83900. type = "jointSlide";
  83901. break;
  83902. case BABYLON.PhysicsJoint.WheelJoint:
  83903. type = "jointWheel";
  83904. break;
  83905. case BABYLON.PhysicsJoint.HingeJoint:
  83906. default:
  83907. type = "jointHinge";
  83908. break;
  83909. }
  83910. nativeJointData.type = type;
  83911. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83912. };
  83913. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83914. //Bug in Oimo prevents us from disposing a joint in the playground
  83915. //joint.joint.physicsJoint.dispose();
  83916. //So we will bruteforce it!
  83917. try {
  83918. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83919. }
  83920. catch (e) {
  83921. BABYLON.Tools.Warn(e);
  83922. }
  83923. };
  83924. OimoJSPlugin.prototype.isSupported = function () {
  83925. return this.BJSOIMO !== undefined;
  83926. };
  83927. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83928. if (!impostor.physicsBody.sleeping) {
  83929. //TODO check that
  83930. /*if (impostor.physicsBody.shapes.next) {
  83931. var parentShape = this._getLastShape(impostor.physicsBody);
  83932. impostor.object.position.copyFrom(parentShape.position);
  83933. console.log(parentShape.position);
  83934. } else {*/
  83935. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83936. //}
  83937. if (impostor.object.rotationQuaternion) {
  83938. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83939. }
  83940. }
  83941. };
  83942. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83943. var body = impostor.physicsBody;
  83944. body.position.copy(newPosition);
  83945. body.orientation.copy(newRotation);
  83946. body.syncShapes();
  83947. body.awake();
  83948. };
  83949. /*private _getLastShape(body: any): any {
  83950. var lastShape = body.shapes;
  83951. while (lastShape.next) {
  83952. lastShape = lastShape.next;
  83953. }
  83954. return lastShape;
  83955. }*/
  83956. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83957. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83958. };
  83959. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83960. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83961. };
  83962. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83963. var v = impostor.physicsBody.linearVelocity;
  83964. if (!v) {
  83965. return null;
  83966. }
  83967. return new BABYLON.Vector3(v.x, v.y, v.z);
  83968. };
  83969. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83970. var v = impostor.physicsBody.angularVelocity;
  83971. if (!v) {
  83972. return null;
  83973. }
  83974. return new BABYLON.Vector3(v.x, v.y, v.z);
  83975. };
  83976. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83977. var staticBody = mass === 0;
  83978. //this will actually set the body's density and not its mass.
  83979. //But this is how oimo treats the mass variable.
  83980. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83981. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83982. };
  83983. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83984. return impostor.physicsBody.shapes.density;
  83985. };
  83986. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83987. return impostor.physicsBody.shapes.friction;
  83988. };
  83989. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83990. impostor.physicsBody.shapes.friction = friction;
  83991. };
  83992. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83993. return impostor.physicsBody.shapes.restitution;
  83994. };
  83995. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83996. impostor.physicsBody.shapes.restitution = restitution;
  83997. };
  83998. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83999. impostor.physicsBody.sleep();
  84000. };
  84001. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84002. impostor.physicsBody.awake();
  84003. };
  84004. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84005. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84006. if (minDistance !== void 0) {
  84007. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84008. }
  84009. };
  84010. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84011. //TODO separate rotational and transational motors.
  84012. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84013. if (motor) {
  84014. motor.setMotor(speed, maxForce);
  84015. }
  84016. };
  84017. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84018. //TODO separate rotational and transational motors.
  84019. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84020. if (motor) {
  84021. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84022. }
  84023. };
  84024. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84025. var body = impostor.physicsBody;
  84026. mesh.position.x = body.position.x;
  84027. mesh.position.y = body.position.y;
  84028. mesh.position.z = body.position.z;
  84029. if (mesh.rotationQuaternion) {
  84030. mesh.rotationQuaternion.x = body.orientation.x;
  84031. mesh.rotationQuaternion.y = body.orientation.y;
  84032. mesh.rotationQuaternion.z = body.orientation.z;
  84033. mesh.rotationQuaternion.w = body.orientation.s;
  84034. }
  84035. };
  84036. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84037. return impostor.physicsBody.shapes.radius;
  84038. };
  84039. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84040. var shape = impostor.physicsBody.shapes;
  84041. result.x = shape.halfWidth * 2;
  84042. result.y = shape.halfHeight * 2;
  84043. result.z = shape.halfDepth * 2;
  84044. };
  84045. OimoJSPlugin.prototype.dispose = function () {
  84046. this.world.clear();
  84047. };
  84048. return OimoJSPlugin;
  84049. }());
  84050. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84051. })(BABYLON || (BABYLON = {}));
  84052. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84053. var BABYLON;
  84054. (function (BABYLON) {
  84055. /*
  84056. * Based on jsTGALoader - Javascript loader for TGA file
  84057. * By Vincent Thibault
  84058. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84059. */
  84060. var TGATools = /** @class */ (function () {
  84061. function TGATools() {
  84062. }
  84063. TGATools.GetTGAHeader = function (data) {
  84064. var offset = 0;
  84065. var header = {
  84066. id_length: data[offset++],
  84067. colormap_type: data[offset++],
  84068. image_type: data[offset++],
  84069. colormap_index: data[offset++] | data[offset++] << 8,
  84070. colormap_length: data[offset++] | data[offset++] << 8,
  84071. colormap_size: data[offset++],
  84072. origin: [
  84073. data[offset++] | data[offset++] << 8,
  84074. data[offset++] | data[offset++] << 8
  84075. ],
  84076. width: data[offset++] | data[offset++] << 8,
  84077. height: data[offset++] | data[offset++] << 8,
  84078. pixel_size: data[offset++],
  84079. flags: data[offset++]
  84080. };
  84081. return header;
  84082. };
  84083. TGATools.UploadContent = function (gl, data) {
  84084. // Not enough data to contain header ?
  84085. if (data.length < 19) {
  84086. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84087. return;
  84088. }
  84089. // Read Header
  84090. var offset = 18;
  84091. var header = TGATools.GetTGAHeader(data);
  84092. // Assume it's a valid Targa file.
  84093. if (header.id_length + offset > data.length) {
  84094. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84095. return;
  84096. }
  84097. // Skip not needed data
  84098. offset += header.id_length;
  84099. var use_rle = false;
  84100. var use_pal = false;
  84101. var use_grey = false;
  84102. // Get some informations.
  84103. switch (header.image_type) {
  84104. case TGATools._TYPE_RLE_INDEXED:
  84105. use_rle = true;
  84106. case TGATools._TYPE_INDEXED:
  84107. use_pal = true;
  84108. break;
  84109. case TGATools._TYPE_RLE_RGB:
  84110. use_rle = true;
  84111. case TGATools._TYPE_RGB:
  84112. // use_rgb = true;
  84113. break;
  84114. case TGATools._TYPE_RLE_GREY:
  84115. use_rle = true;
  84116. case TGATools._TYPE_GREY:
  84117. use_grey = true;
  84118. break;
  84119. }
  84120. var pixel_data;
  84121. // var numAlphaBits = header.flags & 0xf;
  84122. var pixel_size = header.pixel_size >> 3;
  84123. var pixel_total = header.width * header.height * pixel_size;
  84124. // Read palettes
  84125. var palettes;
  84126. if (use_pal) {
  84127. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84128. }
  84129. // Read LRE
  84130. if (use_rle) {
  84131. pixel_data = new Uint8Array(pixel_total);
  84132. var c, count, i;
  84133. var localOffset = 0;
  84134. var pixels = new Uint8Array(pixel_size);
  84135. while (offset < pixel_total && localOffset < pixel_total) {
  84136. c = data[offset++];
  84137. count = (c & 0x7f) + 1;
  84138. // RLE pixels
  84139. if (c & 0x80) {
  84140. // Bind pixel tmp array
  84141. for (i = 0; i < pixel_size; ++i) {
  84142. pixels[i] = data[offset++];
  84143. }
  84144. // Copy pixel array
  84145. for (i = 0; i < count; ++i) {
  84146. pixel_data.set(pixels, localOffset + i * pixel_size);
  84147. }
  84148. localOffset += pixel_size * count;
  84149. }
  84150. // Raw pixels
  84151. else {
  84152. count *= pixel_size;
  84153. for (i = 0; i < count; ++i) {
  84154. pixel_data[localOffset + i] = data[offset++];
  84155. }
  84156. localOffset += count;
  84157. }
  84158. }
  84159. }
  84160. // RAW Pixels
  84161. else {
  84162. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84163. }
  84164. // Load to texture
  84165. var x_start, y_start, x_step, y_step, y_end, x_end;
  84166. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84167. default:
  84168. case TGATools._ORIGIN_UL:
  84169. x_start = 0;
  84170. x_step = 1;
  84171. x_end = header.width;
  84172. y_start = 0;
  84173. y_step = 1;
  84174. y_end = header.height;
  84175. break;
  84176. case TGATools._ORIGIN_BL:
  84177. x_start = 0;
  84178. x_step = 1;
  84179. x_end = header.width;
  84180. y_start = header.height - 1;
  84181. y_step = -1;
  84182. y_end = -1;
  84183. break;
  84184. case TGATools._ORIGIN_UR:
  84185. x_start = header.width - 1;
  84186. x_step = -1;
  84187. x_end = -1;
  84188. y_start = 0;
  84189. y_step = 1;
  84190. y_end = header.height;
  84191. break;
  84192. case TGATools._ORIGIN_BR:
  84193. x_start = header.width - 1;
  84194. x_step = -1;
  84195. x_end = -1;
  84196. y_start = header.height - 1;
  84197. y_step = -1;
  84198. y_end = -1;
  84199. break;
  84200. }
  84201. // Load the specify method
  84202. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84203. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84204. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84205. };
  84206. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84207. var image = pixel_data, colormap = palettes;
  84208. var width = header.width, height = header.height;
  84209. var color, i = 0, x, y;
  84210. var imageData = new Uint8Array(width * height * 4);
  84211. for (y = y_start; y !== y_end; y += y_step) {
  84212. for (x = x_start; x !== x_end; x += x_step, i++) {
  84213. color = image[i];
  84214. imageData[(x + width * y) * 4 + 3] = 255;
  84215. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84216. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84217. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84218. }
  84219. }
  84220. return imageData;
  84221. };
  84222. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84223. var image = pixel_data;
  84224. var width = header.width, height = header.height;
  84225. var color, i = 0, x, y;
  84226. var imageData = new Uint8Array(width * height * 4);
  84227. for (y = y_start; y !== y_end; y += y_step) {
  84228. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84229. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84230. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84231. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84232. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84233. imageData[(x + width * y) * 4 + 0] = r;
  84234. imageData[(x + width * y) * 4 + 1] = g;
  84235. imageData[(x + width * y) * 4 + 2] = b;
  84236. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84237. }
  84238. }
  84239. return imageData;
  84240. };
  84241. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84242. var image = pixel_data;
  84243. var width = header.width, height = header.height;
  84244. var i = 0, x, y;
  84245. var imageData = new Uint8Array(width * height * 4);
  84246. for (y = y_start; y !== y_end; y += y_step) {
  84247. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84248. imageData[(x + width * y) * 4 + 3] = 255;
  84249. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84250. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84251. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84252. }
  84253. }
  84254. return imageData;
  84255. };
  84256. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84257. var image = pixel_data;
  84258. var width = header.width, height = header.height;
  84259. var i = 0, x, y;
  84260. var imageData = new Uint8Array(width * height * 4);
  84261. for (y = y_start; y !== y_end; y += y_step) {
  84262. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84263. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84264. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84265. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84266. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84267. }
  84268. }
  84269. return imageData;
  84270. };
  84271. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84272. var image = pixel_data;
  84273. var width = header.width, height = header.height;
  84274. var color, i = 0, x, y;
  84275. var imageData = new Uint8Array(width * height * 4);
  84276. for (y = y_start; y !== y_end; y += y_step) {
  84277. for (x = x_start; x !== x_end; x += x_step, i++) {
  84278. color = image[i];
  84279. imageData[(x + width * y) * 4 + 0] = color;
  84280. imageData[(x + width * y) * 4 + 1] = color;
  84281. imageData[(x + width * y) * 4 + 2] = color;
  84282. imageData[(x + width * y) * 4 + 3] = 255;
  84283. }
  84284. }
  84285. return imageData;
  84286. };
  84287. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84288. var image = pixel_data;
  84289. var width = header.width, height = header.height;
  84290. var i = 0, x, y;
  84291. var imageData = new Uint8Array(width * height * 4);
  84292. for (y = y_start; y !== y_end; y += y_step) {
  84293. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84294. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84295. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84296. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84297. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84298. }
  84299. }
  84300. return imageData;
  84301. };
  84302. //private static _TYPE_NO_DATA = 0;
  84303. TGATools._TYPE_INDEXED = 1;
  84304. TGATools._TYPE_RGB = 2;
  84305. TGATools._TYPE_GREY = 3;
  84306. TGATools._TYPE_RLE_INDEXED = 9;
  84307. TGATools._TYPE_RLE_RGB = 10;
  84308. TGATools._TYPE_RLE_GREY = 11;
  84309. TGATools._ORIGIN_MASK = 0x30;
  84310. TGATools._ORIGIN_SHIFT = 0x04;
  84311. TGATools._ORIGIN_BL = 0x00;
  84312. TGATools._ORIGIN_BR = 0x01;
  84313. TGATools._ORIGIN_UL = 0x02;
  84314. TGATools._ORIGIN_UR = 0x03;
  84315. return TGATools;
  84316. }());
  84317. BABYLON.TGATools = TGATools;
  84318. })(BABYLON || (BABYLON = {}));
  84319. //# sourceMappingURL=babylon.tga.js.map
  84320. var BABYLON;
  84321. (function (BABYLON) {
  84322. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84323. // All values and structures referenced from:
  84324. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84325. var DDS_MAGIC = 0x20534444;
  84326. var
  84327. //DDSD_CAPS = 0x1,
  84328. //DDSD_HEIGHT = 0x2,
  84329. //DDSD_WIDTH = 0x4,
  84330. //DDSD_PITCH = 0x8,
  84331. //DDSD_PIXELFORMAT = 0x1000,
  84332. DDSD_MIPMAPCOUNT = 0x20000;
  84333. //DDSD_LINEARSIZE = 0x80000,
  84334. //DDSD_DEPTH = 0x800000;
  84335. // var DDSCAPS_COMPLEX = 0x8,
  84336. // DDSCAPS_MIPMAP = 0x400000,
  84337. // DDSCAPS_TEXTURE = 0x1000;
  84338. var DDSCAPS2_CUBEMAP = 0x200;
  84339. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84340. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84341. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84342. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84343. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84344. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84345. // DDSCAPS2_VOLUME = 0x200000;
  84346. var
  84347. //DDPF_ALPHAPIXELS = 0x1,
  84348. //DDPF_ALPHA = 0x2,
  84349. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84350. //DDPF_YUV = 0x200,
  84351. DDPF_LUMINANCE = 0x20000;
  84352. function FourCCToInt32(value) {
  84353. return value.charCodeAt(0) +
  84354. (value.charCodeAt(1) << 8) +
  84355. (value.charCodeAt(2) << 16) +
  84356. (value.charCodeAt(3) << 24);
  84357. }
  84358. function Int32ToFourCC(value) {
  84359. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84360. }
  84361. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84362. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84363. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84364. var FOURCC_DX10 = FourCCToInt32("DX10");
  84365. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84366. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84367. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84368. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84369. var headerLengthInt = 31; // The header length in 32 bit ints
  84370. // Offsets into the header array
  84371. var off_magic = 0;
  84372. var off_size = 1;
  84373. var off_flags = 2;
  84374. var off_height = 3;
  84375. var off_width = 4;
  84376. var off_mipmapCount = 7;
  84377. var off_pfFlags = 20;
  84378. var off_pfFourCC = 21;
  84379. var off_RGBbpp = 22;
  84380. var off_RMask = 23;
  84381. var off_GMask = 24;
  84382. var off_BMask = 25;
  84383. var off_AMask = 26;
  84384. // var off_caps1 = 27;
  84385. var off_caps2 = 28;
  84386. // var off_caps3 = 29;
  84387. // var off_caps4 = 30;
  84388. var off_dxgiFormat = 32;
  84389. ;
  84390. var DDSTools = /** @class */ (function () {
  84391. function DDSTools() {
  84392. }
  84393. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84394. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84395. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84396. var mipmapCount = 1;
  84397. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84398. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84399. }
  84400. var fourCC = header[off_pfFourCC];
  84401. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84402. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84403. switch (fourCC) {
  84404. case FOURCC_D3DFMT_R16G16B16A16F:
  84405. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84406. break;
  84407. case FOURCC_D3DFMT_R32G32B32A32F:
  84408. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84409. break;
  84410. case FOURCC_DX10:
  84411. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84412. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84413. break;
  84414. }
  84415. }
  84416. return {
  84417. width: header[off_width],
  84418. height: header[off_height],
  84419. mipmapCount: mipmapCount,
  84420. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84421. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84422. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84423. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84424. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84425. dxgiFormat: dxgiFormat,
  84426. textureType: textureType
  84427. };
  84428. };
  84429. DDSTools._ToHalfFloat = function (value) {
  84430. if (!DDSTools._FloatView) {
  84431. DDSTools._FloatView = new Float32Array(1);
  84432. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84433. }
  84434. DDSTools._FloatView[0] = value;
  84435. var x = DDSTools._Int32View[0];
  84436. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84437. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84438. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84439. /* If zero, or denormal, or exponent underflows too much for a denormal
  84440. * half, return signed zero. */
  84441. if (e < 103) {
  84442. return bits;
  84443. }
  84444. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84445. if (e > 142) {
  84446. bits |= 0x7c00;
  84447. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84448. * not Inf, so make sure we set one mantissa bit too. */
  84449. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84450. return bits;
  84451. }
  84452. /* If exponent underflows but not too much, return a denormal */
  84453. if (e < 113) {
  84454. m |= 0x0800;
  84455. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84456. * to 1, which is OK. */
  84457. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84458. return bits;
  84459. }
  84460. bits |= ((e - 112) << 10) | (m >> 1);
  84461. bits += m & 1;
  84462. return bits;
  84463. };
  84464. DDSTools._FromHalfFloat = function (value) {
  84465. var s = (value & 0x8000) >> 15;
  84466. var e = (value & 0x7C00) >> 10;
  84467. var f = value & 0x03FF;
  84468. if (e === 0) {
  84469. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84470. }
  84471. else if (e == 0x1F) {
  84472. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84473. }
  84474. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84475. };
  84476. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84477. var destArray = new Float32Array(dataLength);
  84478. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84479. var index = 0;
  84480. for (var y = 0; y < height; y++) {
  84481. for (var x = 0; x < width; x++) {
  84482. var srcPos = (x + y * width) * 4;
  84483. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84484. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84485. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84486. if (DDSTools.StoreLODInAlphaChannel) {
  84487. destArray[index + 3] = lod;
  84488. }
  84489. else {
  84490. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84491. }
  84492. index += 4;
  84493. }
  84494. }
  84495. return destArray;
  84496. };
  84497. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84498. if (DDSTools.StoreLODInAlphaChannel) {
  84499. var destArray = new Uint16Array(dataLength);
  84500. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84501. var index = 0;
  84502. for (var y = 0; y < height; y++) {
  84503. for (var x = 0; x < width; x++) {
  84504. var srcPos = (x + y * width) * 4;
  84505. destArray[index] = srcData[srcPos];
  84506. destArray[index + 1] = srcData[srcPos + 1];
  84507. destArray[index + 2] = srcData[srcPos + 2];
  84508. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84509. index += 4;
  84510. }
  84511. }
  84512. return destArray;
  84513. }
  84514. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84515. };
  84516. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84517. if (DDSTools.StoreLODInAlphaChannel) {
  84518. var destArray = new Float32Array(dataLength);
  84519. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84520. var index = 0;
  84521. for (var y = 0; y < height; y++) {
  84522. for (var x = 0; x < width; x++) {
  84523. var srcPos = (x + y * width) * 4;
  84524. destArray[index] = srcData[srcPos];
  84525. destArray[index + 1] = srcData[srcPos + 1];
  84526. destArray[index + 2] = srcData[srcPos + 2];
  84527. destArray[index + 3] = lod;
  84528. index += 4;
  84529. }
  84530. }
  84531. return destArray;
  84532. }
  84533. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84534. };
  84535. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84536. var destArray = new Uint8Array(dataLength);
  84537. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84538. var index = 0;
  84539. for (var y = 0; y < height; y++) {
  84540. for (var x = 0; x < width; x++) {
  84541. var srcPos = (x + y * width) * 4;
  84542. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84543. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84544. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84545. if (DDSTools.StoreLODInAlphaChannel) {
  84546. destArray[index + 3] = lod;
  84547. }
  84548. else {
  84549. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84550. }
  84551. index += 4;
  84552. }
  84553. }
  84554. return destArray;
  84555. };
  84556. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84557. var destArray = new Uint8Array(dataLength);
  84558. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84559. var index = 0;
  84560. for (var y = 0; y < height; y++) {
  84561. for (var x = 0; x < width; x++) {
  84562. var srcPos = (x + y * width) * 4;
  84563. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84564. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84565. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84566. if (DDSTools.StoreLODInAlphaChannel) {
  84567. destArray[index + 3] = lod;
  84568. }
  84569. else {
  84570. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84571. }
  84572. index += 4;
  84573. }
  84574. }
  84575. return destArray;
  84576. };
  84577. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84578. var byteArray = new Uint8Array(dataLength);
  84579. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84580. var index = 0;
  84581. for (var y = 0; y < height; y++) {
  84582. for (var x = 0; x < width; x++) {
  84583. var srcPos = (x + y * width) * 4;
  84584. byteArray[index] = srcData[srcPos + rOffset];
  84585. byteArray[index + 1] = srcData[srcPos + gOffset];
  84586. byteArray[index + 2] = srcData[srcPos + bOffset];
  84587. byteArray[index + 3] = srcData[srcPos + aOffset];
  84588. index += 4;
  84589. }
  84590. }
  84591. return byteArray;
  84592. };
  84593. DDSTools._ExtractLongWordOrder = function (value) {
  84594. if (value === 0 || value === 255 || value === -16777216) {
  84595. return 0;
  84596. }
  84597. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84598. };
  84599. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84600. var byteArray = new Uint8Array(dataLength);
  84601. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84602. var index = 0;
  84603. for (var y = 0; y < height; y++) {
  84604. for (var x = 0; x < width; x++) {
  84605. var srcPos = (x + y * width) * 3;
  84606. byteArray[index] = srcData[srcPos + rOffset];
  84607. byteArray[index + 1] = srcData[srcPos + gOffset];
  84608. byteArray[index + 2] = srcData[srcPos + bOffset];
  84609. index += 3;
  84610. }
  84611. }
  84612. return byteArray;
  84613. };
  84614. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84615. var byteArray = new Uint8Array(dataLength);
  84616. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84617. var index = 0;
  84618. for (var y = 0; y < height; y++) {
  84619. for (var x = 0; x < width; x++) {
  84620. var srcPos = (x + y * width);
  84621. byteArray[index] = srcData[srcPos];
  84622. index++;
  84623. }
  84624. }
  84625. return byteArray;
  84626. };
  84627. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84628. if (lodIndex === void 0) { lodIndex = -1; }
  84629. var sphericalPolynomialFaces = null;
  84630. if (info.sphericalPolynomial) {
  84631. sphericalPolynomialFaces = new Array();
  84632. }
  84633. var ext = engine.getCaps().s3tc;
  84634. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84635. var fourCC, width, height, dataLength = 0, dataOffset;
  84636. var byteArray, mipmapCount, mip;
  84637. var internalFormat = 0;
  84638. var format = 0;
  84639. var blockBytes = 1;
  84640. if (header[off_magic] !== DDS_MAGIC) {
  84641. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84642. return;
  84643. }
  84644. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84645. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84646. return;
  84647. }
  84648. if (info.isCompressed && !ext) {
  84649. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84650. return;
  84651. }
  84652. var bpp = header[off_RGBbpp];
  84653. dataOffset = header[off_size] + 4;
  84654. var computeFormats = false;
  84655. if (info.isFourCC) {
  84656. fourCC = header[off_pfFourCC];
  84657. switch (fourCC) {
  84658. case FOURCC_DXT1:
  84659. blockBytes = 8;
  84660. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84661. break;
  84662. case FOURCC_DXT3:
  84663. blockBytes = 16;
  84664. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84665. break;
  84666. case FOURCC_DXT5:
  84667. blockBytes = 16;
  84668. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84669. break;
  84670. case FOURCC_D3DFMT_R16G16B16A16F:
  84671. computeFormats = true;
  84672. break;
  84673. case FOURCC_D3DFMT_R32G32B32A32F:
  84674. computeFormats = true;
  84675. break;
  84676. case FOURCC_DX10:
  84677. // There is an additionnal header so dataOffset need to be changed
  84678. dataOffset += 5 * 4; // 5 uints
  84679. var supported = false;
  84680. switch (info.dxgiFormat) {
  84681. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84682. computeFormats = true;
  84683. supported = true;
  84684. break;
  84685. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84686. info.isRGB = true;
  84687. info.isFourCC = false;
  84688. bpp = 32;
  84689. supported = true;
  84690. break;
  84691. }
  84692. if (supported) {
  84693. break;
  84694. }
  84695. default:
  84696. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84697. return;
  84698. }
  84699. }
  84700. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84701. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84702. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84703. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84704. if (computeFormats) {
  84705. format = engine._getWebGLTextureType(info.textureType);
  84706. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84707. }
  84708. mipmapCount = 1;
  84709. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84710. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84711. }
  84712. for (var face = 0; face < faces; face++) {
  84713. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84714. width = header[off_width];
  84715. height = header[off_height];
  84716. for (mip = 0; mip < mipmapCount; ++mip) {
  84717. if (lodIndex === -1 || lodIndex === mip) {
  84718. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84719. var i = (lodIndex === -1) ? mip : 0;
  84720. if (!info.isCompressed && info.isFourCC) {
  84721. dataLength = width * height * 4;
  84722. var floatArray = null;
  84723. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84724. if (bpp === 128) {
  84725. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84726. if (sphericalPolynomialFaces && i == 0) {
  84727. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84728. }
  84729. }
  84730. else if (bpp === 64) {
  84731. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84732. if (sphericalPolynomialFaces && i == 0) {
  84733. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84734. }
  84735. }
  84736. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84737. format = engine._getWebGLTextureType(info.textureType);
  84738. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84739. }
  84740. else {
  84741. if (bpp === 128) {
  84742. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84743. if (sphericalPolynomialFaces && i == 0) {
  84744. sphericalPolynomialFaces.push(floatArray);
  84745. }
  84746. }
  84747. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84748. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84749. if (sphericalPolynomialFaces && i == 0) {
  84750. sphericalPolynomialFaces.push(floatArray);
  84751. }
  84752. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84753. format = engine._getWebGLTextureType(info.textureType);
  84754. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84755. }
  84756. else { // 64
  84757. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84758. if (sphericalPolynomialFaces && i == 0) {
  84759. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84760. }
  84761. }
  84762. }
  84763. if (floatArray) {
  84764. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84765. }
  84766. }
  84767. else if (info.isRGB) {
  84768. if (bpp === 24) {
  84769. dataLength = width * height * 3;
  84770. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84771. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84772. }
  84773. else { // 32
  84774. dataLength = width * height * 4;
  84775. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84776. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84777. }
  84778. }
  84779. else if (info.isLuminance) {
  84780. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84781. var unpaddedRowSize = width;
  84782. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84783. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84784. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84785. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84786. }
  84787. else {
  84788. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84789. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84790. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84791. }
  84792. }
  84793. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84794. width *= 0.5;
  84795. height *= 0.5;
  84796. width = Math.max(1.0, width);
  84797. height = Math.max(1.0, height);
  84798. }
  84799. if (currentFace !== undefined) {
  84800. // Loading a single face
  84801. break;
  84802. }
  84803. }
  84804. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84805. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84806. size: header[off_width],
  84807. right: sphericalPolynomialFaces[0],
  84808. left: sphericalPolynomialFaces[1],
  84809. up: sphericalPolynomialFaces[2],
  84810. down: sphericalPolynomialFaces[3],
  84811. front: sphericalPolynomialFaces[4],
  84812. back: sphericalPolynomialFaces[5],
  84813. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84814. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84815. gammaSpace: false,
  84816. });
  84817. }
  84818. else {
  84819. info.sphericalPolynomial = undefined;
  84820. }
  84821. };
  84822. DDSTools.StoreLODInAlphaChannel = false;
  84823. return DDSTools;
  84824. }());
  84825. BABYLON.DDSTools = DDSTools;
  84826. })(BABYLON || (BABYLON = {}));
  84827. //# sourceMappingURL=babylon.dds.js.map
  84828. var BABYLON;
  84829. (function (BABYLON) {
  84830. /**
  84831. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84832. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84833. */
  84834. var KhronosTextureContainer = /** @class */ (function () {
  84835. /**
  84836. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84837. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84838. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84839. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84840. */
  84841. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84842. this.arrayBuffer = arrayBuffer;
  84843. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84844. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84845. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84846. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84847. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84848. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84849. BABYLON.Tools.Error("texture missing KTX identifier");
  84850. return;
  84851. }
  84852. // load the reset of the header in native 32 bit int
  84853. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84854. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84855. var oppositeEndianess = header[0] === 0x01020304;
  84856. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84857. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84858. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84859. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84860. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84861. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84862. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84863. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84864. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84865. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84866. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84867. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84868. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84869. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84870. if (this.glType !== 0) {
  84871. BABYLON.Tools.Error("only compressed formats currently supported");
  84872. return;
  84873. }
  84874. else {
  84875. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84876. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84877. }
  84878. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84879. BABYLON.Tools.Error("only 2D textures currently supported");
  84880. return;
  84881. }
  84882. if (this.numberOfArrayElements !== 0) {
  84883. BABYLON.Tools.Error("texture arrays not currently supported");
  84884. return;
  84885. }
  84886. if (this.numberOfFaces !== facesExpected) {
  84887. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84888. return;
  84889. }
  84890. // we now have a completely validated file, so could use existence of loadType as success
  84891. // would need to make this more elaborate & adjust checks above to support more than one load type
  84892. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84893. }
  84894. // not as fast hardware based, but will probably never need to use
  84895. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84896. return ((val & 0xFF) << 24)
  84897. | ((val & 0xFF00) << 8)
  84898. | ((val >> 8) & 0xFF00)
  84899. | ((val >> 24) & 0xFF);
  84900. };
  84901. /**
  84902. * It is assumed that the texture has already been created & is currently bound
  84903. */
  84904. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84905. switch (this.loadType) {
  84906. case KhronosTextureContainer.COMPRESSED_2D:
  84907. this._upload2DCompressedLevels(gl, loadMipmaps);
  84908. break;
  84909. case KhronosTextureContainer.TEX_2D:
  84910. case KhronosTextureContainer.COMPRESSED_3D:
  84911. case KhronosTextureContainer.TEX_3D:
  84912. }
  84913. };
  84914. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84915. // initialize width & height for level 1
  84916. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84917. var width = this.pixelWidth;
  84918. var height = this.pixelHeight;
  84919. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84920. for (var level = 0; level < mipmapCount; level++) {
  84921. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84922. for (var face = 0; face < this.numberOfFaces; face++) {
  84923. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84924. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84925. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84926. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84927. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84928. }
  84929. width = Math.max(1.0, width * 0.5);
  84930. height = Math.max(1.0, height * 0.5);
  84931. }
  84932. };
  84933. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84934. // load types
  84935. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84936. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84937. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84938. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84939. return KhronosTextureContainer;
  84940. }());
  84941. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84942. })(BABYLON || (BABYLON = {}));
  84943. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84944. var BABYLON;
  84945. (function (BABYLON) {
  84946. var Debug;
  84947. (function (Debug) {
  84948. /**
  84949. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84950. */
  84951. var SkeletonViewer = /** @class */ (function () {
  84952. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84953. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84954. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84955. this.skeleton = skeleton;
  84956. this.mesh = mesh;
  84957. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84958. this.renderingGroupId = renderingGroupId;
  84959. this.color = BABYLON.Color3.White();
  84960. this._debugLines = new Array();
  84961. this._isEnabled = false;
  84962. this._scene = scene;
  84963. this.update();
  84964. this._renderFunction = this.update.bind(this);
  84965. }
  84966. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84967. get: function () {
  84968. return this._isEnabled;
  84969. },
  84970. set: function (value) {
  84971. if (this._isEnabled === value) {
  84972. return;
  84973. }
  84974. this._isEnabled = value;
  84975. if (value) {
  84976. this._scene.registerBeforeRender(this._renderFunction);
  84977. }
  84978. else {
  84979. this._scene.unregisterBeforeRender(this._renderFunction);
  84980. }
  84981. },
  84982. enumerable: true,
  84983. configurable: true
  84984. });
  84985. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84986. if (x === void 0) { x = 0; }
  84987. if (y === void 0) { y = 0; }
  84988. if (z === void 0) { z = 0; }
  84989. var tmat = BABYLON.Tmp.Matrix[0];
  84990. var parentBone = bone.getParent();
  84991. tmat.copyFrom(bone.getLocalMatrix());
  84992. if (x !== 0 || y !== 0 || z !== 0) {
  84993. var tmat2 = BABYLON.Tmp.Matrix[1];
  84994. BABYLON.Matrix.IdentityToRef(tmat2);
  84995. tmat2.m[12] = x;
  84996. tmat2.m[13] = y;
  84997. tmat2.m[14] = z;
  84998. tmat2.multiplyToRef(tmat, tmat);
  84999. }
  85000. if (parentBone) {
  85001. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85002. }
  85003. tmat.multiplyToRef(meshMat, tmat);
  85004. position.x = tmat.m[12];
  85005. position.y = tmat.m[13];
  85006. position.z = tmat.m[14];
  85007. };
  85008. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85009. var len = bones.length;
  85010. var meshPos = this.mesh.position;
  85011. for (var i = 0; i < len; i++) {
  85012. var bone = bones[i];
  85013. var points = this._debugLines[i];
  85014. if (!points) {
  85015. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85016. this._debugLines[i] = points;
  85017. }
  85018. this._getBonePosition(points[0], bone, meshMat);
  85019. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85020. points[0].subtractInPlace(meshPos);
  85021. points[1].subtractInPlace(meshPos);
  85022. }
  85023. };
  85024. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85025. var len = bones.length;
  85026. var boneNum = 0;
  85027. var meshPos = this.mesh.position;
  85028. for (var i = len - 1; i >= 0; i--) {
  85029. var childBone = bones[i];
  85030. var parentBone = childBone.getParent();
  85031. if (!parentBone) {
  85032. continue;
  85033. }
  85034. var points = this._debugLines[boneNum];
  85035. if (!points) {
  85036. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85037. this._debugLines[boneNum] = points;
  85038. }
  85039. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85040. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85041. points[0].subtractInPlace(meshPos);
  85042. points[1].subtractInPlace(meshPos);
  85043. boneNum++;
  85044. }
  85045. };
  85046. SkeletonViewer.prototype.update = function () {
  85047. if (this.autoUpdateBonesMatrices) {
  85048. this.skeleton.computeAbsoluteTransforms();
  85049. }
  85050. if (this.skeleton.bones[0].length === undefined) {
  85051. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85052. }
  85053. else {
  85054. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85055. }
  85056. if (!this._debugMesh) {
  85057. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85058. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85059. }
  85060. else {
  85061. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85062. }
  85063. this._debugMesh.position.copyFrom(this.mesh.position);
  85064. this._debugMesh.color = this.color;
  85065. };
  85066. SkeletonViewer.prototype.dispose = function () {
  85067. if (this._debugMesh) {
  85068. this.isEnabled = false;
  85069. this._debugMesh.dispose();
  85070. this._debugMesh = null;
  85071. }
  85072. };
  85073. return SkeletonViewer;
  85074. }());
  85075. Debug.SkeletonViewer = SkeletonViewer;
  85076. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85077. })(BABYLON || (BABYLON = {}));
  85078. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85079. /**
  85080. * Module Debug contains the (visual) components to debug a scene correctly
  85081. */
  85082. var BABYLON;
  85083. (function (BABYLON) {
  85084. var Debug;
  85085. (function (Debug) {
  85086. /**
  85087. * The Axes viewer will show 3 axes in a specific point in space
  85088. */
  85089. var AxesViewer = /** @class */ (function () {
  85090. function AxesViewer(scene, scaleLines) {
  85091. if (scaleLines === void 0) { scaleLines = 1; }
  85092. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85093. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85094. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85095. this.scaleLines = 1;
  85096. this.scaleLines = scaleLines;
  85097. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85098. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85099. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85100. this._xmesh.renderingGroupId = 2;
  85101. this._ymesh.renderingGroupId = 2;
  85102. this._zmesh.renderingGroupId = 2;
  85103. this._xmesh.material.checkReadyOnlyOnce = true;
  85104. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85105. this._ymesh.material.checkReadyOnlyOnce = true;
  85106. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85107. this._zmesh.material.checkReadyOnlyOnce = true;
  85108. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85109. this.scene = scene;
  85110. }
  85111. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85112. var scaleLines = this.scaleLines;
  85113. if (this._xmesh) {
  85114. this._xmesh.position.copyFrom(position);
  85115. }
  85116. if (this._ymesh) {
  85117. this._ymesh.position.copyFrom(position);
  85118. }
  85119. if (this._zmesh) {
  85120. this._zmesh.position.copyFrom(position);
  85121. }
  85122. var point2 = this._xline[1];
  85123. point2.x = xaxis.x * scaleLines;
  85124. point2.y = xaxis.y * scaleLines;
  85125. point2.z = xaxis.z * scaleLines;
  85126. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85127. point2 = this._yline[1];
  85128. point2.x = yaxis.x * scaleLines;
  85129. point2.y = yaxis.y * scaleLines;
  85130. point2.z = yaxis.z * scaleLines;
  85131. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85132. point2 = this._zline[1];
  85133. point2.x = zaxis.x * scaleLines;
  85134. point2.y = zaxis.y * scaleLines;
  85135. point2.z = zaxis.z * scaleLines;
  85136. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85137. };
  85138. AxesViewer.prototype.dispose = function () {
  85139. if (this._xmesh) {
  85140. this._xmesh.dispose();
  85141. }
  85142. if (this._ymesh) {
  85143. this._ymesh.dispose();
  85144. }
  85145. if (this._zmesh) {
  85146. this._zmesh.dispose();
  85147. }
  85148. this._xmesh = null;
  85149. this._ymesh = null;
  85150. this._zmesh = null;
  85151. this.scene = null;
  85152. };
  85153. return AxesViewer;
  85154. }());
  85155. Debug.AxesViewer = AxesViewer;
  85156. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85157. })(BABYLON || (BABYLON = {}));
  85158. //# sourceMappingURL=babylon.axesViewer.js.map
  85159. var BABYLON;
  85160. (function (BABYLON) {
  85161. var Debug;
  85162. (function (Debug) {
  85163. /**
  85164. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85165. */
  85166. var BoneAxesViewer = /** @class */ (function (_super) {
  85167. __extends(BoneAxesViewer, _super);
  85168. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85169. if (scaleLines === void 0) { scaleLines = 1; }
  85170. var _this = _super.call(this, scene, scaleLines) || this;
  85171. _this.pos = BABYLON.Vector3.Zero();
  85172. _this.xaxis = BABYLON.Vector3.Zero();
  85173. _this.yaxis = BABYLON.Vector3.Zero();
  85174. _this.zaxis = BABYLON.Vector3.Zero();
  85175. _this.mesh = mesh;
  85176. _this.bone = bone;
  85177. return _this;
  85178. }
  85179. BoneAxesViewer.prototype.update = function () {
  85180. if (!this.mesh || !this.bone) {
  85181. return;
  85182. }
  85183. var bone = this.bone;
  85184. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85185. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85186. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85187. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85188. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85189. };
  85190. BoneAxesViewer.prototype.dispose = function () {
  85191. if (this.mesh) {
  85192. this.mesh = null;
  85193. this.bone = null;
  85194. _super.prototype.dispose.call(this);
  85195. }
  85196. };
  85197. return BoneAxesViewer;
  85198. }(Debug.AxesViewer));
  85199. Debug.BoneAxesViewer = BoneAxesViewer;
  85200. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85201. })(BABYLON || (BABYLON = {}));
  85202. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85203. var BABYLON;
  85204. (function (BABYLON) {
  85205. var RayHelper = /** @class */ (function () {
  85206. function RayHelper(ray) {
  85207. this.ray = ray;
  85208. }
  85209. RayHelper.CreateAndShow = function (ray, scene, color) {
  85210. var helper = new RayHelper(ray);
  85211. helper.show(scene, color);
  85212. return helper;
  85213. };
  85214. RayHelper.prototype.show = function (scene, color) {
  85215. if (!this._renderFunction && this.ray) {
  85216. var ray = this.ray;
  85217. this._renderFunction = this._render.bind(this);
  85218. this._scene = scene;
  85219. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85220. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85221. if (this._renderFunction) {
  85222. this._scene.registerBeforeRender(this._renderFunction);
  85223. }
  85224. }
  85225. if (color && this._renderLine) {
  85226. this._renderLine.color.copyFrom(color);
  85227. }
  85228. };
  85229. RayHelper.prototype.hide = function () {
  85230. if (this._renderFunction && this._scene) {
  85231. this._scene.unregisterBeforeRender(this._renderFunction);
  85232. this._scene = null;
  85233. this._renderFunction = null;
  85234. if (this._renderLine) {
  85235. this._renderLine.dispose();
  85236. this._renderLine = null;
  85237. }
  85238. this._renderPoints = [];
  85239. }
  85240. };
  85241. RayHelper.prototype._render = function () {
  85242. var ray = this.ray;
  85243. if (!ray) {
  85244. return;
  85245. }
  85246. var point = this._renderPoints[1];
  85247. var len = Math.min(ray.length, 1000000);
  85248. point.copyFrom(ray.direction);
  85249. point.scaleInPlace(len);
  85250. point.addInPlace(ray.origin);
  85251. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85252. };
  85253. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85254. this._attachedToMesh = mesh;
  85255. var ray = this.ray;
  85256. if (!ray) {
  85257. return;
  85258. }
  85259. if (!ray.direction) {
  85260. ray.direction = BABYLON.Vector3.Zero();
  85261. }
  85262. if (!ray.origin) {
  85263. ray.origin = BABYLON.Vector3.Zero();
  85264. }
  85265. if (length) {
  85266. ray.length = length;
  85267. }
  85268. if (!meshSpaceOrigin) {
  85269. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85270. }
  85271. if (!meshSpaceDirection) {
  85272. // -1 so that this will work with Mesh.lookAt
  85273. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85274. }
  85275. if (!this._meshSpaceDirection) {
  85276. this._meshSpaceDirection = meshSpaceDirection.clone();
  85277. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85278. }
  85279. else {
  85280. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85281. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85282. }
  85283. if (!this._updateToMeshFunction) {
  85284. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85285. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85286. }
  85287. this._updateToMesh();
  85288. };
  85289. RayHelper.prototype.detachFromMesh = function () {
  85290. if (this._attachedToMesh) {
  85291. if (this._updateToMeshFunction) {
  85292. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85293. }
  85294. this._attachedToMesh = null;
  85295. this._updateToMeshFunction = null;
  85296. }
  85297. };
  85298. RayHelper.prototype._updateToMesh = function () {
  85299. var ray = this.ray;
  85300. if (!this._attachedToMesh || !ray) {
  85301. return;
  85302. }
  85303. if (this._attachedToMesh._isDisposed) {
  85304. this.detachFromMesh();
  85305. return;
  85306. }
  85307. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85308. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85309. };
  85310. RayHelper.prototype.dispose = function () {
  85311. this.hide();
  85312. this.detachFromMesh();
  85313. this.ray = null;
  85314. };
  85315. return RayHelper;
  85316. }());
  85317. BABYLON.RayHelper = RayHelper;
  85318. })(BABYLON || (BABYLON = {}));
  85319. //# sourceMappingURL=babylon.rayHelper.js.map
  85320. var BABYLON;
  85321. (function (BABYLON) {
  85322. // load the inspector using require, if not present in the global namespace.
  85323. var DebugLayer = /** @class */ (function () {
  85324. function DebugLayer(scene) {
  85325. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85326. this._scene = scene;
  85327. // load inspector using require, if it doesn't exist on the global namespace.
  85328. }
  85329. /** Creates the inspector window. */
  85330. DebugLayer.prototype._createInspector = function (config) {
  85331. if (config === void 0) { config = {}; }
  85332. var popup = config.popup || false;
  85333. var initialTab = config.initialTab || 0;
  85334. var parentElement = config.parentElement || null;
  85335. if (!this._inspector) {
  85336. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85337. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85338. } // else nothing to do,; instance is already existing
  85339. };
  85340. DebugLayer.prototype.isVisible = function () {
  85341. if (!this._inspector) {
  85342. return false;
  85343. }
  85344. return true;
  85345. };
  85346. DebugLayer.prototype.hide = function () {
  85347. if (this._inspector) {
  85348. try {
  85349. this._inspector.dispose();
  85350. }
  85351. catch (e) {
  85352. // If the inspector has been removed directly from the inspector tool
  85353. }
  85354. this._inspector = null;
  85355. }
  85356. };
  85357. DebugLayer.prototype.show = function (config) {
  85358. if (config === void 0) { config = {}; }
  85359. if (typeof this.BJSINSPECTOR == 'undefined') {
  85360. // Load inspector and add it to the DOM
  85361. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85362. }
  85363. else {
  85364. // Otherwise creates the inspector
  85365. this._createInspector(config);
  85366. }
  85367. };
  85368. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85369. return DebugLayer;
  85370. }());
  85371. BABYLON.DebugLayer = DebugLayer;
  85372. })(BABYLON || (BABYLON = {}));
  85373. //# sourceMappingURL=babylon.debugLayer.js.map
  85374. var BABYLON;
  85375. (function (BABYLON) {
  85376. var Debug;
  85377. (function (Debug) {
  85378. /**
  85379. * Used to show the physics impostor around the specific mesh.
  85380. */
  85381. var PhysicsViewer = /** @class */ (function () {
  85382. function PhysicsViewer(scene) {
  85383. this._impostors = [];
  85384. this._meshes = [];
  85385. this._numMeshes = 0;
  85386. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85387. var physicEngine = this._scene.getPhysicsEngine();
  85388. if (physicEngine) {
  85389. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85390. }
  85391. }
  85392. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85393. var plugin = this._physicsEnginePlugin;
  85394. for (var i = 0; i < this._numMeshes; i++) {
  85395. var impostor = this._impostors[i];
  85396. if (!impostor) {
  85397. continue;
  85398. }
  85399. if (impostor.isDisposed) {
  85400. this.hideImpostor(this._impostors[i--]);
  85401. }
  85402. else {
  85403. var mesh = this._meshes[i];
  85404. if (mesh && plugin) {
  85405. plugin.syncMeshWithImpostor(mesh, impostor);
  85406. }
  85407. }
  85408. }
  85409. };
  85410. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85411. if (!this._scene) {
  85412. return;
  85413. }
  85414. for (var i = 0; i < this._numMeshes; i++) {
  85415. if (this._impostors[i] == impostor) {
  85416. return;
  85417. }
  85418. }
  85419. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85420. if (debugMesh) {
  85421. this._impostors[this._numMeshes] = impostor;
  85422. this._meshes[this._numMeshes] = debugMesh;
  85423. if (this._numMeshes === 0) {
  85424. this._renderFunction = this._updateDebugMeshes.bind(this);
  85425. this._scene.registerBeforeRender(this._renderFunction);
  85426. }
  85427. this._numMeshes++;
  85428. }
  85429. };
  85430. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85431. if (!impostor || !this._scene) {
  85432. return;
  85433. }
  85434. var removed = false;
  85435. for (var i = 0; i < this._numMeshes; i++) {
  85436. if (this._impostors[i] == impostor) {
  85437. var mesh = this._meshes[i];
  85438. if (!mesh) {
  85439. continue;
  85440. }
  85441. this._scene.removeMesh(mesh);
  85442. mesh.dispose();
  85443. this._numMeshes--;
  85444. if (this._numMeshes > 0) {
  85445. this._meshes[i] = this._meshes[this._numMeshes];
  85446. this._impostors[i] = this._impostors[this._numMeshes];
  85447. this._meshes[this._numMeshes] = null;
  85448. this._impostors[this._numMeshes] = null;
  85449. }
  85450. else {
  85451. this._meshes[0] = null;
  85452. this._impostors[0] = null;
  85453. }
  85454. removed = true;
  85455. break;
  85456. }
  85457. }
  85458. if (removed && this._numMeshes === 0) {
  85459. this._scene.unregisterBeforeRender(this._renderFunction);
  85460. }
  85461. };
  85462. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85463. if (!this._debugMaterial) {
  85464. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85465. this._debugMaterial.wireframe = true;
  85466. }
  85467. return this._debugMaterial;
  85468. };
  85469. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85470. if (!this._debugBoxMesh) {
  85471. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85472. this._debugBoxMesh.renderingGroupId = 1;
  85473. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85474. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85475. scene.removeMesh(this._debugBoxMesh);
  85476. }
  85477. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85478. };
  85479. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85480. if (!this._debugSphereMesh) {
  85481. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85482. this._debugSphereMesh.renderingGroupId = 1;
  85483. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85484. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85485. scene.removeMesh(this._debugSphereMesh);
  85486. }
  85487. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85488. };
  85489. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85490. var mesh = null;
  85491. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85492. mesh = this._getDebugBoxMesh(scene);
  85493. impostor.getBoxSizeToRef(mesh.scaling);
  85494. }
  85495. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85496. mesh = this._getDebugSphereMesh(scene);
  85497. var radius = impostor.getRadius();
  85498. mesh.scaling.x = radius * 2;
  85499. mesh.scaling.y = radius * 2;
  85500. mesh.scaling.z = radius * 2;
  85501. }
  85502. return mesh;
  85503. };
  85504. PhysicsViewer.prototype.dispose = function () {
  85505. for (var i = 0; i < this._numMeshes; i++) {
  85506. this.hideImpostor(this._impostors[i]);
  85507. }
  85508. if (this._debugBoxMesh) {
  85509. this._debugBoxMesh.dispose();
  85510. }
  85511. if (this._debugSphereMesh) {
  85512. this._debugSphereMesh.dispose();
  85513. }
  85514. if (this._debugMaterial) {
  85515. this._debugMaterial.dispose();
  85516. }
  85517. this._impostors.length = 0;
  85518. this._scene = null;
  85519. this._physicsEnginePlugin = null;
  85520. };
  85521. return PhysicsViewer;
  85522. }());
  85523. Debug.PhysicsViewer = PhysicsViewer;
  85524. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85525. })(BABYLON || (BABYLON = {}));
  85526. //# sourceMappingURL=babylon.physicsViewer.js.map
  85527. var BABYLON;
  85528. (function (BABYLON) {
  85529. var BoundingBoxRenderer = /** @class */ (function () {
  85530. function BoundingBoxRenderer(scene) {
  85531. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85532. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85533. this.showBackLines = true;
  85534. this.renderList = new BABYLON.SmartArray(32);
  85535. this._vertexBuffers = {};
  85536. this._scene = scene;
  85537. }
  85538. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85539. if (this._colorShader) {
  85540. return;
  85541. }
  85542. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85543. attributes: [BABYLON.VertexBuffer.PositionKind],
  85544. uniforms: ["world", "viewProjection", "color"]
  85545. });
  85546. var engine = this._scene.getEngine();
  85547. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85548. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85549. this._createIndexBuffer();
  85550. };
  85551. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85552. var engine = this._scene.getEngine();
  85553. 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]);
  85554. };
  85555. BoundingBoxRenderer.prototype._rebuild = function () {
  85556. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85557. if (vb) {
  85558. vb._rebuild();
  85559. }
  85560. this._createIndexBuffer();
  85561. };
  85562. BoundingBoxRenderer.prototype.reset = function () {
  85563. this.renderList.reset();
  85564. };
  85565. BoundingBoxRenderer.prototype.render = function () {
  85566. if (this.renderList.length === 0) {
  85567. return;
  85568. }
  85569. this._prepareRessources();
  85570. if (!this._colorShader.isReady()) {
  85571. return;
  85572. }
  85573. var engine = this._scene.getEngine();
  85574. engine.setDepthWrite(false);
  85575. this._colorShader._preBind();
  85576. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85577. var boundingBox = this.renderList.data[boundingBoxIndex];
  85578. var min = boundingBox.minimum;
  85579. var max = boundingBox.maximum;
  85580. var diff = max.subtract(min);
  85581. var median = min.add(diff.scale(0.5));
  85582. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85583. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85584. .multiply(boundingBox.getWorldMatrix());
  85585. // VBOs
  85586. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85587. if (this.showBackLines) {
  85588. // Back
  85589. engine.setDepthFunctionToGreaterOrEqual();
  85590. this._scene.resetCachedMaterial();
  85591. this._colorShader.setColor4("color", this.backColor.toColor4());
  85592. this._colorShader.bind(worldMatrix);
  85593. // Draw order
  85594. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85595. }
  85596. // Front
  85597. engine.setDepthFunctionToLess();
  85598. this._scene.resetCachedMaterial();
  85599. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85600. this._colorShader.bind(worldMatrix);
  85601. // Draw order
  85602. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85603. }
  85604. this._colorShader.unbind();
  85605. engine.setDepthFunctionToLessOrEqual();
  85606. engine.setDepthWrite(true);
  85607. };
  85608. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85609. this._prepareRessources();
  85610. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85611. return;
  85612. }
  85613. var engine = this._scene.getEngine();
  85614. engine.setDepthWrite(false);
  85615. engine.setColorWrite(false);
  85616. this._colorShader._preBind();
  85617. var boundingBox = mesh._boundingInfo.boundingBox;
  85618. var min = boundingBox.minimum;
  85619. var max = boundingBox.maximum;
  85620. var diff = max.subtract(min);
  85621. var median = min.add(diff.scale(0.5));
  85622. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85623. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85624. .multiply(boundingBox.getWorldMatrix());
  85625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85626. engine.setDepthFunctionToLess();
  85627. this._scene.resetCachedMaterial();
  85628. this._colorShader.bind(worldMatrix);
  85629. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85630. this._colorShader.unbind();
  85631. engine.setDepthFunctionToLessOrEqual();
  85632. engine.setDepthWrite(true);
  85633. engine.setColorWrite(true);
  85634. };
  85635. BoundingBoxRenderer.prototype.dispose = function () {
  85636. if (!this._colorShader) {
  85637. return;
  85638. }
  85639. this.renderList.dispose();
  85640. this._colorShader.dispose();
  85641. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85642. if (buffer) {
  85643. buffer.dispose();
  85644. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85645. }
  85646. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85647. };
  85648. return BoundingBoxRenderer;
  85649. }());
  85650. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85651. })(BABYLON || (BABYLON = {}));
  85652. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85653. var BABYLON;
  85654. (function (BABYLON) {
  85655. /**
  85656. * Defines a target to use with MorphTargetManager
  85657. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85658. */
  85659. var MorphTarget = /** @class */ (function () {
  85660. /**
  85661. * Creates a new MorphTarget
  85662. * @param name defines the name of the target
  85663. * @param influence defines the influence to use
  85664. */
  85665. function MorphTarget(
  85666. /** defines the name of the target */
  85667. name, influence, scene) {
  85668. if (influence === void 0) { influence = 0; }
  85669. if (scene === void 0) { scene = null; }
  85670. this.name = name;
  85671. /**
  85672. * Gets or sets the list of animations
  85673. */
  85674. this.animations = new Array();
  85675. this._positions = null;
  85676. this._normals = null;
  85677. this._tangents = null;
  85678. /**
  85679. * Observable raised when the influence changes
  85680. */
  85681. this.onInfluenceChanged = new BABYLON.Observable();
  85682. this._animationPropertiesOverride = null;
  85683. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85684. this.influence = influence;
  85685. }
  85686. Object.defineProperty(MorphTarget.prototype, "influence", {
  85687. /**
  85688. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85689. */
  85690. get: function () {
  85691. return this._influence;
  85692. },
  85693. set: function (influence) {
  85694. if (this._influence === influence) {
  85695. return;
  85696. }
  85697. var previous = this._influence;
  85698. this._influence = influence;
  85699. if (this.onInfluenceChanged.hasObservers) {
  85700. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85701. }
  85702. },
  85703. enumerable: true,
  85704. configurable: true
  85705. });
  85706. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85707. /**
  85708. * Gets or sets the animation properties override
  85709. */
  85710. get: function () {
  85711. if (!this._animationPropertiesOverride && this._scene) {
  85712. return this._scene.animationPropertiesOverride;
  85713. }
  85714. return this._animationPropertiesOverride;
  85715. },
  85716. set: function (value) {
  85717. this._animationPropertiesOverride = value;
  85718. },
  85719. enumerable: true,
  85720. configurable: true
  85721. });
  85722. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85723. /**
  85724. * Gets a boolean defining if the target contains position data
  85725. */
  85726. get: function () {
  85727. return !!this._positions;
  85728. },
  85729. enumerable: true,
  85730. configurable: true
  85731. });
  85732. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85733. /**
  85734. * Gets a boolean defining if the target contains normal data
  85735. */
  85736. get: function () {
  85737. return !!this._normals;
  85738. },
  85739. enumerable: true,
  85740. configurable: true
  85741. });
  85742. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85743. /**
  85744. * Gets a boolean defining if the target contains tangent data
  85745. */
  85746. get: function () {
  85747. return !!this._tangents;
  85748. },
  85749. enumerable: true,
  85750. configurable: true
  85751. });
  85752. /**
  85753. * Affects position data to this target
  85754. * @param data defines the position data to use
  85755. */
  85756. MorphTarget.prototype.setPositions = function (data) {
  85757. this._positions = data;
  85758. };
  85759. /**
  85760. * Gets the position data stored in this target
  85761. * @returns a FloatArray containing the position data (or null if not present)
  85762. */
  85763. MorphTarget.prototype.getPositions = function () {
  85764. return this._positions;
  85765. };
  85766. /**
  85767. * Affects normal data to this target
  85768. * @param data defines the normal data to use
  85769. */
  85770. MorphTarget.prototype.setNormals = function (data) {
  85771. this._normals = data;
  85772. };
  85773. /**
  85774. * Gets the normal data stored in this target
  85775. * @returns a FloatArray containing the normal data (or null if not present)
  85776. */
  85777. MorphTarget.prototype.getNormals = function () {
  85778. return this._normals;
  85779. };
  85780. /**
  85781. * Affects tangent data to this target
  85782. * @param data defines the tangent data to use
  85783. */
  85784. MorphTarget.prototype.setTangents = function (data) {
  85785. this._tangents = data;
  85786. };
  85787. /**
  85788. * Gets the tangent data stored in this target
  85789. * @returns a FloatArray containing the tangent data (or null if not present)
  85790. */
  85791. MorphTarget.prototype.getTangents = function () {
  85792. return this._tangents;
  85793. };
  85794. /**
  85795. * Serializes the current target into a Serialization object
  85796. * @returns the serialized object
  85797. */
  85798. MorphTarget.prototype.serialize = function () {
  85799. var serializationObject = {};
  85800. serializationObject.name = this.name;
  85801. serializationObject.influence = this.influence;
  85802. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85803. if (this.hasNormals) {
  85804. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85805. }
  85806. if (this.hasTangents) {
  85807. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85808. }
  85809. // Animations
  85810. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85811. return serializationObject;
  85812. };
  85813. // Statics
  85814. /**
  85815. * Creates a new target from serialized data
  85816. * @param serializationObject defines the serialized data to use
  85817. * @returns a new MorphTarget
  85818. */
  85819. MorphTarget.Parse = function (serializationObject) {
  85820. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85821. result.setPositions(serializationObject.positions);
  85822. if (serializationObject.normals) {
  85823. result.setNormals(serializationObject.normals);
  85824. }
  85825. if (serializationObject.tangents) {
  85826. result.setTangents(serializationObject.tangents);
  85827. }
  85828. // Animations
  85829. if (serializationObject.animations) {
  85830. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85831. var parsedAnimation = serializationObject.animations[animationIndex];
  85832. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85833. }
  85834. }
  85835. return result;
  85836. };
  85837. /**
  85838. * Creates a MorphTarget from mesh data
  85839. * @param mesh defines the source mesh
  85840. * @param name defines the name to use for the new target
  85841. * @param influence defines the influence to attach to the target
  85842. * @returns a new MorphTarget
  85843. */
  85844. MorphTarget.FromMesh = function (mesh, name, influence) {
  85845. if (!name) {
  85846. name = mesh.name;
  85847. }
  85848. var result = new MorphTarget(name, influence, mesh.getScene());
  85849. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85851. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85852. }
  85853. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85854. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85855. }
  85856. return result;
  85857. };
  85858. return MorphTarget;
  85859. }());
  85860. BABYLON.MorphTarget = MorphTarget;
  85861. })(BABYLON || (BABYLON = {}));
  85862. //# sourceMappingURL=babylon.morphTarget.js.map
  85863. var BABYLON;
  85864. (function (BABYLON) {
  85865. /**
  85866. * This class is used to deform meshes using morphing between different targets
  85867. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85868. */
  85869. var MorphTargetManager = /** @class */ (function () {
  85870. /**
  85871. * Creates a new MorphTargetManager
  85872. * @param scene defines the current scene
  85873. */
  85874. function MorphTargetManager(scene) {
  85875. if (scene === void 0) { scene = null; }
  85876. this._targets = new Array();
  85877. this._targetObservable = new Array();
  85878. this._activeTargets = new BABYLON.SmartArray(16);
  85879. this._supportsNormals = false;
  85880. this._supportsTangents = false;
  85881. this._vertexCount = 0;
  85882. this._uniqueId = 0;
  85883. this._tempInfluences = new Array();
  85884. if (!scene) {
  85885. scene = BABYLON.Engine.LastCreatedScene;
  85886. }
  85887. this._scene = scene;
  85888. if (this._scene) {
  85889. this._scene.morphTargetManagers.push(this);
  85890. this._uniqueId = this._scene.getUniqueId();
  85891. }
  85892. }
  85893. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85894. /**
  85895. * Gets the unique ID of this manager
  85896. */
  85897. get: function () {
  85898. return this._uniqueId;
  85899. },
  85900. enumerable: true,
  85901. configurable: true
  85902. });
  85903. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85904. /**
  85905. * Gets the number of vertices handled by this manager
  85906. */
  85907. get: function () {
  85908. return this._vertexCount;
  85909. },
  85910. enumerable: true,
  85911. configurable: true
  85912. });
  85913. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85914. /**
  85915. * Gets a boolean indicating if this manager supports morphing of normals
  85916. */
  85917. get: function () {
  85918. return this._supportsNormals;
  85919. },
  85920. enumerable: true,
  85921. configurable: true
  85922. });
  85923. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85924. /**
  85925. * Gets a boolean indicating if this manager supports morphing of tangents
  85926. */
  85927. get: function () {
  85928. return this._supportsTangents;
  85929. },
  85930. enumerable: true,
  85931. configurable: true
  85932. });
  85933. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85934. /**
  85935. * Gets the number of targets stored in this manager
  85936. */
  85937. get: function () {
  85938. return this._targets.length;
  85939. },
  85940. enumerable: true,
  85941. configurable: true
  85942. });
  85943. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85944. /**
  85945. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85946. */
  85947. get: function () {
  85948. return this._activeTargets.length;
  85949. },
  85950. enumerable: true,
  85951. configurable: true
  85952. });
  85953. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85954. /**
  85955. * Gets the list of influences (one per target)
  85956. */
  85957. get: function () {
  85958. return this._influences;
  85959. },
  85960. enumerable: true,
  85961. configurable: true
  85962. });
  85963. /**
  85964. * Gets the active target at specified index. An active target is a target with an influence > 0
  85965. * @param index defines the index to check
  85966. * @returns the requested target
  85967. */
  85968. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85969. return this._activeTargets.data[index];
  85970. };
  85971. /**
  85972. * Gets the target at specified index
  85973. * @param index defines the index to check
  85974. * @returns the requested target
  85975. */
  85976. MorphTargetManager.prototype.getTarget = function (index) {
  85977. return this._targets[index];
  85978. };
  85979. /**
  85980. * Add a new target to this manager
  85981. * @param target defines the target to add
  85982. */
  85983. MorphTargetManager.prototype.addTarget = function (target) {
  85984. var _this = this;
  85985. this._targets.push(target);
  85986. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85987. _this._syncActiveTargets(needUpdate);
  85988. }));
  85989. this._syncActiveTargets(true);
  85990. };
  85991. /**
  85992. * Removes a target from the manager
  85993. * @param target defines the target to remove
  85994. */
  85995. MorphTargetManager.prototype.removeTarget = function (target) {
  85996. var index = this._targets.indexOf(target);
  85997. if (index >= 0) {
  85998. this._targets.splice(index, 1);
  85999. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86000. this._syncActiveTargets(true);
  86001. }
  86002. };
  86003. /**
  86004. * Serializes the current manager into a Serialization object
  86005. * @returns the serialized object
  86006. */
  86007. MorphTargetManager.prototype.serialize = function () {
  86008. var serializationObject = {};
  86009. serializationObject.id = this.uniqueId;
  86010. serializationObject.targets = [];
  86011. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86012. var target = _a[_i];
  86013. serializationObject.targets.push(target.serialize());
  86014. }
  86015. return serializationObject;
  86016. };
  86017. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86018. var influenceCount = 0;
  86019. this._activeTargets.reset();
  86020. this._supportsNormals = true;
  86021. this._supportsTangents = true;
  86022. this._vertexCount = 0;
  86023. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86024. var target = _a[_i];
  86025. this._activeTargets.push(target);
  86026. this._tempInfluences[influenceCount++] = target.influence;
  86027. var positions = target.getPositions();
  86028. if (positions) {
  86029. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86030. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86031. var vertexCount = positions.length / 3;
  86032. if (this._vertexCount === 0) {
  86033. this._vertexCount = vertexCount;
  86034. }
  86035. else if (this._vertexCount !== vertexCount) {
  86036. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86037. return;
  86038. }
  86039. }
  86040. }
  86041. if (!this._influences || this._influences.length !== influenceCount) {
  86042. this._influences = new Float32Array(influenceCount);
  86043. }
  86044. for (var index = 0; index < influenceCount; index++) {
  86045. this._influences[index] = this._tempInfluences[index];
  86046. }
  86047. if (needUpdate) {
  86048. this.synchronize();
  86049. }
  86050. };
  86051. /**
  86052. * Syncrhonize the targets with all the meshes using this morph target manager
  86053. */
  86054. MorphTargetManager.prototype.synchronize = function () {
  86055. if (!this._scene) {
  86056. return;
  86057. }
  86058. // Flag meshes as dirty to resync with the active targets
  86059. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86060. var mesh = _a[_i];
  86061. if (mesh.morphTargetManager === this) {
  86062. mesh._syncGeometryWithMorphTargetManager();
  86063. }
  86064. }
  86065. };
  86066. // Statics
  86067. /**
  86068. * Creates a new MorphTargetManager from serialized data
  86069. * @param serializationObject defines the serialized data
  86070. * @param scene defines the hosting scene
  86071. * @returns the new MorphTargetManager
  86072. */
  86073. MorphTargetManager.Parse = function (serializationObject, scene) {
  86074. var result = new MorphTargetManager(scene);
  86075. result._uniqueId = serializationObject.id;
  86076. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86077. var targetData = _a[_i];
  86078. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86079. }
  86080. return result;
  86081. };
  86082. return MorphTargetManager;
  86083. }());
  86084. BABYLON.MorphTargetManager = MorphTargetManager;
  86085. })(BABYLON || (BABYLON = {}));
  86086. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86087. var BABYLON;
  86088. (function (BABYLON) {
  86089. var Octree = /** @class */ (function () {
  86090. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86091. if (maxDepth === void 0) { maxDepth = 2; }
  86092. this.maxDepth = maxDepth;
  86093. this.dynamicContent = new Array();
  86094. this._maxBlockCapacity = maxBlockCapacity || 64;
  86095. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86096. this._creationFunc = creationFunc;
  86097. }
  86098. // Methods
  86099. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86100. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86101. };
  86102. Octree.prototype.addMesh = function (entry) {
  86103. for (var index = 0; index < this.blocks.length; index++) {
  86104. var block = this.blocks[index];
  86105. block.addEntry(entry);
  86106. }
  86107. };
  86108. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86109. this._selectionContent.reset();
  86110. for (var index = 0; index < this.blocks.length; index++) {
  86111. var block = this.blocks[index];
  86112. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86113. }
  86114. if (allowDuplicate) {
  86115. this._selectionContent.concat(this.dynamicContent);
  86116. }
  86117. else {
  86118. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86119. }
  86120. return this._selectionContent;
  86121. };
  86122. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86123. this._selectionContent.reset();
  86124. for (var index = 0; index < this.blocks.length; index++) {
  86125. var block = this.blocks[index];
  86126. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86127. }
  86128. if (allowDuplicate) {
  86129. this._selectionContent.concat(this.dynamicContent);
  86130. }
  86131. else {
  86132. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86133. }
  86134. return this._selectionContent;
  86135. };
  86136. Octree.prototype.intersectsRay = function (ray) {
  86137. this._selectionContent.reset();
  86138. for (var index = 0; index < this.blocks.length; index++) {
  86139. var block = this.blocks[index];
  86140. block.intersectsRay(ray, this._selectionContent);
  86141. }
  86142. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86143. return this._selectionContent;
  86144. };
  86145. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86146. target.blocks = new Array();
  86147. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86148. // Segmenting space
  86149. for (var x = 0; x < 2; x++) {
  86150. for (var y = 0; y < 2; y++) {
  86151. for (var z = 0; z < 2; z++) {
  86152. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86153. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86154. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86155. block.addEntries(entries);
  86156. target.blocks.push(block);
  86157. }
  86158. }
  86159. }
  86160. };
  86161. Octree.CreationFuncForMeshes = function (entry, block) {
  86162. var boundingInfo = entry.getBoundingInfo();
  86163. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86164. block.entries.push(entry);
  86165. }
  86166. };
  86167. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86168. var boundingInfo = entry.getBoundingInfo();
  86169. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86170. block.entries.push(entry);
  86171. }
  86172. };
  86173. return Octree;
  86174. }());
  86175. BABYLON.Octree = Octree;
  86176. })(BABYLON || (BABYLON = {}));
  86177. //# sourceMappingURL=babylon.octree.js.map
  86178. var BABYLON;
  86179. (function (BABYLON) {
  86180. var OctreeBlock = /** @class */ (function () {
  86181. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86182. this.entries = new Array();
  86183. this._boundingVectors = new Array();
  86184. this._capacity = capacity;
  86185. this._depth = depth;
  86186. this._maxDepth = maxDepth;
  86187. this._creationFunc = creationFunc;
  86188. this._minPoint = minPoint;
  86189. this._maxPoint = maxPoint;
  86190. this._boundingVectors.push(minPoint.clone());
  86191. this._boundingVectors.push(maxPoint.clone());
  86192. this._boundingVectors.push(minPoint.clone());
  86193. this._boundingVectors[2].x = maxPoint.x;
  86194. this._boundingVectors.push(minPoint.clone());
  86195. this._boundingVectors[3].y = maxPoint.y;
  86196. this._boundingVectors.push(minPoint.clone());
  86197. this._boundingVectors[4].z = maxPoint.z;
  86198. this._boundingVectors.push(maxPoint.clone());
  86199. this._boundingVectors[5].z = minPoint.z;
  86200. this._boundingVectors.push(maxPoint.clone());
  86201. this._boundingVectors[6].x = minPoint.x;
  86202. this._boundingVectors.push(maxPoint.clone());
  86203. this._boundingVectors[7].y = minPoint.y;
  86204. }
  86205. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86206. // Property
  86207. get: function () {
  86208. return this._capacity;
  86209. },
  86210. enumerable: true,
  86211. configurable: true
  86212. });
  86213. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86214. get: function () {
  86215. return this._minPoint;
  86216. },
  86217. enumerable: true,
  86218. configurable: true
  86219. });
  86220. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86221. get: function () {
  86222. return this._maxPoint;
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. // Methods
  86228. OctreeBlock.prototype.addEntry = function (entry) {
  86229. if (this.blocks) {
  86230. for (var index = 0; index < this.blocks.length; index++) {
  86231. var block = this.blocks[index];
  86232. block.addEntry(entry);
  86233. }
  86234. return;
  86235. }
  86236. this._creationFunc(entry, this);
  86237. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86238. this.createInnerBlocks();
  86239. }
  86240. };
  86241. OctreeBlock.prototype.addEntries = function (entries) {
  86242. for (var index = 0; index < entries.length; index++) {
  86243. var mesh = entries[index];
  86244. this.addEntry(mesh);
  86245. }
  86246. };
  86247. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86248. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86249. if (this.blocks) {
  86250. for (var index = 0; index < this.blocks.length; index++) {
  86251. var block = this.blocks[index];
  86252. block.select(frustumPlanes, selection, allowDuplicate);
  86253. }
  86254. return;
  86255. }
  86256. if (allowDuplicate) {
  86257. selection.concat(this.entries);
  86258. }
  86259. else {
  86260. selection.concatWithNoDuplicate(this.entries);
  86261. }
  86262. }
  86263. };
  86264. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86265. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86266. if (this.blocks) {
  86267. for (var index = 0; index < this.blocks.length; index++) {
  86268. var block = this.blocks[index];
  86269. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86270. }
  86271. return;
  86272. }
  86273. if (allowDuplicate) {
  86274. selection.concat(this.entries);
  86275. }
  86276. else {
  86277. selection.concatWithNoDuplicate(this.entries);
  86278. }
  86279. }
  86280. };
  86281. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86282. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86283. if (this.blocks) {
  86284. for (var index = 0; index < this.blocks.length; index++) {
  86285. var block = this.blocks[index];
  86286. block.intersectsRay(ray, selection);
  86287. }
  86288. return;
  86289. }
  86290. selection.concatWithNoDuplicate(this.entries);
  86291. }
  86292. };
  86293. OctreeBlock.prototype.createInnerBlocks = function () {
  86294. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86295. };
  86296. return OctreeBlock;
  86297. }());
  86298. BABYLON.OctreeBlock = OctreeBlock;
  86299. })(BABYLON || (BABYLON = {}));
  86300. //# sourceMappingURL=babylon.octreeBlock.js.map
  86301. var BABYLON;
  86302. (function (BABYLON) {
  86303. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86304. __extends(VRDistortionCorrectionPostProcess, _super);
  86305. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86306. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86307. 'LensCenter',
  86308. 'Scale',
  86309. 'ScaleIn',
  86310. 'HmdWarpParam'
  86311. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86312. _this._isRightEye = isRightEye;
  86313. _this._distortionFactors = vrMetrics.distortionK;
  86314. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86315. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86316. _this.adaptScaleToCurrentViewport = true;
  86317. _this.onSizeChangedObservable.add(function () {
  86318. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86319. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86320. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86321. });
  86322. _this.onApplyObservable.add(function (effect) {
  86323. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86324. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86325. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86326. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86327. });
  86328. return _this;
  86329. }
  86330. return VRDistortionCorrectionPostProcess;
  86331. }(BABYLON.PostProcess));
  86332. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86333. })(BABYLON || (BABYLON = {}));
  86334. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86335. var BABYLON;
  86336. (function (BABYLON) {
  86337. /**
  86338. * Postprocess used to generate anaglyphic rendering
  86339. */
  86340. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86341. __extends(AnaglyphPostProcess, _super);
  86342. /**
  86343. * Creates a new AnaglyphPostProcess
  86344. * @param name defines postprocess name
  86345. * @param options defines creation options or target ratio scale
  86346. * @param rigCameras defines cameras using this postprocess
  86347. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86348. * @param engine defines hosting engine
  86349. * @param reusable defines if the postprocess will be reused multiple times per frame
  86350. */
  86351. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86352. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86353. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86354. _this.onApplyObservable.add(function (effect) {
  86355. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86356. });
  86357. return _this;
  86358. }
  86359. return AnaglyphPostProcess;
  86360. }(BABYLON.PostProcess));
  86361. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86362. })(BABYLON || (BABYLON = {}));
  86363. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86364. var BABYLON;
  86365. (function (BABYLON) {
  86366. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86367. __extends(StereoscopicInterlacePostProcess, _super);
  86368. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86369. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86370. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86371. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86372. _this.onSizeChangedObservable.add(function () {
  86373. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86374. });
  86375. _this.onApplyObservable.add(function (effect) {
  86376. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86377. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86378. });
  86379. return _this;
  86380. }
  86381. return StereoscopicInterlacePostProcess;
  86382. }(BABYLON.PostProcess));
  86383. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86384. })(BABYLON || (BABYLON = {}));
  86385. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86386. var BABYLON;
  86387. (function (BABYLON) {
  86388. /**
  86389. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86390. * Screen rotation is taken into account.
  86391. */
  86392. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86393. function FreeCameraDeviceOrientationInput() {
  86394. var _this = this;
  86395. this._screenOrientationAngle = 0;
  86396. this._screenQuaternion = new BABYLON.Quaternion();
  86397. this._alpha = 0;
  86398. this._beta = 0;
  86399. this._gamma = 0;
  86400. this._orientationChanged = function () {
  86401. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86402. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86403. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86404. };
  86405. this._deviceOrientation = function (evt) {
  86406. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86407. _this._beta = evt.beta !== null ? evt.beta : 0;
  86408. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86409. };
  86410. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86411. this._orientationChanged();
  86412. }
  86413. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86414. get: function () {
  86415. return this._camera;
  86416. },
  86417. set: function (camera) {
  86418. this._camera = camera;
  86419. if (this._camera != null && !this._camera.rotationQuaternion) {
  86420. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86421. }
  86422. },
  86423. enumerable: true,
  86424. configurable: true
  86425. });
  86426. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86427. window.addEventListener("orientationchange", this._orientationChanged);
  86428. window.addEventListener("deviceorientation", this._deviceOrientation);
  86429. //In certain cases, the attach control is called AFTER orientation was changed,
  86430. //So this is needed.
  86431. this._orientationChanged();
  86432. };
  86433. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86434. window.removeEventListener("orientationchange", this._orientationChanged);
  86435. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86436. };
  86437. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86438. //if no device orientation provided, don't update the rotation.
  86439. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86440. if (!this._alpha)
  86441. return;
  86442. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86443. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86444. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86445. //Mirror on XY Plane
  86446. this._camera.rotationQuaternion.z *= -1;
  86447. this._camera.rotationQuaternion.w *= -1;
  86448. };
  86449. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86450. return "FreeCameraDeviceOrientationInput";
  86451. };
  86452. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86453. return "deviceOrientation";
  86454. };
  86455. return FreeCameraDeviceOrientationInput;
  86456. }());
  86457. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86458. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86459. })(BABYLON || (BABYLON = {}));
  86460. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86461. var BABYLON;
  86462. (function (BABYLON) {
  86463. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86464. function ArcRotateCameraVRDeviceOrientationInput() {
  86465. this.alphaCorrection = 1;
  86466. this.betaCorrection = 1;
  86467. this.gammaCorrection = 1;
  86468. this._alpha = 0;
  86469. this._gamma = 0;
  86470. this._dirty = false;
  86471. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86472. }
  86473. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86474. this.camera.attachControl(element, noPreventDefault);
  86475. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86476. };
  86477. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86478. if (evt.alpha !== null) {
  86479. this._alpha = +evt.alpha | 0;
  86480. }
  86481. if (evt.gamma !== null) {
  86482. this._gamma = +evt.gamma | 0;
  86483. }
  86484. this._dirty = true;
  86485. };
  86486. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86487. if (this._dirty) {
  86488. this._dirty = false;
  86489. if (this._gamma < 0) {
  86490. this._gamma = 180 + this._gamma;
  86491. }
  86492. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86493. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86494. }
  86495. };
  86496. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86497. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86498. };
  86499. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86500. return "ArcRotateCameraVRDeviceOrientationInput";
  86501. };
  86502. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86503. return "VRDeviceOrientation";
  86504. };
  86505. return ArcRotateCameraVRDeviceOrientationInput;
  86506. }());
  86507. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86508. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86509. })(BABYLON || (BABYLON = {}));
  86510. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86511. var BABYLON;
  86512. (function (BABYLON) {
  86513. var VRCameraMetrics = /** @class */ (function () {
  86514. function VRCameraMetrics() {
  86515. this.compensateDistortion = true;
  86516. }
  86517. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86518. get: function () {
  86519. return this.hResolution / (2 * this.vResolution);
  86520. },
  86521. enumerable: true,
  86522. configurable: true
  86523. });
  86524. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86525. get: function () {
  86526. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86527. },
  86528. enumerable: true,
  86529. configurable: true
  86530. });
  86531. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86532. get: function () {
  86533. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86534. var h = (4 * meters) / this.hScreenSize;
  86535. return BABYLON.Matrix.Translation(h, 0, 0);
  86536. },
  86537. enumerable: true,
  86538. configurable: true
  86539. });
  86540. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86541. get: function () {
  86542. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86543. var h = (4 * meters) / this.hScreenSize;
  86544. return BABYLON.Matrix.Translation(-h, 0, 0);
  86545. },
  86546. enumerable: true,
  86547. configurable: true
  86548. });
  86549. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86550. get: function () {
  86551. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86552. },
  86553. enumerable: true,
  86554. configurable: true
  86555. });
  86556. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86557. get: function () {
  86558. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86559. },
  86560. enumerable: true,
  86561. configurable: true
  86562. });
  86563. VRCameraMetrics.GetDefault = function () {
  86564. var result = new VRCameraMetrics();
  86565. result.hResolution = 1280;
  86566. result.vResolution = 800;
  86567. result.hScreenSize = 0.149759993;
  86568. result.vScreenSize = 0.0935999975;
  86569. result.vScreenCenter = 0.0467999987;
  86570. result.eyeToScreenDistance = 0.0410000011;
  86571. result.lensSeparationDistance = 0.0635000020;
  86572. result.interpupillaryDistance = 0.0640000030;
  86573. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86574. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86575. result.postProcessScaleFactor = 1.714605507808412;
  86576. result.lensCenterOffset = 0.151976421;
  86577. return result;
  86578. };
  86579. return VRCameraMetrics;
  86580. }());
  86581. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86582. })(BABYLON || (BABYLON = {}));
  86583. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86584. var BABYLON;
  86585. (function (BABYLON) {
  86586. /**
  86587. * This represents a WebVR camera.
  86588. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86589. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86590. */
  86591. var WebVRFreeCamera = /** @class */ (function (_super) {
  86592. __extends(WebVRFreeCamera, _super);
  86593. /**
  86594. * Instantiates a WebVRFreeCamera.
  86595. * @param name The name of the WebVRFreeCamera
  86596. * @param position The starting anchor position for the camera
  86597. * @param scene The scene the camera belongs to
  86598. * @param webVROptions a set of customizable options for the webVRCamera
  86599. */
  86600. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86601. if (webVROptions === void 0) { webVROptions = {}; }
  86602. var _this = _super.call(this, name, position, scene) || this;
  86603. _this.webVROptions = webVROptions;
  86604. /**
  86605. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86606. */
  86607. _this._vrDevice = null;
  86608. /**
  86609. * The rawPose of the vrDevice.
  86610. */
  86611. _this.rawPose = null;
  86612. _this._specsVersion = "1.1";
  86613. _this._attached = false;
  86614. _this._descendants = [];
  86615. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86616. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86617. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86618. _this._standingMatrix = null;
  86619. /**
  86620. * Represents device position in babylon space.
  86621. */
  86622. _this.devicePosition = BABYLON.Vector3.Zero();
  86623. /**
  86624. * Represents device rotation in babylon space.
  86625. */
  86626. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86627. /**
  86628. * The scale of the device to be used when translating from device space to babylon space.
  86629. */
  86630. _this.deviceScaleFactor = 1;
  86631. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86632. _this._worldToDevice = BABYLON.Matrix.Identity();
  86633. /**
  86634. * References to the webVR controllers for the vrDevice.
  86635. */
  86636. _this.controllers = [];
  86637. /**
  86638. * Emits an event when a controller is attached.
  86639. */
  86640. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86641. /**
  86642. * Emits an event when a controller's mesh has been loaded;
  86643. */
  86644. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86645. /**
  86646. * If the rig cameras be used as parent instead of this camera.
  86647. */
  86648. _this.rigParenting = true;
  86649. _this._defaultHeight = undefined;
  86650. _this._workingVector = BABYLON.Vector3.Zero();
  86651. _this._oneVector = BABYLON.Vector3.One();
  86652. _this._workingMatrix = BABYLON.Matrix.Identity();
  86653. _this._cache.position = BABYLON.Vector3.Zero();
  86654. if (webVROptions.defaultHeight) {
  86655. _this._defaultHeight = webVROptions.defaultHeight;
  86656. _this.position.y = _this._defaultHeight;
  86657. }
  86658. _this.minZ = 0.1;
  86659. //legacy support - the compensation boolean was removed.
  86660. if (arguments.length === 5) {
  86661. _this.webVROptions = arguments[4];
  86662. }
  86663. // default webVR options
  86664. if (_this.webVROptions.trackPosition == undefined) {
  86665. _this.webVROptions.trackPosition = true;
  86666. }
  86667. if (_this.webVROptions.controllerMeshes == undefined) {
  86668. _this.webVROptions.controllerMeshes = true;
  86669. }
  86670. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86671. _this.webVROptions.defaultLightingOnControllers = true;
  86672. }
  86673. _this.rotationQuaternion = new BABYLON.Quaternion();
  86674. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86675. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86676. }
  86677. //enable VR
  86678. var engine = _this.getEngine();
  86679. _this._onVREnabled = function (success) { if (success) {
  86680. _this.initControllers();
  86681. } };
  86682. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86683. engine.initWebVR().add(function (event) {
  86684. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86685. return;
  86686. }
  86687. _this._vrDevice = event.vrDisplay;
  86688. //reset the rig parameters.
  86689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86690. if (_this._attached) {
  86691. _this.getEngine().enableVR();
  86692. }
  86693. });
  86694. if (typeof (VRFrameData) !== "undefined")
  86695. _this._frameData = new VRFrameData();
  86696. /**
  86697. * The idea behind the following lines:
  86698. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86699. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86700. * the second will not show it correctly.
  86701. *
  86702. * To solve this - each object that has the camera as parent will be added to a protected array.
  86703. * When the rig camera renders, it will take this array and set all of those to be its children.
  86704. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86705. * Amazing!
  86706. */
  86707. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86708. if (camera.parent === _this && _this.rigParenting) {
  86709. _this._descendants = _this.getDescendants(true, function (n) {
  86710. // don't take the cameras or the controllers!
  86711. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86712. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86713. return !isController && !isRigCamera;
  86714. });
  86715. _this._descendants.forEach(function (node) {
  86716. node.parent = camera;
  86717. });
  86718. }
  86719. });
  86720. scene.onAfterCameraRenderObservable.add(function (camera) {
  86721. if (camera.parent === _this && _this.rigParenting) {
  86722. _this._descendants.forEach(function (node) {
  86723. node.parent = _this;
  86724. });
  86725. }
  86726. });
  86727. return _this;
  86728. }
  86729. /**
  86730. * Gets the device distance from the ground in meters.
  86731. * @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.
  86732. */
  86733. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86734. if (this._standingMatrix) {
  86735. // Add standing matrix offset to get real offset from ground in room
  86736. this._standingMatrix.getTranslationToRef(this._workingVector);
  86737. return this._deviceRoomPosition.y + this._workingVector.y;
  86738. }
  86739. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86740. return this._defaultHeight || 0;
  86741. };
  86742. /**
  86743. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86744. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86745. */
  86746. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86747. var _this = this;
  86748. if (callback === void 0) { callback = function (bool) { }; }
  86749. // Use standing matrix if available
  86750. this.getEngine().initWebVRAsync().then(function (result) {
  86751. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86752. callback(false);
  86753. }
  86754. else {
  86755. _this._standingMatrix = new BABYLON.Matrix();
  86756. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86757. if (!_this.getScene().useRightHandedSystem) {
  86758. [2, 6, 8, 9, 14].forEach(function (num) {
  86759. if (_this._standingMatrix) {
  86760. _this._standingMatrix.m[num] *= -1;
  86761. }
  86762. });
  86763. }
  86764. callback(true);
  86765. }
  86766. });
  86767. };
  86768. /**
  86769. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86770. * @returns A promise with a boolean set to if the standing matrix is supported.
  86771. */
  86772. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86773. var _this = this;
  86774. return new Promise(function (res, rej) {
  86775. _this.useStandingMatrix(function (supported) {
  86776. res(supported);
  86777. });
  86778. });
  86779. };
  86780. /**
  86781. * Disposes the camera
  86782. */
  86783. WebVRFreeCamera.prototype.dispose = function () {
  86784. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86785. _super.prototype.dispose.call(this);
  86786. };
  86787. /**
  86788. * Gets a vrController by name.
  86789. * @param name The name of the controller to retreive
  86790. * @returns the controller matching the name specified or null if not found
  86791. */
  86792. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86793. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86794. var gp = _a[_i];
  86795. if (gp.hand === name) {
  86796. return gp;
  86797. }
  86798. }
  86799. return null;
  86800. };
  86801. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86802. /**
  86803. * The controller corrisponding to the users left hand.
  86804. */
  86805. get: function () {
  86806. if (!this._leftController) {
  86807. this._leftController = this.getControllerByName("left");
  86808. }
  86809. return this._leftController;
  86810. },
  86811. enumerable: true,
  86812. configurable: true
  86813. });
  86814. ;
  86815. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86816. /**
  86817. * The controller corrisponding to the users right hand.
  86818. */
  86819. get: function () {
  86820. if (!this._rightController) {
  86821. this._rightController = this.getControllerByName("right");
  86822. }
  86823. return this._rightController;
  86824. },
  86825. enumerable: true,
  86826. configurable: true
  86827. });
  86828. ;
  86829. /**
  86830. * Casts a ray forward from the vrCamera's gaze.
  86831. * @param length Length of the ray (default: 100)
  86832. * @returns the ray corrisponding to the gaze
  86833. */
  86834. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86835. if (length === void 0) { length = 100; }
  86836. if (this.leftCamera) {
  86837. // Use left eye to avoid computation to compute center on every call
  86838. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86839. }
  86840. else {
  86841. return _super.prototype.getForwardRay.call(this, length);
  86842. }
  86843. };
  86844. /**
  86845. * Updates the camera based on device's frame data
  86846. */
  86847. WebVRFreeCamera.prototype._checkInputs = function () {
  86848. if (this._vrDevice && this._vrDevice.isPresenting) {
  86849. this._vrDevice.getFrameData(this._frameData);
  86850. this.updateFromDevice(this._frameData.pose);
  86851. }
  86852. _super.prototype._checkInputs.call(this);
  86853. };
  86854. /**
  86855. * Updates the poseControlled values based on the input device pose.
  86856. * @param poseData Pose coming from the device
  86857. */
  86858. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86859. if (poseData && poseData.orientation) {
  86860. this.rawPose = poseData;
  86861. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86862. if (this.getScene().useRightHandedSystem) {
  86863. this._deviceRoomRotationQuaternion.z *= -1;
  86864. this._deviceRoomRotationQuaternion.w *= -1;
  86865. }
  86866. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86867. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86868. if (this.getScene().useRightHandedSystem) {
  86869. this._deviceRoomPosition.z *= -1;
  86870. }
  86871. }
  86872. }
  86873. };
  86874. /**
  86875. * WebVR's attach control will start broadcasting frames to the device.
  86876. * Note that in certain browsers (chrome for example) this function must be called
  86877. * within a user-interaction callback. Example:
  86878. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86879. *
  86880. * @param element html element to attach the vrDevice to
  86881. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86882. */
  86883. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86884. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86885. this._attached = true;
  86886. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86887. if (this._vrDevice) {
  86888. this.getEngine().enableVR();
  86889. }
  86890. };
  86891. /**
  86892. * Detaches the camera from the html element and disables VR
  86893. *
  86894. * @param element html element to detach from
  86895. */
  86896. WebVRFreeCamera.prototype.detachControl = function (element) {
  86897. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86898. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86899. _super.prototype.detachControl.call(this, element);
  86900. this._attached = false;
  86901. this.getEngine().disableVR();
  86902. };
  86903. /**
  86904. * @returns the name of this class
  86905. */
  86906. WebVRFreeCamera.prototype.getClassName = function () {
  86907. return "WebVRFreeCamera";
  86908. };
  86909. /**
  86910. * Calls resetPose on the vrDisplay
  86911. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86912. */
  86913. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86914. //uses the vrDisplay's "resetPose()".
  86915. //pitch and roll won't be affected.
  86916. this._vrDevice.resetPose();
  86917. };
  86918. /**
  86919. * Updates the rig cameras (left and right eye)
  86920. */
  86921. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86922. var camLeft = this._rigCameras[0];
  86923. var camRight = this._rigCameras[1];
  86924. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86925. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86926. camLeft.position.copyFrom(this._deviceRoomPosition);
  86927. camRight.position.copyFrom(this._deviceRoomPosition);
  86928. };
  86929. /**
  86930. * Updates the cached values of the camera
  86931. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86932. */
  86933. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86934. var _this = this;
  86935. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86936. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86937. if (!this.updateCacheCalled) {
  86938. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86939. this.updateCacheCalled = true;
  86940. this.update();
  86941. }
  86942. // Set working vector to the device position in room space rotated by the new rotation
  86943. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86944. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86945. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86946. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86947. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86948. // Add translation from anchor position
  86949. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86950. this._workingVector.addInPlace(this.position);
  86951. this._workingVector.subtractInPlace(this._cache.position);
  86952. this._deviceToWorld.setTranslation(this._workingVector);
  86953. // Set an inverted matrix to be used when updating the camera
  86954. this._deviceToWorld.invertToRef(this._worldToDevice);
  86955. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86956. this.controllers.forEach(function (controller) {
  86957. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86958. controller.update();
  86959. });
  86960. }
  86961. if (!ignoreParentClass) {
  86962. _super.prototype._updateCache.call(this);
  86963. }
  86964. this.updateCacheCalled = false;
  86965. };
  86966. /**
  86967. * Updates the current device position and rotation in the babylon world
  86968. */
  86969. WebVRFreeCamera.prototype.update = function () {
  86970. // Get current device position in babylon world
  86971. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86972. // Get current device rotation in babylon world
  86973. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86974. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86975. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86976. _super.prototype.update.call(this);
  86977. };
  86978. /**
  86979. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86980. * @returns an identity matrix
  86981. */
  86982. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86983. return BABYLON.Matrix.Identity();
  86984. };
  86985. /**
  86986. * This function is called by the two RIG cameras.
  86987. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86988. */
  86989. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86990. var _this = this;
  86991. // Update the parent camera prior to using a child camera to avoid desynchronization
  86992. var parentCamera = this._cameraRigParams["parentCamera"];
  86993. parentCamera._updateCache();
  86994. //WebVR 1.1
  86995. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86996. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86997. if (!this.getScene().useRightHandedSystem) {
  86998. [2, 6, 8, 9, 14].forEach(function (num) {
  86999. _this._webvrViewMatrix.m[num] *= -1;
  87000. });
  87001. }
  87002. // update the camera rotation matrix
  87003. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87004. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87005. // Computing target and final matrix
  87006. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87007. // should the view matrix be updated with scale and position offset?
  87008. if (parentCamera.deviceScaleFactor !== 1) {
  87009. this._webvrViewMatrix.invert();
  87010. // scale the position, if set
  87011. if (parentCamera.deviceScaleFactor) {
  87012. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87013. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87014. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87015. }
  87016. this._webvrViewMatrix.invert();
  87017. }
  87018. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87019. // Compute global position
  87020. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87021. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87022. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87023. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87024. this._markSyncedWithParent();
  87025. return this._webvrViewMatrix;
  87026. };
  87027. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87028. var _this = this;
  87029. var parentCamera = this.parent;
  87030. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87031. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87032. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87033. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87034. //babylon compatible matrix
  87035. if (!this.getScene().useRightHandedSystem) {
  87036. [8, 9, 10, 11].forEach(function (num) {
  87037. _this._projectionMatrix.m[num] *= -1;
  87038. });
  87039. }
  87040. return this._projectionMatrix;
  87041. };
  87042. /**
  87043. * Initializes the controllers and their meshes
  87044. */
  87045. WebVRFreeCamera.prototype.initControllers = function () {
  87046. var _this = this;
  87047. this.controllers = [];
  87048. var manager = this.getScene().gamepadManager;
  87049. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87050. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87051. var webVrController = gamepad;
  87052. if (webVrController.defaultModel) {
  87053. webVrController.defaultModel.setEnabled(false);
  87054. }
  87055. if (webVrController.hand === "right") {
  87056. _this._rightController = null;
  87057. }
  87058. if (webVrController.hand === "left") {
  87059. _this._leftController = null;
  87060. }
  87061. var controllerIndex = _this.controllers.indexOf(webVrController);
  87062. if (controllerIndex !== -1) {
  87063. _this.controllers.splice(controllerIndex, 1);
  87064. }
  87065. }
  87066. });
  87067. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87068. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87069. var webVrController_1 = gamepad;
  87070. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87071. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87072. if (_this.webVROptions.controllerMeshes) {
  87073. if (webVrController_1.defaultModel) {
  87074. webVrController_1.defaultModel.setEnabled(true);
  87075. }
  87076. else {
  87077. // Load the meshes
  87078. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87079. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87080. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87081. if (_this.webVROptions.defaultLightingOnControllers) {
  87082. if (!_this._lightOnControllers) {
  87083. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87084. }
  87085. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87086. var children = mesh.getChildren();
  87087. if (children.length !== 0) {
  87088. children.forEach(function (mesh) {
  87089. light.includedOnlyMeshes.push(mesh);
  87090. activateLightOnSubMeshes_1(mesh, light);
  87091. });
  87092. }
  87093. };
  87094. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87095. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87096. }
  87097. });
  87098. }
  87099. }
  87100. webVrController_1.attachToPoseControlledCamera(_this);
  87101. // since this is async - sanity check. Is the controller already stored?
  87102. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87103. //add to the controllers array
  87104. _this.controllers.push(webVrController_1);
  87105. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87106. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87107. // So we're overriding setting left & right manually to be sure
  87108. var firstViveWandDetected = false;
  87109. for (var i = 0; i < _this.controllers.length; i++) {
  87110. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87111. if (!firstViveWandDetected) {
  87112. firstViveWandDetected = true;
  87113. _this.controllers[i].hand = "left";
  87114. }
  87115. else {
  87116. _this.controllers[i].hand = "right";
  87117. }
  87118. }
  87119. }
  87120. //did we find enough controllers? Great! let the developer know.
  87121. if (_this.controllers.length >= 2) {
  87122. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87123. }
  87124. }
  87125. }
  87126. });
  87127. };
  87128. return WebVRFreeCamera;
  87129. }(BABYLON.FreeCamera));
  87130. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87131. })(BABYLON || (BABYLON = {}));
  87132. //# sourceMappingURL=babylon.webVRCamera.js.map
  87133. var BABYLON;
  87134. (function (BABYLON) {
  87135. // We're mainly based on the logic defined into the FreeCamera code
  87136. /**
  87137. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87138. * being tilted forward or back and left or right.
  87139. */
  87140. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87141. __extends(DeviceOrientationCamera, _super);
  87142. /**
  87143. * Creates a new device orientation camera
  87144. * @param name The name of the camera
  87145. * @param position The start position camera
  87146. * @param scene The scene the camera belongs to
  87147. */
  87148. function DeviceOrientationCamera(name, position, scene) {
  87149. var _this = _super.call(this, name, position, scene) || this;
  87150. _this._quaternionCache = new BABYLON.Quaternion();
  87151. _this.inputs.addDeviceOrientation();
  87152. return _this;
  87153. }
  87154. /**
  87155. * Gets the current instance class name ("DeviceOrientationCamera").
  87156. * This helps avoiding instanceof at run time.
  87157. * @returns the class name
  87158. */
  87159. DeviceOrientationCamera.prototype.getClassName = function () {
  87160. return "DeviceOrientationCamera";
  87161. };
  87162. /**
  87163. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87164. */
  87165. DeviceOrientationCamera.prototype._checkInputs = function () {
  87166. _super.prototype._checkInputs.call(this);
  87167. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87168. if (this._initialQuaternion) {
  87169. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87170. }
  87171. };
  87172. /**
  87173. * Reset the camera to its default orientation on the specified axis only.
  87174. * @param axis The axis to reset
  87175. */
  87176. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87177. var _this = this;
  87178. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87179. //can only work if this camera has a rotation quaternion already.
  87180. if (!this.rotationQuaternion)
  87181. return;
  87182. if (!this._initialQuaternion) {
  87183. this._initialQuaternion = new BABYLON.Quaternion();
  87184. }
  87185. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87186. ['x', 'y', 'z'].forEach(function (axisName) {
  87187. if (!axis[axisName]) {
  87188. _this._initialQuaternion[axisName] = 0;
  87189. }
  87190. else {
  87191. _this._initialQuaternion[axisName] *= -1;
  87192. }
  87193. });
  87194. this._initialQuaternion.normalize();
  87195. //force rotation update
  87196. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87197. };
  87198. return DeviceOrientationCamera;
  87199. }(BABYLON.FreeCamera));
  87200. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87201. })(BABYLON || (BABYLON = {}));
  87202. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87203. var BABYLON;
  87204. (function (BABYLON) {
  87205. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87206. __extends(VRDeviceOrientationFreeCamera, _super);
  87207. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87208. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87209. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87210. var _this = _super.call(this, name, position, scene) || this;
  87211. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87212. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87213. return _this;
  87214. }
  87215. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87216. return "VRDeviceOrientationFreeCamera";
  87217. };
  87218. return VRDeviceOrientationFreeCamera;
  87219. }(BABYLON.DeviceOrientationCamera));
  87220. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87221. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87222. __extends(VRDeviceOrientationGamepadCamera, _super);
  87223. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87224. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87225. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87226. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87227. _this.inputs.addGamepad();
  87228. return _this;
  87229. }
  87230. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87231. return "VRDeviceOrientationGamepadCamera";
  87232. };
  87233. return VRDeviceOrientationGamepadCamera;
  87234. }(VRDeviceOrientationFreeCamera));
  87235. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87236. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87237. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87238. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87239. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87240. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87241. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87242. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87243. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87244. _this.inputs.addVRDeviceOrientation();
  87245. return _this;
  87246. }
  87247. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87248. return "VRDeviceOrientationArcRotateCamera";
  87249. };
  87250. return VRDeviceOrientationArcRotateCamera;
  87251. }(BABYLON.ArcRotateCamera));
  87252. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87253. })(BABYLON || (BABYLON = {}));
  87254. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87255. var BABYLON;
  87256. (function (BABYLON) {
  87257. /**
  87258. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87259. */
  87260. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87261. __extends(AnaglyphFreeCamera, _super);
  87262. /**
  87263. * Creates a new AnaglyphFreeCamera
  87264. * @param name defines camera name
  87265. * @param position defines initial position
  87266. * @param interaxialDistance defines distance between each color axis
  87267. * @param scene defines the hosting scene
  87268. */
  87269. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87270. var _this = _super.call(this, name, position, scene) || this;
  87271. _this.interaxialDistance = interaxialDistance;
  87272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87273. return _this;
  87274. }
  87275. /**
  87276. * Gets camera class name
  87277. * @returns AnaglyphFreeCamera
  87278. */
  87279. AnaglyphFreeCamera.prototype.getClassName = function () {
  87280. return "AnaglyphFreeCamera";
  87281. };
  87282. return AnaglyphFreeCamera;
  87283. }(BABYLON.FreeCamera));
  87284. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87285. /**
  87286. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87287. */
  87288. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87289. __extends(AnaglyphArcRotateCamera, _super);
  87290. /**
  87291. * Creates a new AnaglyphArcRotateCamera
  87292. * @param name defines camera name
  87293. * @param alpha defines alpha angle (in radians)
  87294. * @param beta defines beta angle (in radians)
  87295. * @param radius defines radius
  87296. * @param target defines camera target
  87297. * @param interaxialDistance defines distance between each color axis
  87298. * @param scene defines the hosting scene
  87299. */
  87300. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87301. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87302. _this.interaxialDistance = interaxialDistance;
  87303. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87304. return _this;
  87305. }
  87306. /**
  87307. * Gets camera class name
  87308. * @returns AnaglyphArcRotateCamera
  87309. */
  87310. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87311. return "AnaglyphArcRotateCamera";
  87312. };
  87313. return AnaglyphArcRotateCamera;
  87314. }(BABYLON.ArcRotateCamera));
  87315. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87316. /**
  87317. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87318. */
  87319. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87320. __extends(AnaglyphGamepadCamera, _super);
  87321. /**
  87322. * Creates a new AnaglyphGamepadCamera
  87323. * @param name defines camera name
  87324. * @param position defines initial position
  87325. * @param interaxialDistance defines distance between each color axis
  87326. * @param scene defines the hosting scene
  87327. */
  87328. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87329. var _this = _super.call(this, name, position, scene) || this;
  87330. _this.interaxialDistance = interaxialDistance;
  87331. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87332. return _this;
  87333. }
  87334. /**
  87335. * Gets camera class name
  87336. * @returns AnaglyphGamepadCamera
  87337. */
  87338. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87339. return "AnaglyphGamepadCamera";
  87340. };
  87341. return AnaglyphGamepadCamera;
  87342. }(BABYLON.GamepadCamera));
  87343. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87344. /**
  87345. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87346. */
  87347. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87348. __extends(AnaglyphUniversalCamera, _super);
  87349. /**
  87350. * Creates a new AnaglyphUniversalCamera
  87351. * @param name defines camera name
  87352. * @param position defines initial position
  87353. * @param interaxialDistance defines distance between each color axis
  87354. * @param scene defines the hosting scene
  87355. */
  87356. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87357. var _this = _super.call(this, name, position, scene) || this;
  87358. _this.interaxialDistance = interaxialDistance;
  87359. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87360. return _this;
  87361. }
  87362. /**
  87363. * Gets camera class name
  87364. * @returns AnaglyphUniversalCamera
  87365. */
  87366. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87367. return "AnaglyphUniversalCamera";
  87368. };
  87369. return AnaglyphUniversalCamera;
  87370. }(BABYLON.UniversalCamera));
  87371. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87372. /**
  87373. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87374. */
  87375. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87376. __extends(StereoscopicFreeCamera, _super);
  87377. /**
  87378. * Creates a new StereoscopicFreeCamera
  87379. * @param name defines camera name
  87380. * @param position defines initial position
  87381. * @param interaxialDistance defines distance between each color axis
  87382. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87383. * @param scene defines the hosting scene
  87384. */
  87385. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87386. var _this = _super.call(this, name, position, scene) || this;
  87387. _this.interaxialDistance = interaxialDistance;
  87388. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87389. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87390. return _this;
  87391. }
  87392. /**
  87393. * Gets camera class name
  87394. * @returns StereoscopicFreeCamera
  87395. */
  87396. StereoscopicFreeCamera.prototype.getClassName = function () {
  87397. return "StereoscopicFreeCamera";
  87398. };
  87399. return StereoscopicFreeCamera;
  87400. }(BABYLON.FreeCamera));
  87401. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87402. /**
  87403. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87404. */
  87405. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87406. __extends(StereoscopicArcRotateCamera, _super);
  87407. /**
  87408. * Creates a new StereoscopicArcRotateCamera
  87409. * @param name defines camera name
  87410. * @param alpha defines alpha angle (in radians)
  87411. * @param beta defines beta angle (in radians)
  87412. * @param radius defines radius
  87413. * @param target defines camera target
  87414. * @param interaxialDistance defines distance between each color axis
  87415. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87416. * @param scene defines the hosting scene
  87417. */
  87418. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87419. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87420. _this.interaxialDistance = interaxialDistance;
  87421. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87422. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87423. return _this;
  87424. }
  87425. /**
  87426. * Gets camera class name
  87427. * @returns StereoscopicArcRotateCamera
  87428. */
  87429. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87430. return "StereoscopicArcRotateCamera";
  87431. };
  87432. return StereoscopicArcRotateCamera;
  87433. }(BABYLON.ArcRotateCamera));
  87434. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87435. /**
  87436. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87437. */
  87438. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87439. __extends(StereoscopicGamepadCamera, _super);
  87440. /**
  87441. * Creates a new StereoscopicGamepadCamera
  87442. * @param name defines camera name
  87443. * @param position defines initial position
  87444. * @param interaxialDistance defines distance between each color axis
  87445. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87446. * @param scene defines the hosting scene
  87447. */
  87448. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87449. var _this = _super.call(this, name, position, scene) || this;
  87450. _this.interaxialDistance = interaxialDistance;
  87451. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87452. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87453. return _this;
  87454. }
  87455. /**
  87456. * Gets camera class name
  87457. * @returns StereoscopicGamepadCamera
  87458. */
  87459. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87460. return "StereoscopicGamepadCamera";
  87461. };
  87462. return StereoscopicGamepadCamera;
  87463. }(BABYLON.GamepadCamera));
  87464. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87465. /**
  87466. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87467. */
  87468. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87469. __extends(StereoscopicUniversalCamera, _super);
  87470. /**
  87471. * Creates a new StereoscopicUniversalCamera
  87472. * @param name defines camera name
  87473. * @param position defines initial position
  87474. * @param interaxialDistance defines distance between each color axis
  87475. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87476. * @param scene defines the hosting scene
  87477. */
  87478. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87479. var _this = _super.call(this, name, position, scene) || this;
  87480. _this.interaxialDistance = interaxialDistance;
  87481. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87482. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87483. return _this;
  87484. }
  87485. /**
  87486. * Gets camera class name
  87487. * @returns StereoscopicUniversalCamera
  87488. */
  87489. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87490. return "StereoscopicUniversalCamera";
  87491. };
  87492. return StereoscopicUniversalCamera;
  87493. }(BABYLON.UniversalCamera));
  87494. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87495. })(BABYLON || (BABYLON = {}));
  87496. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87497. var BABYLON;
  87498. (function (BABYLON) {
  87499. var VRExperienceHelperGazer = /** @class */ (function () {
  87500. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87501. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87502. this.scene = scene;
  87503. this._pointerDownOnMeshAsked = false;
  87504. this._isActionableMesh = false;
  87505. this._teleportationRequestInitiated = false;
  87506. this._teleportationBackRequestInitiated = false;
  87507. this._rotationRightAsked = false;
  87508. this._rotationLeftAsked = false;
  87509. this._dpadPressed = true;
  87510. this._activePointer = false;
  87511. this._id = VRExperienceHelperGazer._idCounter++;
  87512. // Gaze tracker
  87513. if (!gazeTrackerToClone) {
  87514. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87515. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87516. this._gazeTracker.isPickable = false;
  87517. this._gazeTracker.isVisible = false;
  87518. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87519. targetMat.specularColor = BABYLON.Color3.Black();
  87520. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87521. targetMat.backFaceCulling = false;
  87522. this._gazeTracker.material = targetMat;
  87523. }
  87524. else {
  87525. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87526. }
  87527. }
  87528. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87529. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87530. };
  87531. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87532. this._pointerDownOnMeshAsked = true;
  87533. if (this._currentMeshSelected && this._currentHit) {
  87534. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87535. }
  87536. };
  87537. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87538. if (this._currentMeshSelected && this._currentHit) {
  87539. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87540. }
  87541. this._pointerDownOnMeshAsked = false;
  87542. };
  87543. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87544. this._activePointer = true;
  87545. };
  87546. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87547. this._activePointer = false;
  87548. };
  87549. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87550. if (distance === void 0) { distance = 100; }
  87551. };
  87552. VRExperienceHelperGazer.prototype.dispose = function () {
  87553. this._interactionsEnabled = false;
  87554. this._teleportationEnabled = false;
  87555. if (this._gazeTracker) {
  87556. this._gazeTracker.dispose();
  87557. }
  87558. };
  87559. VRExperienceHelperGazer._idCounter = 0;
  87560. return VRExperienceHelperGazer;
  87561. }());
  87562. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87563. __extends(VRExperienceHelperControllerGazer, _super);
  87564. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87565. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87566. _this.webVRController = webVRController;
  87567. // Laser pointer
  87568. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87569. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87570. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87571. laserPointerMaterial.alpha = 0.6;
  87572. _this._laserPointer.material = laserPointerMaterial;
  87573. _this._laserPointer.rotation.x = Math.PI / 2;
  87574. _this._laserPointer.position.z = -0.5;
  87575. _this._laserPointer.isVisible = false;
  87576. if (!webVRController.mesh) {
  87577. // Create an empty mesh that is used prior to loading the high quality model
  87578. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87579. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87580. preloadPointerPose.rotation.x = -0.7;
  87581. preloadMesh.addChild(preloadPointerPose);
  87582. webVRController.attachToMesh(preloadMesh);
  87583. }
  87584. _this._setLaserPointerParent(webVRController.mesh);
  87585. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87586. _this._setLaserPointerParent(mesh);
  87587. });
  87588. return _this;
  87589. }
  87590. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87591. return this.webVRController.getForwardRay(length);
  87592. };
  87593. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87594. _super.prototype._activatePointer.call(this);
  87595. this._laserPointer.isVisible = true;
  87596. };
  87597. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87598. _super.prototype._deactivatePointer.call(this);
  87599. this._laserPointer.isVisible = false;
  87600. };
  87601. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87602. this._laserPointer.material.emissiveColor = color;
  87603. };
  87604. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87605. var makeNotPick = function (root) {
  87606. root.name += " laserPointer";
  87607. root.getChildMeshes().forEach(function (c) {
  87608. makeNotPick(c);
  87609. });
  87610. };
  87611. makeNotPick(mesh);
  87612. var childMeshes = mesh.getChildMeshes();
  87613. this.webVRController._pointingPoseNode = null;
  87614. for (var i = 0; i < childMeshes.length; i++) {
  87615. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87616. mesh = childMeshes[i];
  87617. this.webVRController._pointingPoseNode = mesh;
  87618. break;
  87619. }
  87620. }
  87621. this._laserPointer.parent = mesh;
  87622. };
  87623. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87624. if (distance === void 0) { distance = 100; }
  87625. this._laserPointer.scaling.y = distance;
  87626. this._laserPointer.position.z = -distance / 2;
  87627. };
  87628. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87629. _super.prototype.dispose.call(this);
  87630. this._laserPointer.dispose();
  87631. if (this._meshAttachedObserver) {
  87632. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87633. }
  87634. };
  87635. return VRExperienceHelperControllerGazer;
  87636. }(VRExperienceHelperGazer));
  87637. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87638. __extends(VRExperienceHelperCameraGazer, _super);
  87639. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87640. var _this = _super.call(this, scene) || this;
  87641. _this.getCamera = getCamera;
  87642. return _this;
  87643. }
  87644. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87645. var camera = this.getCamera();
  87646. if (camera) {
  87647. return camera.getForwardRay(length);
  87648. }
  87649. else {
  87650. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87651. }
  87652. };
  87653. return VRExperienceHelperCameraGazer;
  87654. }(VRExperienceHelperGazer));
  87655. /**
  87656. * Helps to quickly add VR support to an existing scene.
  87657. * See http://doc.babylonjs.com/how_to/webvr_helper
  87658. */
  87659. var VRExperienceHelper = /** @class */ (function () {
  87660. /**
  87661. * Instantiates a VRExperienceHelper.
  87662. * Helps to quickly add VR support to an existing scene.
  87663. * @param scene The scene the VRExperienceHelper belongs to.
  87664. * @param webVROptions Options to modify the vr experience helper's behavior.
  87665. */
  87666. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87667. if (webVROptions === void 0) { webVROptions = {}; }
  87668. var _this = this;
  87669. this.webVROptions = webVROptions;
  87670. // Can the system support WebVR, even if a headset isn't plugged in?
  87671. this._webVRsupported = false;
  87672. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87673. this._webVRready = false;
  87674. // Are we waiting for the requestPresent callback to complete?
  87675. this._webVRrequesting = false;
  87676. // Are we presenting to the headset right now?
  87677. this._webVRpresenting = false;
  87678. // Are we presenting in the fullscreen fallback?
  87679. this._fullscreenVRpresenting = false;
  87680. /**
  87681. * Observable raised when entering VR.
  87682. */
  87683. this.onEnteringVRObservable = new BABYLON.Observable();
  87684. /**
  87685. * Observable raised when exiting VR.
  87686. */
  87687. this.onExitingVRObservable = new BABYLON.Observable();
  87688. /**
  87689. * Observable raised when controller mesh is loaded.
  87690. */
  87691. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87692. this._useCustomVRButton = false;
  87693. this._teleportationRequested = false;
  87694. this._teleportActive = false;
  87695. this._floorMeshesCollection = [];
  87696. this._rotationAllowed = true;
  87697. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87698. this._isDefaultTeleportationTarget = true;
  87699. this._teleportationFillColor = "#444444";
  87700. this._teleportationBorderColor = "#FFFFFF";
  87701. this._rotationAngle = 0;
  87702. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87703. this._padSensibilityUp = 0.65;
  87704. this._padSensibilityDown = 0.35;
  87705. this.leftController = null;
  87706. this.rightController = null;
  87707. /**
  87708. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87709. */
  87710. this.onNewMeshSelected = new BABYLON.Observable();
  87711. /**
  87712. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87713. */
  87714. this.onNewMeshPicked = new BABYLON.Observable();
  87715. /**
  87716. * Observable raised before camera teleportation
  87717. */
  87718. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87719. /**
  87720. * Observable raised after camera teleportation
  87721. */
  87722. this.onAfterCameraTeleport = new BABYLON.Observable();
  87723. /**
  87724. * Observable raised when current selected mesh gets unselected
  87725. */
  87726. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87727. /**
  87728. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87729. */
  87730. this.teleportationEnabled = true;
  87731. this._teleportationInitialized = false;
  87732. this._interactionsEnabled = false;
  87733. this._interactionsRequested = false;
  87734. this._displayGaze = true;
  87735. this._displayLaserPointer = true;
  87736. this._onResize = function () {
  87737. _this.moveButtonToBottomRight();
  87738. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87739. _this.exitVR();
  87740. }
  87741. };
  87742. this._onFullscreenChange = function () {
  87743. if (document.fullscreen !== undefined) {
  87744. _this._fullscreenVRpresenting = document.fullscreen;
  87745. }
  87746. else if (document.mozFullScreen !== undefined) {
  87747. _this._fullscreenVRpresenting = document.mozFullScreen;
  87748. }
  87749. else if (document.webkitIsFullScreen !== undefined) {
  87750. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87751. }
  87752. else if (document.msIsFullScreen !== undefined) {
  87753. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87754. }
  87755. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87756. _this.exitVR();
  87757. if (!_this._useCustomVRButton) {
  87758. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87759. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87760. }
  87761. }
  87762. };
  87763. this.beforeRender = function () {
  87764. if (_this.leftController && _this.leftController._activePointer) {
  87765. _this._castRayAndSelectObject(_this.leftController);
  87766. }
  87767. if (_this.rightController && _this.rightController._activePointer) {
  87768. _this._castRayAndSelectObject(_this.rightController);
  87769. }
  87770. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87771. _this._castRayAndSelectObject(_this._cameraGazer);
  87772. }
  87773. else {
  87774. _this._cameraGazer._gazeTracker.isVisible = false;
  87775. }
  87776. };
  87777. this._onNewGamepadConnected = function (gamepad) {
  87778. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87779. if (gamepad.leftStick) {
  87780. gamepad.onleftstickchanged(function (stickValues) {
  87781. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87782. // Listening to classic/xbox gamepad only if no VR controller is active
  87783. if ((!_this.leftController && !_this.rightController) ||
  87784. ((_this.leftController && !_this.leftController._activePointer) &&
  87785. (_this.rightController && !_this.rightController._activePointer))) {
  87786. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87787. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87788. }
  87789. }
  87790. });
  87791. }
  87792. if (gamepad.rightStick) {
  87793. gamepad.onrightstickchanged(function (stickValues) {
  87794. if (_this._teleportationInitialized) {
  87795. _this._checkRotate(stickValues, _this._cameraGazer);
  87796. }
  87797. });
  87798. }
  87799. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87800. gamepad.onbuttondown(function (buttonPressed) {
  87801. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87802. _this._cameraGazer._selectionPointerDown();
  87803. }
  87804. });
  87805. gamepad.onbuttonup(function (buttonPressed) {
  87806. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87807. _this._cameraGazer._selectionPointerUp();
  87808. }
  87809. });
  87810. }
  87811. }
  87812. else {
  87813. var webVRController = gamepad;
  87814. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87815. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87816. _this.rightController = controller;
  87817. }
  87818. else {
  87819. _this.leftController = controller;
  87820. }
  87821. _this._tryEnableInteractionOnController(controller);
  87822. }
  87823. };
  87824. // 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
  87825. this._tryEnableInteractionOnController = function (controller) {
  87826. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87827. _this._enableInteractionOnController(controller);
  87828. }
  87829. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87830. _this._enableTeleportationOnController(controller);
  87831. }
  87832. };
  87833. this._onNewGamepadDisconnected = function (gamepad) {
  87834. if (gamepad instanceof BABYLON.WebVRController) {
  87835. if (gamepad.hand === "left" && _this.leftController != null) {
  87836. _this.leftController.dispose();
  87837. _this.leftController = null;
  87838. }
  87839. if (gamepad.hand === "right" && _this.rightController != null) {
  87840. _this.rightController.dispose();
  87841. _this.rightController = null;
  87842. }
  87843. }
  87844. };
  87845. this._workingVector = BABYLON.Vector3.Zero();
  87846. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87847. this._workingMatrix = BABYLON.Matrix.Identity();
  87848. this._scene = scene;
  87849. this._canvas = scene.getEngine().getRenderingCanvas();
  87850. // Parse options
  87851. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87852. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87853. }
  87854. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87855. webVROptions.createDeviceOrientationCamera = true;
  87856. }
  87857. if (webVROptions.defaultHeight === undefined) {
  87858. webVROptions.defaultHeight = 1.7;
  87859. }
  87860. if (webVROptions.useCustomVRButton) {
  87861. this._useCustomVRButton = true;
  87862. if (webVROptions.customVRButton) {
  87863. this._btnVR = webVROptions.customVRButton;
  87864. }
  87865. }
  87866. if (webVROptions.rayLength) {
  87867. this._rayLength = webVROptions.rayLength;
  87868. }
  87869. this._defaultHeight = webVROptions.defaultHeight;
  87870. if (webVROptions.positionScale) {
  87871. this._rayLength *= webVROptions.positionScale;
  87872. this._defaultHeight *= webVROptions.positionScale;
  87873. }
  87874. // Set position
  87875. if (this._scene.activeCamera) {
  87876. this._position = this._scene.activeCamera.position.clone();
  87877. }
  87878. else {
  87879. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87880. }
  87881. // Set non-vr camera
  87882. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87883. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87884. // Copy data from existing camera
  87885. if (this._scene.activeCamera) {
  87886. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87887. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87888. // Set rotation from previous camera
  87889. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87890. var targetCamera = this._scene.activeCamera;
  87891. if (targetCamera.rotationQuaternion) {
  87892. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87893. }
  87894. else {
  87895. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87896. }
  87897. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87898. }
  87899. }
  87900. this._scene.activeCamera = this._deviceOrientationCamera;
  87901. if (this._canvas) {
  87902. this._scene.activeCamera.attachControl(this._canvas);
  87903. }
  87904. }
  87905. else {
  87906. this._existingCamera = this._scene.activeCamera;
  87907. }
  87908. // Create VR cameras
  87909. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87910. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87911. }
  87912. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87913. this._webVRCamera.useStandingMatrix();
  87914. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87915. // Create default button
  87916. if (!this._useCustomVRButton) {
  87917. this._btnVR = document.createElement("BUTTON");
  87918. this._btnVR.className = "babylonVRicon";
  87919. this._btnVR.id = "babylonVRiconbtn";
  87920. this._btnVR.title = "Click to switch to VR";
  87921. 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) }";
  87922. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87923. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87924. // css += ".babylonVRicon.vrdisplaysupported { }";
  87925. // css += ".babylonVRicon.vrdisplayready { }";
  87926. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87927. var style = document.createElement('style');
  87928. style.appendChild(document.createTextNode(css));
  87929. document.getElementsByTagName('head')[0].appendChild(style);
  87930. this.moveButtonToBottomRight();
  87931. }
  87932. // VR button click event
  87933. if (this._btnVR) {
  87934. this._btnVR.addEventListener("click", function () {
  87935. if (!_this.isInVRMode) {
  87936. _this.enterVR();
  87937. }
  87938. else {
  87939. _this.exitVR();
  87940. }
  87941. });
  87942. }
  87943. // Window events
  87944. window.addEventListener("resize", this._onResize);
  87945. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87946. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87947. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87948. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87949. // Display vr button when headset is connected
  87950. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87951. this.displayVRButton();
  87952. }
  87953. else {
  87954. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87955. if (e.vrDisplay) {
  87956. _this.displayVRButton();
  87957. }
  87958. });
  87959. }
  87960. // Exiting VR mode using 'ESC' key on desktop
  87961. this._onKeyDown = function (event) {
  87962. if (event.keyCode === 27 && _this.isInVRMode) {
  87963. _this.exitVR();
  87964. }
  87965. };
  87966. document.addEventListener("keydown", this._onKeyDown);
  87967. // Exiting VR mode double tapping the touch screen
  87968. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87969. if (_this.isInVRMode) {
  87970. _this.exitVR();
  87971. if (_this._fullscreenVRpresenting) {
  87972. _this._scene.getEngine().switchFullscreen(true);
  87973. }
  87974. }
  87975. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87976. // Listen for WebVR display changes
  87977. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87978. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87979. this._onVRRequestPresentStart = function () {
  87980. _this._webVRrequesting = true;
  87981. _this.updateButtonVisibility();
  87982. };
  87983. this._onVRRequestPresentComplete = function (success) {
  87984. _this._webVRrequesting = false;
  87985. _this.updateButtonVisibility();
  87986. };
  87987. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87988. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87989. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87990. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87991. scene.onDisposeObservable.add(function () {
  87992. _this.dispose();
  87993. });
  87994. // Gamepad connection events
  87995. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87996. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87997. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87998. this.updateButtonVisibility();
  87999. //create easing functions
  88000. this._circleEase = new BABYLON.CircleEase();
  88001. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88002. }
  88003. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88004. /** Return this.onEnteringVRObservable
  88005. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88006. */
  88007. get: function () {
  88008. return this.onEnteringVRObservable;
  88009. },
  88010. enumerable: true,
  88011. configurable: true
  88012. });
  88013. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88014. /** Return this.onExitingVRObservable
  88015. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88016. */
  88017. get: function () {
  88018. return this.onExitingVRObservable;
  88019. },
  88020. enumerable: true,
  88021. configurable: true
  88022. });
  88023. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88024. /** Return this.onControllerMeshLoadedObservable
  88025. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88026. */
  88027. get: function () {
  88028. return this.onControllerMeshLoadedObservable;
  88029. },
  88030. enumerable: true,
  88031. configurable: true
  88032. });
  88033. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88034. /**
  88035. * The mesh used to display where the user is going to teleport.
  88036. */
  88037. get: function () {
  88038. return this._teleportationTarget;
  88039. },
  88040. /**
  88041. * Sets the mesh to be used to display where the user is going to teleport.
  88042. */
  88043. set: function (value) {
  88044. if (value) {
  88045. value.name = "teleportationTarget";
  88046. this._isDefaultTeleportationTarget = false;
  88047. this._teleportationTarget = value;
  88048. }
  88049. },
  88050. enumerable: true,
  88051. configurable: true
  88052. });
  88053. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88054. /**
  88055. * The mesh used to display where the user is selecting,
  88056. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88057. * See http://doc.babylonjs.com/resources/baking_transformations
  88058. */
  88059. get: function () {
  88060. return this._cameraGazer._gazeTracker;
  88061. },
  88062. set: function (value) {
  88063. if (value) {
  88064. this._cameraGazer._gazeTracker = value;
  88065. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88066. this._cameraGazer._gazeTracker.isPickable = false;
  88067. this._cameraGazer._gazeTracker.isVisible = false;
  88068. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88069. if (this.leftController) {
  88070. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88071. }
  88072. if (this.rightController) {
  88073. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88074. }
  88075. }
  88076. },
  88077. enumerable: true,
  88078. configurable: true
  88079. });
  88080. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88081. /**
  88082. * If the ray of the gaze should be displayed.
  88083. */
  88084. get: function () {
  88085. return this._displayGaze;
  88086. },
  88087. /**
  88088. * Sets if the ray of the gaze should be displayed.
  88089. */
  88090. set: function (value) {
  88091. this._displayGaze = value;
  88092. if (!value) {
  88093. this._cameraGazer._gazeTracker.isVisible = false;
  88094. if (this.leftController) {
  88095. this.leftController._gazeTracker.isVisible = false;
  88096. }
  88097. if (this.rightController) {
  88098. this.rightController._gazeTracker.isVisible = false;
  88099. }
  88100. }
  88101. },
  88102. enumerable: true,
  88103. configurable: true
  88104. });
  88105. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88106. /**
  88107. * If the ray of the LaserPointer should be displayed.
  88108. */
  88109. get: function () {
  88110. return this._displayLaserPointer;
  88111. },
  88112. /**
  88113. * Sets if the ray of the LaserPointer should be displayed.
  88114. */
  88115. set: function (value) {
  88116. this._displayLaserPointer = value;
  88117. if (!value) {
  88118. if (this.rightController) {
  88119. this.rightController._deactivatePointer();
  88120. this.rightController._gazeTracker.isVisible = false;
  88121. }
  88122. if (this.leftController) {
  88123. this.leftController._deactivatePointer();
  88124. this.leftController._gazeTracker.isVisible = false;
  88125. }
  88126. }
  88127. else {
  88128. if (this.rightController) {
  88129. this.rightController._activatePointer();
  88130. }
  88131. if (this.leftController) {
  88132. this.leftController._activatePointer();
  88133. }
  88134. }
  88135. },
  88136. enumerable: true,
  88137. configurable: true
  88138. });
  88139. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88140. /**
  88141. * The deviceOrientationCamera used as the camera when not in VR.
  88142. */
  88143. get: function () {
  88144. return this._deviceOrientationCamera;
  88145. },
  88146. enumerable: true,
  88147. configurable: true
  88148. });
  88149. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88150. /**
  88151. * Based on the current WebVR support, returns the current VR camera used.
  88152. */
  88153. get: function () {
  88154. if (this._webVRready) {
  88155. return this._webVRCamera;
  88156. }
  88157. else {
  88158. return this._scene.activeCamera;
  88159. }
  88160. },
  88161. enumerable: true,
  88162. configurable: true
  88163. });
  88164. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88165. /**
  88166. * The webVRCamera which is used when in VR.
  88167. */
  88168. get: function () {
  88169. return this._webVRCamera;
  88170. },
  88171. enumerable: true,
  88172. configurable: true
  88173. });
  88174. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88175. /**
  88176. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88177. */
  88178. get: function () {
  88179. return this._vrDeviceOrientationCamera;
  88180. },
  88181. enumerable: true,
  88182. configurable: true
  88183. });
  88184. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88185. get: function () {
  88186. var result = this._cameraGazer._teleportationRequestInitiated
  88187. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88188. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88189. return result;
  88190. },
  88191. enumerable: true,
  88192. configurable: true
  88193. });
  88194. // Raised when one of the controller has loaded successfully its associated default mesh
  88195. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88196. if (this.leftController && this.leftController.webVRController == webVRController) {
  88197. if (webVRController.mesh) {
  88198. this.leftController._setLaserPointerParent(webVRController.mesh);
  88199. }
  88200. }
  88201. if (this.rightController && this.rightController.webVRController == webVRController) {
  88202. if (webVRController.mesh) {
  88203. this.rightController._setLaserPointerParent(webVRController.mesh);
  88204. }
  88205. }
  88206. try {
  88207. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88208. }
  88209. catch (err) {
  88210. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88211. }
  88212. };
  88213. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88214. /**
  88215. * Gets a value indicating if we are currently in VR mode.
  88216. */
  88217. get: function () {
  88218. return this._webVRpresenting || this._fullscreenVRpresenting;
  88219. },
  88220. enumerable: true,
  88221. configurable: true
  88222. });
  88223. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88224. var vrDisplay = this._scene.getEngine().getVRDevice();
  88225. if (vrDisplay) {
  88226. var wasPresenting = this._webVRpresenting;
  88227. // A VR display is connected
  88228. this._webVRpresenting = vrDisplay.isPresenting;
  88229. if (wasPresenting && !this._webVRpresenting)
  88230. this.exitVR();
  88231. }
  88232. else {
  88233. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88234. }
  88235. this.updateButtonVisibility();
  88236. };
  88237. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88238. this._webVRsupported = eventArgs.vrSupported;
  88239. this._webVRready = !!eventArgs.vrDisplay;
  88240. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88241. this.updateButtonVisibility();
  88242. };
  88243. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88244. if (this._canvas && !this._useCustomVRButton) {
  88245. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88246. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88247. }
  88248. };
  88249. VRExperienceHelper.prototype.displayVRButton = function () {
  88250. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88251. document.body.appendChild(this._btnVR);
  88252. this._btnVRDisplayed = true;
  88253. }
  88254. };
  88255. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88256. if (!this._btnVR || this._useCustomVRButton) {
  88257. return;
  88258. }
  88259. this._btnVR.className = "babylonVRicon";
  88260. if (this.isInVRMode) {
  88261. this._btnVR.className += " vrdisplaypresenting";
  88262. }
  88263. else {
  88264. if (this._webVRready)
  88265. this._btnVR.className += " vrdisplayready";
  88266. if (this._webVRsupported)
  88267. this._btnVR.className += " vrdisplaysupported";
  88268. if (this._webVRrequesting)
  88269. this._btnVR.className += " vrdisplayrequesting";
  88270. }
  88271. };
  88272. /**
  88273. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88274. * Otherwise, will use the fullscreen API.
  88275. */
  88276. VRExperienceHelper.prototype.enterVR = function () {
  88277. if (this.onEnteringVRObservable) {
  88278. try {
  88279. this.onEnteringVRObservable.notifyObservers(this);
  88280. }
  88281. catch (err) {
  88282. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88283. }
  88284. }
  88285. if (this._scene.activeCamera) {
  88286. this._position = this._scene.activeCamera.position.clone();
  88287. // make sure that we return to the last active camera
  88288. this._existingCamera = this._scene.activeCamera;
  88289. }
  88290. if (this._webVRrequesting)
  88291. return;
  88292. // If WebVR is supported and a headset is connected
  88293. if (this._webVRready) {
  88294. if (!this._webVRpresenting) {
  88295. this._webVRCamera.position = this._position;
  88296. this._scene.activeCamera = this._webVRCamera;
  88297. }
  88298. }
  88299. else if (this._vrDeviceOrientationCamera) {
  88300. this._vrDeviceOrientationCamera.position = this._position;
  88301. if (this._scene.activeCamera) {
  88302. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88303. }
  88304. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88305. this._scene.getEngine().switchFullscreen(true);
  88306. this.updateButtonVisibility();
  88307. }
  88308. if (this._scene.activeCamera && this._canvas) {
  88309. this._scene.activeCamera.attachControl(this._canvas);
  88310. }
  88311. if (this._interactionsEnabled) {
  88312. this._scene.registerBeforeRender(this.beforeRender);
  88313. }
  88314. };
  88315. /**
  88316. * Attempt to exit VR, or fullscreen.
  88317. */
  88318. VRExperienceHelper.prototype.exitVR = function () {
  88319. if (this.onExitingVRObservable) {
  88320. try {
  88321. this.onExitingVRObservable.notifyObservers(this);
  88322. }
  88323. catch (err) {
  88324. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88325. }
  88326. }
  88327. if (this._webVRpresenting) {
  88328. this._scene.getEngine().disableVR();
  88329. }
  88330. if (this._scene.activeCamera) {
  88331. this._position = this._scene.activeCamera.position.clone();
  88332. }
  88333. if (this._deviceOrientationCamera) {
  88334. this._deviceOrientationCamera.position = this._position;
  88335. this._scene.activeCamera = this._deviceOrientationCamera;
  88336. if (this._canvas) {
  88337. this._scene.activeCamera.attachControl(this._canvas);
  88338. }
  88339. }
  88340. else if (this._existingCamera) {
  88341. this._existingCamera.position = this._position;
  88342. this._scene.activeCamera = this._existingCamera;
  88343. }
  88344. this.updateButtonVisibility();
  88345. if (this._interactionsEnabled) {
  88346. this._scene.unregisterBeforeRender(this.beforeRender);
  88347. }
  88348. // resize to update width and height when exiting vr exits fullscreen
  88349. this._scene.getEngine().resize();
  88350. };
  88351. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88352. /**
  88353. * The position of the vr experience helper.
  88354. */
  88355. get: function () {
  88356. return this._position;
  88357. },
  88358. /**
  88359. * Sets the position of the vr experience helper.
  88360. */
  88361. set: function (value) {
  88362. this._position = value;
  88363. if (this._scene.activeCamera) {
  88364. this._scene.activeCamera.position = value;
  88365. }
  88366. },
  88367. enumerable: true,
  88368. configurable: true
  88369. });
  88370. /**
  88371. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88372. */
  88373. VRExperienceHelper.prototype.enableInteractions = function () {
  88374. var _this = this;
  88375. if (!this._interactionsEnabled) {
  88376. this._interactionsRequested = true;
  88377. if (this.leftController) {
  88378. this._enableInteractionOnController(this.leftController);
  88379. }
  88380. if (this.rightController) {
  88381. this._enableInteractionOnController(this.rightController);
  88382. }
  88383. this.raySelectionPredicate = function (mesh) {
  88384. return mesh.isVisible;
  88385. };
  88386. this.meshSelectionPredicate = function (mesh) {
  88387. return true;
  88388. };
  88389. this._raySelectionPredicate = function (mesh) {
  88390. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88391. && mesh.name.indexOf("teleportationTarget") === -1
  88392. && mesh.name.indexOf("torusTeleportation") === -1
  88393. && mesh.name.indexOf("laserPointer") === -1)) {
  88394. return _this.raySelectionPredicate(mesh);
  88395. }
  88396. return false;
  88397. };
  88398. this._interactionsEnabled = true;
  88399. }
  88400. };
  88401. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88402. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88403. if (this._floorMeshesCollection[i].id === mesh.id) {
  88404. return true;
  88405. }
  88406. }
  88407. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88408. return true;
  88409. }
  88410. return false;
  88411. };
  88412. /**
  88413. * Adds a floor mesh to be used for teleportation.
  88414. * @param floorMesh the mesh to be used for teleportation.
  88415. */
  88416. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88417. if (!this._floorMeshesCollection) {
  88418. return;
  88419. }
  88420. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88421. return;
  88422. }
  88423. this._floorMeshesCollection.push(floorMesh);
  88424. };
  88425. /**
  88426. * Removes a floor mesh from being used for teleportation.
  88427. * @param floorMesh the mesh to be removed.
  88428. */
  88429. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88430. if (!this._floorMeshesCollection) {
  88431. return;
  88432. }
  88433. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88434. if (meshIndex !== -1) {
  88435. this._floorMeshesCollection.splice(meshIndex, 1);
  88436. }
  88437. };
  88438. /**
  88439. * Enables interactions and teleportation using the VR controllers and gaze.
  88440. * @param vrTeleportationOptions options to modify teleportation behavior.
  88441. */
  88442. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88443. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88444. if (!this._teleportationInitialized) {
  88445. this._teleportationRequested = true;
  88446. this.enableInteractions();
  88447. if (vrTeleportationOptions.floorMeshName) {
  88448. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88449. }
  88450. if (vrTeleportationOptions.floorMeshes) {
  88451. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88452. }
  88453. if (this.leftController != null) {
  88454. this._enableTeleportationOnController(this.leftController);
  88455. }
  88456. if (this.rightController != null) {
  88457. this._enableTeleportationOnController(this.rightController);
  88458. }
  88459. // Creates an image processing post process for the vignette not relying
  88460. // on the main scene configuration for image processing to reduce setup and spaces
  88461. // (gamma/linear) conflicts.
  88462. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88463. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88464. imageProcessingConfiguration.vignetteEnabled = true;
  88465. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88466. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88467. this._teleportationInitialized = true;
  88468. if (this._isDefaultTeleportationTarget) {
  88469. this._createTeleportationCircles();
  88470. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88471. }
  88472. }
  88473. };
  88474. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88475. var _this = this;
  88476. var controllerMesh = controller.webVRController.mesh;
  88477. if (controllerMesh) {
  88478. controller._interactionsEnabled = true;
  88479. controller._activatePointer();
  88480. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88481. // Enabling / disabling laserPointer
  88482. if (_this._displayLaserPointer && stateObject.value === 1) {
  88483. if (controller._activePointer) {
  88484. controller._deactivatePointer();
  88485. }
  88486. else {
  88487. controller._activatePointer();
  88488. }
  88489. if (_this.displayGaze) {
  88490. controller._gazeTracker.isVisible = controller._activePointer;
  88491. }
  88492. }
  88493. });
  88494. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88495. if (!controller._pointerDownOnMeshAsked) {
  88496. if (stateObject.value > _this._padSensibilityUp) {
  88497. controller._selectionPointerDown();
  88498. }
  88499. }
  88500. else if (stateObject.value < _this._padSensibilityDown) {
  88501. controller._selectionPointerUp();
  88502. }
  88503. });
  88504. }
  88505. };
  88506. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88507. // Dont teleport if another gaze already requested teleportation
  88508. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88509. return;
  88510. }
  88511. if (!gazer._teleportationRequestInitiated) {
  88512. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88513. gazer._activatePointer();
  88514. gazer._teleportationRequestInitiated = true;
  88515. }
  88516. }
  88517. else {
  88518. // Listening to the proper controller values changes to confirm teleportation
  88519. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88520. if (this._teleportActive) {
  88521. this._teleportCamera(this._haloCenter);
  88522. }
  88523. gazer._teleportationRequestInitiated = false;
  88524. }
  88525. }
  88526. };
  88527. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88528. // Only rotate when user is not currently selecting a teleportation location
  88529. if (gazer._teleportationRequestInitiated) {
  88530. return;
  88531. }
  88532. if (!gazer._rotationLeftAsked) {
  88533. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88534. gazer._rotationLeftAsked = true;
  88535. if (this._rotationAllowed) {
  88536. this._rotateCamera(false);
  88537. }
  88538. }
  88539. }
  88540. else {
  88541. if (stateObject.x > -this._padSensibilityDown) {
  88542. gazer._rotationLeftAsked = false;
  88543. }
  88544. }
  88545. if (!gazer._rotationRightAsked) {
  88546. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88547. gazer._rotationRightAsked = true;
  88548. if (this._rotationAllowed) {
  88549. this._rotateCamera(true);
  88550. }
  88551. }
  88552. }
  88553. else {
  88554. if (stateObject.x < this._padSensibilityDown) {
  88555. gazer._rotationRightAsked = false;
  88556. }
  88557. }
  88558. };
  88559. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88560. // Only teleport backwards when user is not currently selecting a teleportation location
  88561. if (gazer._teleportationRequestInitiated) {
  88562. return;
  88563. }
  88564. // Teleport backwards
  88565. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88566. if (!gazer._teleportationBackRequestInitiated) {
  88567. if (!this.currentVRCamera) {
  88568. return;
  88569. }
  88570. // Get rotation and position of the current camera
  88571. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88572. var position = this.currentVRCamera.position;
  88573. // If the camera has device position, use that instead
  88574. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88575. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88576. position = this.currentVRCamera.devicePosition;
  88577. }
  88578. // Get matrix with only the y rotation of the device rotation
  88579. rotation.toEulerAnglesToRef(this._workingVector);
  88580. this._workingVector.z = 0;
  88581. this._workingVector.x = 0;
  88582. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88583. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88584. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88585. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88586. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88587. var ray = new BABYLON.Ray(position, this._workingVector);
  88588. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88589. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88590. this._teleportCamera(hit.pickedPoint);
  88591. }
  88592. gazer._teleportationBackRequestInitiated = true;
  88593. }
  88594. }
  88595. else {
  88596. gazer._teleportationBackRequestInitiated = false;
  88597. }
  88598. };
  88599. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88600. var _this = this;
  88601. var controllerMesh = controller.webVRController.mesh;
  88602. if (controllerMesh) {
  88603. if (!controller._interactionsEnabled) {
  88604. this._enableInteractionOnController(controller);
  88605. }
  88606. controller._interactionsEnabled = true;
  88607. controller._teleportationEnabled = true;
  88608. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88609. controller._dpadPressed = false;
  88610. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88611. controller._dpadPressed = stateObject.pressed;
  88612. if (!controller._dpadPressed) {
  88613. controller._rotationLeftAsked = false;
  88614. controller._rotationRightAsked = false;
  88615. controller._teleportationBackRequestInitiated = false;
  88616. }
  88617. });
  88618. }
  88619. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88620. if (_this.teleportationEnabled) {
  88621. _this._checkTeleportBackwards(stateObject, controller);
  88622. _this._checkTeleportWithRay(stateObject, controller);
  88623. }
  88624. _this._checkRotate(stateObject, controller);
  88625. });
  88626. }
  88627. };
  88628. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88629. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88630. this._teleportationTarget.isPickable = false;
  88631. var length = 512;
  88632. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88633. dynamicTexture.hasAlpha = true;
  88634. var context = dynamicTexture.getContext();
  88635. var centerX = length / 2;
  88636. var centerY = length / 2;
  88637. var radius = 200;
  88638. context.beginPath();
  88639. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88640. context.fillStyle = this._teleportationFillColor;
  88641. context.fill();
  88642. context.lineWidth = 10;
  88643. context.strokeStyle = this._teleportationBorderColor;
  88644. context.stroke();
  88645. context.closePath();
  88646. dynamicTexture.update();
  88647. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88648. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88649. this._teleportationTarget.material = teleportationCircleMaterial;
  88650. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88651. torus.isPickable = false;
  88652. torus.parent = this._teleportationTarget;
  88653. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88654. var keys = [];
  88655. keys.push({
  88656. frame: 0,
  88657. value: 0
  88658. });
  88659. keys.push({
  88660. frame: 30,
  88661. value: 0.4
  88662. });
  88663. keys.push({
  88664. frame: 60,
  88665. value: 0
  88666. });
  88667. animationInnerCircle.setKeys(keys);
  88668. var easingFunction = new BABYLON.SineEase();
  88669. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88670. animationInnerCircle.setEasingFunction(easingFunction);
  88671. torus.animations = [];
  88672. torus.animations.push(animationInnerCircle);
  88673. this._scene.beginAnimation(torus, 0, 60, true);
  88674. this._hideTeleportationTarget();
  88675. };
  88676. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88677. this._teleportActive = true;
  88678. if (this._teleportationInitialized) {
  88679. this._teleportationTarget.isVisible = true;
  88680. if (this._isDefaultTeleportationTarget) {
  88681. this._teleportationTarget.getChildren()[0].isVisible = true;
  88682. }
  88683. }
  88684. };
  88685. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88686. this._teleportActive = false;
  88687. if (this._teleportationInitialized) {
  88688. this._teleportationTarget.isVisible = false;
  88689. if (this._isDefaultTeleportationTarget) {
  88690. this._teleportationTarget.getChildren()[0].isVisible = false;
  88691. }
  88692. }
  88693. };
  88694. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88695. var _this = this;
  88696. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88697. return;
  88698. }
  88699. if (right) {
  88700. this._rotationAngle++;
  88701. }
  88702. else {
  88703. this._rotationAngle--;
  88704. }
  88705. this.currentVRCamera.animations = [];
  88706. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88707. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88708. var animationRotationKeys = [];
  88709. animationRotationKeys.push({
  88710. frame: 0,
  88711. value: this.currentVRCamera.rotationQuaternion
  88712. });
  88713. animationRotationKeys.push({
  88714. frame: 6,
  88715. value: target
  88716. });
  88717. animationRotation.setKeys(animationRotationKeys);
  88718. animationRotation.setEasingFunction(this._circleEase);
  88719. this.currentVRCamera.animations.push(animationRotation);
  88720. this._postProcessMove.animations = [];
  88721. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88722. var vignetteWeightKeys = [];
  88723. vignetteWeightKeys.push({
  88724. frame: 0,
  88725. value: 0
  88726. });
  88727. vignetteWeightKeys.push({
  88728. frame: 3,
  88729. value: 4
  88730. });
  88731. vignetteWeightKeys.push({
  88732. frame: 6,
  88733. value: 0
  88734. });
  88735. animationPP.setKeys(vignetteWeightKeys);
  88736. animationPP.setEasingFunction(this._circleEase);
  88737. this._postProcessMove.animations.push(animationPP);
  88738. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88739. var vignetteStretchKeys = [];
  88740. vignetteStretchKeys.push({
  88741. frame: 0,
  88742. value: 0
  88743. });
  88744. vignetteStretchKeys.push({
  88745. frame: 3,
  88746. value: 10
  88747. });
  88748. vignetteStretchKeys.push({
  88749. frame: 6,
  88750. value: 0
  88751. });
  88752. animationPP2.setKeys(vignetteStretchKeys);
  88753. animationPP2.setEasingFunction(this._circleEase);
  88754. this._postProcessMove.animations.push(animationPP2);
  88755. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88756. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88757. this._postProcessMove.samples = 4;
  88758. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88759. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88760. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88761. });
  88762. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88763. };
  88764. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88765. if (hit.pickedPoint) {
  88766. if (gazer._teleportationRequestInitiated) {
  88767. this._displayTeleportationTarget();
  88768. this._haloCenter.copyFrom(hit.pickedPoint);
  88769. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88770. }
  88771. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88772. if (pickNormal) {
  88773. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88774. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88775. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88776. }
  88777. this._teleportationTarget.position.y += 0.1;
  88778. }
  88779. };
  88780. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88781. var _this = this;
  88782. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88783. return;
  88784. }
  88785. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88786. // offset of the headset from the anchor.
  88787. if (this.webVRCamera.leftCamera) {
  88788. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88789. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88790. location.subtractToRef(this._workingVector, this._workingVector);
  88791. }
  88792. else {
  88793. this._workingVector.copyFrom(location);
  88794. }
  88795. // Add height to account for user's height offset
  88796. if (this.isInVRMode) {
  88797. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88798. }
  88799. else {
  88800. this._workingVector.y += this._defaultHeight;
  88801. }
  88802. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88803. // Create animation from the camera's position to the new location
  88804. this.currentVRCamera.animations = [];
  88805. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88806. var animationCameraTeleportationKeys = [{
  88807. frame: 0,
  88808. value: this.currentVRCamera.position
  88809. },
  88810. {
  88811. frame: 11,
  88812. value: this._workingVector
  88813. }
  88814. ];
  88815. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88816. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88817. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88818. this._postProcessMove.animations = [];
  88819. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88820. var vignetteWeightKeys = [];
  88821. vignetteWeightKeys.push({
  88822. frame: 0,
  88823. value: 0
  88824. });
  88825. vignetteWeightKeys.push({
  88826. frame: 5,
  88827. value: 8
  88828. });
  88829. vignetteWeightKeys.push({
  88830. frame: 11,
  88831. value: 0
  88832. });
  88833. animationPP.setKeys(vignetteWeightKeys);
  88834. this._postProcessMove.animations.push(animationPP);
  88835. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88836. var vignetteStretchKeys = [];
  88837. vignetteStretchKeys.push({
  88838. frame: 0,
  88839. value: 0
  88840. });
  88841. vignetteStretchKeys.push({
  88842. frame: 5,
  88843. value: 10
  88844. });
  88845. vignetteStretchKeys.push({
  88846. frame: 11,
  88847. value: 0
  88848. });
  88849. animationPP2.setKeys(vignetteStretchKeys);
  88850. this._postProcessMove.animations.push(animationPP2);
  88851. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88852. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88853. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88854. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88855. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88856. });
  88857. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88858. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88859. });
  88860. this._hideTeleportationTarget();
  88861. };
  88862. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88863. if (normal) {
  88864. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88865. if (angle < Math.PI / 2) {
  88866. normal.scaleInPlace(-1);
  88867. }
  88868. }
  88869. return normal;
  88870. };
  88871. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88872. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88873. return;
  88874. }
  88875. var ray = gazer._getForwardRay(this._rayLength);
  88876. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88877. // Moving the gazeTracker on the mesh face targetted
  88878. if (hit && hit.pickedPoint) {
  88879. if (this._displayGaze) {
  88880. var multiplier = 1;
  88881. gazer._gazeTracker.isVisible = true;
  88882. if (gazer._isActionableMesh) {
  88883. multiplier = 3;
  88884. }
  88885. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88886. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88887. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88888. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88889. // To avoid z-fighting
  88890. var deltaFighting = 0.002;
  88891. if (pickNormal) {
  88892. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88893. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88894. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88895. }
  88896. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88897. if (gazer._gazeTracker.position.x < 0) {
  88898. gazer._gazeTracker.position.x += deltaFighting;
  88899. }
  88900. else {
  88901. gazer._gazeTracker.position.x -= deltaFighting;
  88902. }
  88903. if (gazer._gazeTracker.position.y < 0) {
  88904. gazer._gazeTracker.position.y += deltaFighting;
  88905. }
  88906. else {
  88907. gazer._gazeTracker.position.y -= deltaFighting;
  88908. }
  88909. if (gazer._gazeTracker.position.z < 0) {
  88910. gazer._gazeTracker.position.z += deltaFighting;
  88911. }
  88912. else {
  88913. gazer._gazeTracker.position.z -= deltaFighting;
  88914. }
  88915. }
  88916. // Changing the size of the laser pointer based on the distance from the targetted point
  88917. gazer._updatePointerDistance(hit.distance);
  88918. }
  88919. else {
  88920. gazer._updatePointerDistance();
  88921. gazer._gazeTracker.isVisible = false;
  88922. }
  88923. if (hit && hit.pickedMesh) {
  88924. gazer._currentHit = hit;
  88925. if (gazer._pointerDownOnMeshAsked) {
  88926. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88927. }
  88928. // The object selected is the floor, we're in a teleportation scenario
  88929. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88930. // Moving the teleportation area to this targetted point
  88931. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88932. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88933. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88934. }
  88935. gazer._currentMeshSelected = null;
  88936. if (gazer._teleportationRequestInitiated) {
  88937. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88938. }
  88939. return;
  88940. }
  88941. // If not, we're in a selection scenario
  88942. //this._teleportationAllowed = false;
  88943. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88944. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88945. this.onNewMeshPicked.notifyObservers(hit);
  88946. gazer._currentMeshSelected = hit.pickedMesh;
  88947. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88948. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88949. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88950. gazer._isActionableMesh = true;
  88951. }
  88952. else {
  88953. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88954. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88955. gazer._isActionableMesh = false;
  88956. }
  88957. try {
  88958. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88959. }
  88960. catch (err) {
  88961. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88962. }
  88963. }
  88964. else {
  88965. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88966. gazer._currentMeshSelected = null;
  88967. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88968. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88969. }
  88970. }
  88971. }
  88972. else {
  88973. gazer._currentHit = null;
  88974. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88975. gazer._currentMeshSelected = null;
  88976. //this._teleportationAllowed = false;
  88977. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88978. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88979. }
  88980. };
  88981. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88982. if (mesh) {
  88983. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88984. }
  88985. };
  88986. /**
  88987. * Sets the color of the laser ray from the vr controllers.
  88988. * @param color new color for the ray.
  88989. */
  88990. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88991. if (this.leftController) {
  88992. this.leftController._setLaserPointerColor(color);
  88993. }
  88994. if (this.rightController) {
  88995. this.rightController._setLaserPointerColor(color);
  88996. }
  88997. };
  88998. /**
  88999. * Sets the color of the ray from the vr headsets gaze.
  89000. * @param color new color for the ray.
  89001. */
  89002. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89003. if (!this._cameraGazer._gazeTracker.material) {
  89004. return;
  89005. }
  89006. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89007. if (this.leftController) {
  89008. this.leftController._gazeTracker.material.emissiveColor = color;
  89009. }
  89010. if (this.rightController) {
  89011. this.rightController._gazeTracker.material.emissiveColor = color;
  89012. }
  89013. };
  89014. /**
  89015. * Exits VR and disposes of the vr experience helper
  89016. */
  89017. VRExperienceHelper.prototype.dispose = function () {
  89018. if (this.isInVRMode) {
  89019. this.exitVR();
  89020. }
  89021. if (this._postProcessMove) {
  89022. this._postProcessMove.dispose();
  89023. }
  89024. if (this._webVRCamera) {
  89025. this._webVRCamera.dispose();
  89026. }
  89027. if (this._vrDeviceOrientationCamera) {
  89028. this._vrDeviceOrientationCamera.dispose();
  89029. }
  89030. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89031. document.body.removeChild(this._btnVR);
  89032. }
  89033. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89034. this._deviceOrientationCamera.dispose();
  89035. }
  89036. if (this._cameraGazer) {
  89037. this._cameraGazer.dispose();
  89038. }
  89039. if (this.leftController) {
  89040. this.leftController.dispose();
  89041. }
  89042. if (this.rightController) {
  89043. this.rightController.dispose();
  89044. }
  89045. if (this._teleportationTarget) {
  89046. this._teleportationTarget.dispose();
  89047. }
  89048. this._floorMeshesCollection = [];
  89049. document.removeEventListener("keydown", this._onKeyDown);
  89050. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89051. window.removeEventListener("resize", this._onResize);
  89052. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89053. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89054. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89055. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89056. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89057. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89058. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89059. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89060. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89061. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89062. this._scene.unregisterBeforeRender(this.beforeRender);
  89063. };
  89064. /**
  89065. * Gets the name of the VRExperienceHelper class
  89066. * @returns "VRExperienceHelper"
  89067. */
  89068. VRExperienceHelper.prototype.getClassName = function () {
  89069. return "VRExperienceHelper";
  89070. };
  89071. return VRExperienceHelper;
  89072. }());
  89073. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89074. })(BABYLON || (BABYLON = {}));
  89075. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89076. // Mainly based on these 2 articles :
  89077. // 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
  89078. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89079. var BABYLON;
  89080. (function (BABYLON) {
  89081. /**
  89082. * Defines the potential axis of a Joystick
  89083. */
  89084. var JoystickAxis;
  89085. (function (JoystickAxis) {
  89086. /** X axis */
  89087. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89088. /** Y axis */
  89089. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89090. /** Z axis */
  89091. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89092. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89093. /**
  89094. * Class used to define virtual joystick (used in touch mode)
  89095. */
  89096. var VirtualJoystick = /** @class */ (function () {
  89097. /**
  89098. * Creates a new virtual joystick
  89099. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89100. */
  89101. function VirtualJoystick(leftJoystick) {
  89102. var _this = this;
  89103. if (leftJoystick) {
  89104. this._leftJoystick = true;
  89105. }
  89106. else {
  89107. this._leftJoystick = false;
  89108. }
  89109. VirtualJoystick._globalJoystickIndex++;
  89110. // By default left & right arrow keys are moving the X
  89111. // and up & down keys are moving the Y
  89112. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89113. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89114. this.reverseLeftRight = false;
  89115. this.reverseUpDown = false;
  89116. // collections of pointers
  89117. this._touches = new BABYLON.StringDictionary();
  89118. this.deltaPosition = BABYLON.Vector3.Zero();
  89119. this._joystickSensibility = 25;
  89120. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89121. this._onResize = function (evt) {
  89122. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89123. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89124. if (VirtualJoystick.vjCanvas) {
  89125. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89126. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89127. }
  89128. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89129. };
  89130. // injecting a canvas element on top of the canvas 3D game
  89131. if (!VirtualJoystick.vjCanvas) {
  89132. window.addEventListener("resize", this._onResize, false);
  89133. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89134. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89135. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89136. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89137. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89138. VirtualJoystick.vjCanvas.style.width = "100%";
  89139. VirtualJoystick.vjCanvas.style.height = "100%";
  89140. VirtualJoystick.vjCanvas.style.position = "absolute";
  89141. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89142. VirtualJoystick.vjCanvas.style.top = "0px";
  89143. VirtualJoystick.vjCanvas.style.left = "0px";
  89144. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89145. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89146. // Support for jQuery PEP polyfill
  89147. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89148. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89149. if (!context) {
  89150. throw new Error("Unable to create canvas for virtual joystick");
  89151. }
  89152. VirtualJoystick.vjCanvasContext = context;
  89153. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89154. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89155. document.body.appendChild(VirtualJoystick.vjCanvas);
  89156. }
  89157. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89158. this.pressed = false;
  89159. // default joystick color
  89160. this._joystickColor = "cyan";
  89161. this._joystickPointerID = -1;
  89162. // current joystick position
  89163. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89164. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89165. // origin joystick position
  89166. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89167. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89168. this._onPointerDownHandlerRef = function (evt) {
  89169. _this._onPointerDown(evt);
  89170. };
  89171. this._onPointerMoveHandlerRef = function (evt) {
  89172. _this._onPointerMove(evt);
  89173. };
  89174. this._onPointerUpHandlerRef = function (evt) {
  89175. _this._onPointerUp(evt);
  89176. };
  89177. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89178. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89179. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89180. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89181. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89182. evt.preventDefault(); // Disables system menu
  89183. }, false);
  89184. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89185. }
  89186. /**
  89187. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89188. * @param newJoystickSensibility defines the new sensibility
  89189. */
  89190. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89191. this._joystickSensibility = newJoystickSensibility;
  89192. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89193. };
  89194. VirtualJoystick.prototype._onPointerDown = function (e) {
  89195. var positionOnScreenCondition;
  89196. e.preventDefault();
  89197. if (this._leftJoystick === true) {
  89198. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89199. }
  89200. else {
  89201. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89202. }
  89203. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89204. // First contact will be dedicated to the virtual joystick
  89205. this._joystickPointerID = e.pointerId;
  89206. this._joystickPointerStartPos.x = e.clientX;
  89207. this._joystickPointerStartPos.y = e.clientY;
  89208. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89209. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89210. this._deltaJoystickVector.x = 0;
  89211. this._deltaJoystickVector.y = 0;
  89212. this.pressed = true;
  89213. this._touches.add(e.pointerId.toString(), e);
  89214. }
  89215. else {
  89216. // You can only trigger the action buttons with a joystick declared
  89217. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89218. this._action();
  89219. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89220. }
  89221. }
  89222. };
  89223. VirtualJoystick.prototype._onPointerMove = function (e) {
  89224. // If the current pointer is the one associated to the joystick (first touch contact)
  89225. if (this._joystickPointerID == e.pointerId) {
  89226. this._joystickPointerPos.x = e.clientX;
  89227. this._joystickPointerPos.y = e.clientY;
  89228. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89229. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89230. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89231. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89232. switch (this._axisTargetedByLeftAndRight) {
  89233. case JoystickAxis.X:
  89234. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89235. break;
  89236. case JoystickAxis.Y:
  89237. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89238. break;
  89239. case JoystickAxis.Z:
  89240. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89241. break;
  89242. }
  89243. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89244. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89245. switch (this._axisTargetedByUpAndDown) {
  89246. case JoystickAxis.X:
  89247. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89248. break;
  89249. case JoystickAxis.Y:
  89250. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89251. break;
  89252. case JoystickAxis.Z:
  89253. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89254. break;
  89255. }
  89256. }
  89257. else {
  89258. var data = this._touches.get(e.pointerId.toString());
  89259. if (data) {
  89260. data.x = e.clientX;
  89261. data.y = e.clientY;
  89262. }
  89263. }
  89264. };
  89265. VirtualJoystick.prototype._onPointerUp = function (e) {
  89266. if (this._joystickPointerID == e.pointerId) {
  89267. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89268. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89269. this._joystickPointerID = -1;
  89270. this.pressed = false;
  89271. }
  89272. else {
  89273. var touch = this._touches.get(e.pointerId.toString());
  89274. if (touch) {
  89275. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89276. }
  89277. }
  89278. this._deltaJoystickVector.x = 0;
  89279. this._deltaJoystickVector.y = 0;
  89280. this._touches.remove(e.pointerId.toString());
  89281. };
  89282. /**
  89283. * Change the color of the virtual joystick
  89284. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89285. */
  89286. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89287. this._joystickColor = newColor;
  89288. };
  89289. /**
  89290. * Defines a callback to call when the joystick is touched
  89291. * @param action defines the callback
  89292. */
  89293. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89294. this._action = action;
  89295. };
  89296. /**
  89297. * Defines which axis you'd like to control for left & right
  89298. * @param axis defines the axis to use
  89299. */
  89300. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89301. switch (axis) {
  89302. case JoystickAxis.X:
  89303. case JoystickAxis.Y:
  89304. case JoystickAxis.Z:
  89305. this._axisTargetedByLeftAndRight = axis;
  89306. break;
  89307. default:
  89308. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89309. break;
  89310. }
  89311. };
  89312. /**
  89313. * Defines which axis you'd like to control for up & down
  89314. * @param axis defines the axis to use
  89315. */
  89316. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89317. switch (axis) {
  89318. case JoystickAxis.X:
  89319. case JoystickAxis.Y:
  89320. case JoystickAxis.Z:
  89321. this._axisTargetedByUpAndDown = axis;
  89322. break;
  89323. default:
  89324. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89325. break;
  89326. }
  89327. };
  89328. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89329. var _this = this;
  89330. if (this.pressed) {
  89331. this._touches.forEach(function (key, touch) {
  89332. if (touch.pointerId === _this._joystickPointerID) {
  89333. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89334. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89335. VirtualJoystick.vjCanvasContext.beginPath();
  89336. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89337. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89338. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89339. VirtualJoystick.vjCanvasContext.stroke();
  89340. VirtualJoystick.vjCanvasContext.closePath();
  89341. VirtualJoystick.vjCanvasContext.beginPath();
  89342. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89343. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89344. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89345. VirtualJoystick.vjCanvasContext.stroke();
  89346. VirtualJoystick.vjCanvasContext.closePath();
  89347. VirtualJoystick.vjCanvasContext.beginPath();
  89348. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89349. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89350. VirtualJoystick.vjCanvasContext.stroke();
  89351. VirtualJoystick.vjCanvasContext.closePath();
  89352. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89353. }
  89354. else {
  89355. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89356. VirtualJoystick.vjCanvasContext.beginPath();
  89357. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89358. VirtualJoystick.vjCanvasContext.beginPath();
  89359. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89360. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89361. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89362. VirtualJoystick.vjCanvasContext.stroke();
  89363. VirtualJoystick.vjCanvasContext.closePath();
  89364. touch.prevX = touch.x;
  89365. touch.prevY = touch.y;
  89366. }
  89367. ;
  89368. });
  89369. }
  89370. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89371. };
  89372. /**
  89373. * Release internal HTML canvas
  89374. */
  89375. VirtualJoystick.prototype.releaseCanvas = function () {
  89376. if (VirtualJoystick.vjCanvas) {
  89377. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89378. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89379. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89380. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89381. window.removeEventListener("resize", this._onResize);
  89382. document.body.removeChild(VirtualJoystick.vjCanvas);
  89383. VirtualJoystick.vjCanvas = null;
  89384. }
  89385. };
  89386. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89387. VirtualJoystick._globalJoystickIndex = 0;
  89388. return VirtualJoystick;
  89389. }());
  89390. BABYLON.VirtualJoystick = VirtualJoystick;
  89391. })(BABYLON || (BABYLON = {}));
  89392. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89393. var BABYLON;
  89394. (function (BABYLON) {
  89395. // We're mainly based on the logic defined into the FreeCamera code
  89396. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89397. __extends(VirtualJoysticksCamera, _super);
  89398. function VirtualJoysticksCamera(name, position, scene) {
  89399. var _this = _super.call(this, name, position, scene) || this;
  89400. _this.inputs.addVirtualJoystick();
  89401. return _this;
  89402. }
  89403. VirtualJoysticksCamera.prototype.getClassName = function () {
  89404. return "VirtualJoysticksCamera";
  89405. };
  89406. return VirtualJoysticksCamera;
  89407. }(BABYLON.FreeCamera));
  89408. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89409. })(BABYLON || (BABYLON = {}));
  89410. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89411. var BABYLON;
  89412. (function (BABYLON) {
  89413. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89414. function FreeCameraVirtualJoystickInput() {
  89415. }
  89416. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89417. return this._leftjoystick;
  89418. };
  89419. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89420. return this._rightjoystick;
  89421. };
  89422. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89423. if (this._leftjoystick) {
  89424. var camera = this.camera;
  89425. var speed = camera._computeLocalCameraSpeed() * 50;
  89426. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89427. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89428. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89429. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89430. if (!this._leftjoystick.pressed) {
  89431. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89432. }
  89433. if (!this._rightjoystick.pressed) {
  89434. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89435. }
  89436. }
  89437. };
  89438. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89439. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89440. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89441. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89442. this._leftjoystick.setJoystickSensibility(0.15);
  89443. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89444. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89445. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89446. this._rightjoystick.reverseUpDown = true;
  89447. this._rightjoystick.setJoystickSensibility(0.05);
  89448. this._rightjoystick.setJoystickColor("yellow");
  89449. };
  89450. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89451. this._leftjoystick.releaseCanvas();
  89452. this._rightjoystick.releaseCanvas();
  89453. };
  89454. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89455. return "FreeCameraVirtualJoystickInput";
  89456. };
  89457. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89458. return "virtualJoystick";
  89459. };
  89460. return FreeCameraVirtualJoystickInput;
  89461. }());
  89462. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89463. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89464. })(BABYLON || (BABYLON = {}));
  89465. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89466. var BABYLON;
  89467. (function (BABYLON) {
  89468. var SimplificationSettings = /** @class */ (function () {
  89469. function SimplificationSettings(quality, distance, optimizeMesh) {
  89470. this.quality = quality;
  89471. this.distance = distance;
  89472. this.optimizeMesh = optimizeMesh;
  89473. }
  89474. return SimplificationSettings;
  89475. }());
  89476. BABYLON.SimplificationSettings = SimplificationSettings;
  89477. var SimplificationQueue = /** @class */ (function () {
  89478. function SimplificationQueue() {
  89479. this.running = false;
  89480. this._simplificationArray = [];
  89481. }
  89482. SimplificationQueue.prototype.addTask = function (task) {
  89483. this._simplificationArray.push(task);
  89484. };
  89485. SimplificationQueue.prototype.executeNext = function () {
  89486. var task = this._simplificationArray.pop();
  89487. if (task) {
  89488. this.running = true;
  89489. this.runSimplification(task);
  89490. }
  89491. else {
  89492. this.running = false;
  89493. }
  89494. };
  89495. SimplificationQueue.prototype.runSimplification = function (task) {
  89496. var _this = this;
  89497. if (task.parallelProcessing) {
  89498. //parallel simplifier
  89499. task.settings.forEach(function (setting) {
  89500. var simplifier = _this.getSimplifier(task);
  89501. simplifier.simplify(setting, function (newMesh) {
  89502. task.mesh.addLODLevel(setting.distance, newMesh);
  89503. newMesh.isVisible = true;
  89504. //check if it is the last
  89505. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89506. //all done, run the success callback.
  89507. task.successCallback();
  89508. }
  89509. _this.executeNext();
  89510. });
  89511. });
  89512. }
  89513. else {
  89514. //single simplifier.
  89515. var simplifier = this.getSimplifier(task);
  89516. var runDecimation = function (setting, callback) {
  89517. simplifier.simplify(setting, function (newMesh) {
  89518. task.mesh.addLODLevel(setting.distance, newMesh);
  89519. newMesh.isVisible = true;
  89520. //run the next quality level
  89521. callback();
  89522. });
  89523. };
  89524. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89525. runDecimation(task.settings[loop.index], function () {
  89526. loop.executeNext();
  89527. });
  89528. }, function () {
  89529. //execution ended, run the success callback.
  89530. if (task.successCallback) {
  89531. task.successCallback();
  89532. }
  89533. _this.executeNext();
  89534. });
  89535. }
  89536. };
  89537. SimplificationQueue.prototype.getSimplifier = function (task) {
  89538. switch (task.simplificationType) {
  89539. case SimplificationType.QUADRATIC:
  89540. default:
  89541. return new QuadraticErrorSimplification(task.mesh);
  89542. }
  89543. };
  89544. return SimplificationQueue;
  89545. }());
  89546. BABYLON.SimplificationQueue = SimplificationQueue;
  89547. /**
  89548. * The implemented types of simplification
  89549. * At the moment only Quadratic Error Decimation is implemented
  89550. */
  89551. var SimplificationType;
  89552. (function (SimplificationType) {
  89553. /** Quadratic error decimation */
  89554. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89555. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89556. var DecimationTriangle = /** @class */ (function () {
  89557. function DecimationTriangle(vertices) {
  89558. this.vertices = vertices;
  89559. this.error = new Array(4);
  89560. this.deleted = false;
  89561. this.isDirty = false;
  89562. this.deletePending = false;
  89563. this.borderFactor = 0;
  89564. }
  89565. return DecimationTriangle;
  89566. }());
  89567. BABYLON.DecimationTriangle = DecimationTriangle;
  89568. var DecimationVertex = /** @class */ (function () {
  89569. function DecimationVertex(position, id) {
  89570. this.position = position;
  89571. this.id = id;
  89572. this.isBorder = true;
  89573. this.q = new QuadraticMatrix();
  89574. this.triangleCount = 0;
  89575. this.triangleStart = 0;
  89576. this.originalOffsets = [];
  89577. }
  89578. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89579. this.position.copyFrom(newPosition);
  89580. };
  89581. return DecimationVertex;
  89582. }());
  89583. BABYLON.DecimationVertex = DecimationVertex;
  89584. var QuadraticMatrix = /** @class */ (function () {
  89585. function QuadraticMatrix(data) {
  89586. this.data = new Array(10);
  89587. for (var i = 0; i < 10; ++i) {
  89588. if (data && data[i]) {
  89589. this.data[i] = data[i];
  89590. }
  89591. else {
  89592. this.data[i] = 0;
  89593. }
  89594. }
  89595. }
  89596. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89597. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89598. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89599. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89600. return det;
  89601. };
  89602. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89603. for (var i = 0; i < 10; ++i) {
  89604. this.data[i] += matrix.data[i];
  89605. }
  89606. };
  89607. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89608. for (var i = 0; i < 10; ++i) {
  89609. this.data[i] += data[i];
  89610. }
  89611. };
  89612. QuadraticMatrix.prototype.add = function (matrix) {
  89613. var m = new QuadraticMatrix();
  89614. for (var i = 0; i < 10; ++i) {
  89615. m.data[i] = this.data[i] + matrix.data[i];
  89616. }
  89617. return m;
  89618. };
  89619. QuadraticMatrix.FromData = function (a, b, c, d) {
  89620. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89621. };
  89622. //returning an array to avoid garbage collection
  89623. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89624. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89625. };
  89626. return QuadraticMatrix;
  89627. }());
  89628. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89629. var Reference = /** @class */ (function () {
  89630. function Reference(vertexId, triangleId) {
  89631. this.vertexId = vertexId;
  89632. this.triangleId = triangleId;
  89633. }
  89634. return Reference;
  89635. }());
  89636. BABYLON.Reference = Reference;
  89637. /**
  89638. * An implementation of the Quadratic Error simplification algorithm.
  89639. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89640. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89641. * @author RaananW
  89642. */
  89643. var QuadraticErrorSimplification = /** @class */ (function () {
  89644. function QuadraticErrorSimplification(_mesh) {
  89645. this._mesh = _mesh;
  89646. this.syncIterations = 5000;
  89647. this.aggressiveness = 7;
  89648. this.decimationIterations = 100;
  89649. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89650. }
  89651. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89652. var _this = this;
  89653. this.initDecimatedMesh();
  89654. //iterating through the submeshes array, one after the other.
  89655. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89656. _this.initWithMesh(loop.index, function () {
  89657. _this.runDecimation(settings, loop.index, function () {
  89658. loop.executeNext();
  89659. });
  89660. }, settings.optimizeMesh);
  89661. }, function () {
  89662. setTimeout(function () {
  89663. successCallback(_this._reconstructedMesh);
  89664. }, 0);
  89665. });
  89666. };
  89667. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89668. var _this = this;
  89669. var targetCount = ~~(this.triangles.length * settings.quality);
  89670. var deletedTriangles = 0;
  89671. var triangleCount = this.triangles.length;
  89672. var iterationFunction = function (iteration, callback) {
  89673. setTimeout(function () {
  89674. if (iteration % 5 === 0) {
  89675. _this.updateMesh(iteration === 0);
  89676. }
  89677. for (var i = 0; i < _this.triangles.length; ++i) {
  89678. _this.triangles[i].isDirty = false;
  89679. }
  89680. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89681. var trianglesIterator = function (i) {
  89682. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89683. var t = _this.triangles[tIdx];
  89684. if (!t)
  89685. return;
  89686. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89687. return;
  89688. }
  89689. for (var j = 0; j < 3; ++j) {
  89690. if (t.error[j] < threshold) {
  89691. var deleted0 = [];
  89692. var deleted1 = [];
  89693. var v0 = t.vertices[j];
  89694. var v1 = t.vertices[(j + 1) % 3];
  89695. if (v0.isBorder || v1.isBorder)
  89696. continue;
  89697. var p = BABYLON.Vector3.Zero();
  89698. var n = BABYLON.Vector3.Zero();
  89699. var uv = BABYLON.Vector2.Zero();
  89700. var color = new BABYLON.Color4(0, 0, 0, 1);
  89701. _this.calculateError(v0, v1, p, n, uv, color);
  89702. var delTr = new Array();
  89703. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89704. continue;
  89705. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89706. continue;
  89707. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89708. continue;
  89709. var uniqueArray = new Array();
  89710. delTr.forEach(function (deletedT) {
  89711. if (uniqueArray.indexOf(deletedT) === -1) {
  89712. deletedT.deletePending = true;
  89713. uniqueArray.push(deletedT);
  89714. }
  89715. });
  89716. if (uniqueArray.length % 2 !== 0) {
  89717. continue;
  89718. }
  89719. v0.q = v1.q.add(v0.q);
  89720. v0.updatePosition(p);
  89721. var tStart = _this.references.length;
  89722. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89723. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89724. var tCount = _this.references.length - tStart;
  89725. if (tCount <= v0.triangleCount) {
  89726. if (tCount) {
  89727. for (var c = 0; c < tCount; c++) {
  89728. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89729. }
  89730. }
  89731. }
  89732. else {
  89733. v0.triangleStart = tStart;
  89734. }
  89735. v0.triangleCount = tCount;
  89736. break;
  89737. }
  89738. }
  89739. };
  89740. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89741. }, 0);
  89742. };
  89743. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89744. if (triangleCount - deletedTriangles <= targetCount)
  89745. loop.breakLoop();
  89746. else {
  89747. iterationFunction(loop.index, function () {
  89748. loop.executeNext();
  89749. });
  89750. }
  89751. }, function () {
  89752. setTimeout(function () {
  89753. //reconstruct this part of the mesh
  89754. _this.reconstructMesh(submeshIndex);
  89755. successCallback();
  89756. }, 0);
  89757. });
  89758. };
  89759. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89760. var _this = this;
  89761. this.vertices = [];
  89762. this.triangles = [];
  89763. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89764. var indices = this._mesh.getIndices();
  89765. var submesh = this._mesh.subMeshes[submeshIndex];
  89766. var findInVertices = function (positionToSearch) {
  89767. if (optimizeMesh) {
  89768. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89769. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89770. return _this.vertices[ii];
  89771. }
  89772. }
  89773. }
  89774. return null;
  89775. };
  89776. var vertexReferences = [];
  89777. var vertexInit = function (i) {
  89778. if (!positionData) {
  89779. return;
  89780. }
  89781. var offset = i + submesh.verticesStart;
  89782. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89783. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89784. vertex.originalOffsets.push(offset);
  89785. if (vertex.id === _this.vertices.length) {
  89786. _this.vertices.push(vertex);
  89787. }
  89788. vertexReferences.push(vertex.id);
  89789. };
  89790. //var totalVertices = mesh.getTotalVertices();
  89791. var totalVertices = submesh.verticesCount;
  89792. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89793. var indicesInit = function (i) {
  89794. if (!indices) {
  89795. return;
  89796. }
  89797. var offset = (submesh.indexStart / 3) + i;
  89798. var pos = (offset * 3);
  89799. var i0 = indices[pos + 0];
  89800. var i1 = indices[pos + 1];
  89801. var i2 = indices[pos + 2];
  89802. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89803. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89804. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89805. var triangle = new DecimationTriangle([v0, v1, v2]);
  89806. triangle.originalOffset = pos;
  89807. _this.triangles.push(triangle);
  89808. };
  89809. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89810. _this.init(callback);
  89811. });
  89812. });
  89813. };
  89814. QuadraticErrorSimplification.prototype.init = function (callback) {
  89815. var _this = this;
  89816. var triangleInit1 = function (i) {
  89817. var t = _this.triangles[i];
  89818. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89819. for (var j = 0; j < 3; j++) {
  89820. 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))));
  89821. }
  89822. };
  89823. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89824. var triangleInit2 = function (i) {
  89825. var t = _this.triangles[i];
  89826. for (var j = 0; j < 3; ++j) {
  89827. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89828. }
  89829. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89830. };
  89831. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89832. callback();
  89833. });
  89834. });
  89835. };
  89836. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89837. var newTriangles = [];
  89838. var i;
  89839. for (i = 0; i < this.vertices.length; ++i) {
  89840. this.vertices[i].triangleCount = 0;
  89841. }
  89842. var t;
  89843. var j;
  89844. for (i = 0; i < this.triangles.length; ++i) {
  89845. if (!this.triangles[i].deleted) {
  89846. t = this.triangles[i];
  89847. for (j = 0; j < 3; ++j) {
  89848. t.vertices[j].triangleCount = 1;
  89849. }
  89850. newTriangles.push(t);
  89851. }
  89852. }
  89853. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89854. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89855. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89856. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89857. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89858. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89859. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89860. var vertexCount = 0;
  89861. for (i = 0; i < this.vertices.length; ++i) {
  89862. var vertex = this.vertices[i];
  89863. vertex.id = vertexCount;
  89864. if (vertex.triangleCount) {
  89865. vertex.originalOffsets.forEach(function (originalOffset) {
  89866. if (!normalData) {
  89867. return;
  89868. }
  89869. newPositionData.push(vertex.position.x);
  89870. newPositionData.push(vertex.position.y);
  89871. newPositionData.push(vertex.position.z);
  89872. newNormalData.push(normalData[originalOffset * 3]);
  89873. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89874. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89875. if (uvs && uvs.length) {
  89876. newUVsData.push(uvs[(originalOffset * 2)]);
  89877. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89878. }
  89879. else if (colorsData && colorsData.length) {
  89880. newColorsData.push(colorsData[(originalOffset * 4)]);
  89881. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89882. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89883. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89884. }
  89885. ++vertexCount;
  89886. });
  89887. }
  89888. }
  89889. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89890. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89891. var submeshesArray = this._reconstructedMesh.subMeshes;
  89892. this._reconstructedMesh.subMeshes = [];
  89893. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89894. var originalIndices = this._mesh.getIndices();
  89895. for (i = 0; i < newTriangles.length; ++i) {
  89896. t = newTriangles[i]; //now get the new referencing point for each vertex
  89897. [0, 1, 2].forEach(function (idx) {
  89898. var id = originalIndices[t.originalOffset + idx];
  89899. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89900. if (offset < 0)
  89901. offset = 0;
  89902. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89903. });
  89904. }
  89905. //overwriting the old vertex buffers and indices.
  89906. this._reconstructedMesh.setIndices(newIndicesArray);
  89907. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89908. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89909. if (newUVsData.length > 0)
  89910. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89911. if (newColorsData.length > 0)
  89912. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89913. //create submesh
  89914. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89915. if (submeshIndex > 0) {
  89916. this._reconstructedMesh.subMeshes = [];
  89917. submeshesArray.forEach(function (submesh) {
  89918. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89919. });
  89920. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89921. }
  89922. };
  89923. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89924. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89925. this._reconstructedMesh.material = this._mesh.material;
  89926. this._reconstructedMesh.parent = this._mesh.parent;
  89927. this._reconstructedMesh.isVisible = false;
  89928. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89929. };
  89930. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89931. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89932. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89933. if (t.deleted)
  89934. continue;
  89935. var s = this.references[vertex1.triangleStart + i].vertexId;
  89936. var v1 = t.vertices[(s + 1) % 3];
  89937. var v2 = t.vertices[(s + 2) % 3];
  89938. if ((v1 === vertex2 || v2 === vertex2)) {
  89939. deletedArray[i] = true;
  89940. delTr.push(t);
  89941. continue;
  89942. }
  89943. var d1 = v1.position.subtract(point);
  89944. d1 = d1.normalize();
  89945. var d2 = v2.position.subtract(point);
  89946. d2 = d2.normalize();
  89947. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89948. return true;
  89949. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89950. deletedArray[i] = false;
  89951. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89952. return true;
  89953. }
  89954. return false;
  89955. };
  89956. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89957. var newDeleted = deletedTriangles;
  89958. for (var i = 0; i < vertex.triangleCount; ++i) {
  89959. var ref = this.references[vertex.triangleStart + i];
  89960. var t = this.triangles[ref.triangleId];
  89961. if (t.deleted)
  89962. continue;
  89963. if (deletedArray[i] && t.deletePending) {
  89964. t.deleted = true;
  89965. newDeleted++;
  89966. continue;
  89967. }
  89968. t.vertices[ref.vertexId] = origVertex;
  89969. t.isDirty = true;
  89970. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89971. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89972. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89973. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89974. this.references.push(ref);
  89975. }
  89976. return newDeleted;
  89977. };
  89978. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89979. for (var i = 0; i < this.vertices.length; ++i) {
  89980. var vCount = [];
  89981. var vId = [];
  89982. var v = this.vertices[i];
  89983. var j;
  89984. for (j = 0; j < v.triangleCount; ++j) {
  89985. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89986. for (var ii = 0; ii < 3; ii++) {
  89987. var ofs = 0;
  89988. var vv = triangle.vertices[ii];
  89989. while (ofs < vCount.length) {
  89990. if (vId[ofs] === vv.id)
  89991. break;
  89992. ++ofs;
  89993. }
  89994. if (ofs === vCount.length) {
  89995. vCount.push(1);
  89996. vId.push(vv.id);
  89997. }
  89998. else {
  89999. vCount[ofs]++;
  90000. }
  90001. }
  90002. }
  90003. for (j = 0; j < vCount.length; ++j) {
  90004. if (vCount[j] === 1) {
  90005. this.vertices[vId[j]].isBorder = true;
  90006. }
  90007. else {
  90008. this.vertices[vId[j]].isBorder = false;
  90009. }
  90010. }
  90011. }
  90012. };
  90013. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90014. if (identifyBorders === void 0) { identifyBorders = false; }
  90015. var i;
  90016. if (!identifyBorders) {
  90017. var newTrianglesVector = [];
  90018. for (i = 0; i < this.triangles.length; ++i) {
  90019. if (!this.triangles[i].deleted) {
  90020. newTrianglesVector.push(this.triangles[i]);
  90021. }
  90022. }
  90023. this.triangles = newTrianglesVector;
  90024. }
  90025. for (i = 0; i < this.vertices.length; ++i) {
  90026. this.vertices[i].triangleCount = 0;
  90027. this.vertices[i].triangleStart = 0;
  90028. }
  90029. var t;
  90030. var j;
  90031. var v;
  90032. for (i = 0; i < this.triangles.length; ++i) {
  90033. t = this.triangles[i];
  90034. for (j = 0; j < 3; ++j) {
  90035. v = t.vertices[j];
  90036. v.triangleCount++;
  90037. }
  90038. }
  90039. var tStart = 0;
  90040. for (i = 0; i < this.vertices.length; ++i) {
  90041. this.vertices[i].triangleStart = tStart;
  90042. tStart += this.vertices[i].triangleCount;
  90043. this.vertices[i].triangleCount = 0;
  90044. }
  90045. var newReferences = new Array(this.triangles.length * 3);
  90046. for (i = 0; i < this.triangles.length; ++i) {
  90047. t = this.triangles[i];
  90048. for (j = 0; j < 3; ++j) {
  90049. v = t.vertices[j];
  90050. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90051. v.triangleCount++;
  90052. }
  90053. }
  90054. this.references = newReferences;
  90055. if (identifyBorders) {
  90056. this.identifyBorder();
  90057. }
  90058. };
  90059. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90060. var x = point.x;
  90061. var y = point.y;
  90062. var z = point.z;
  90063. 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
  90064. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90065. };
  90066. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90067. var q = vertex1.q.add(vertex2.q);
  90068. var border = vertex1.isBorder && vertex2.isBorder;
  90069. var error = 0;
  90070. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90071. if (qDet !== 0 && !border) {
  90072. if (!pointResult) {
  90073. pointResult = BABYLON.Vector3.Zero();
  90074. }
  90075. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90076. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90077. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90078. error = this.vertexError(q, pointResult);
  90079. }
  90080. else {
  90081. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90082. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90083. var error1 = this.vertexError(q, vertex1.position);
  90084. var error2 = this.vertexError(q, vertex2.position);
  90085. var error3 = this.vertexError(q, p3);
  90086. error = Math.min(error1, error2, error3);
  90087. if (error === error1) {
  90088. if (pointResult) {
  90089. pointResult.copyFrom(vertex1.position);
  90090. }
  90091. }
  90092. else if (error === error2) {
  90093. if (pointResult) {
  90094. pointResult.copyFrom(vertex2.position);
  90095. }
  90096. }
  90097. else {
  90098. if (pointResult) {
  90099. pointResult.copyFrom(p3);
  90100. }
  90101. }
  90102. }
  90103. return error;
  90104. };
  90105. return QuadraticErrorSimplification;
  90106. }());
  90107. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90108. })(BABYLON || (BABYLON = {}));
  90109. //# sourceMappingURL=babylon.meshSimplification.js.map
  90110. var BABYLON;
  90111. (function (BABYLON) {
  90112. var MeshLODLevel = /** @class */ (function () {
  90113. function MeshLODLevel(distance, mesh) {
  90114. this.distance = distance;
  90115. this.mesh = mesh;
  90116. }
  90117. return MeshLODLevel;
  90118. }());
  90119. BABYLON.MeshLODLevel = MeshLODLevel;
  90120. })(BABYLON || (BABYLON = {}));
  90121. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90122. var BABYLON;
  90123. (function (BABYLON) {
  90124. /**
  90125. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90126. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90127. */
  90128. var SceneOptimization = /** @class */ (function () {
  90129. /**
  90130. * Creates the SceneOptimization object
  90131. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90132. * @param desc defines the description associated with the optimization
  90133. */
  90134. function SceneOptimization(
  90135. /**
  90136. * Defines the priority of this optimization (0 by default which means first in the list)
  90137. */
  90138. priority) {
  90139. if (priority === void 0) { priority = 0; }
  90140. this.priority = priority;
  90141. }
  90142. /**
  90143. * Gets a string describing the action executed by the current optimization
  90144. * @returns description string
  90145. */
  90146. SceneOptimization.prototype.getDescription = function () {
  90147. return "";
  90148. };
  90149. /**
  90150. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90151. * @param scene defines the current scene where to apply this optimization
  90152. * @param optimizer defines the current optimizer
  90153. * @returns true if everything that can be done was applied
  90154. */
  90155. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90156. return true;
  90157. };
  90158. ;
  90159. return SceneOptimization;
  90160. }());
  90161. BABYLON.SceneOptimization = SceneOptimization;
  90162. /**
  90163. * Defines an optimization used to reduce the size of render target textures
  90164. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90165. */
  90166. var TextureOptimization = /** @class */ (function (_super) {
  90167. __extends(TextureOptimization, _super);
  90168. /**
  90169. * Creates the TextureOptimization object
  90170. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90171. * @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
  90172. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90173. */
  90174. function TextureOptimization(
  90175. /**
  90176. * Defines the priority of this optimization (0 by default which means first in the list)
  90177. */
  90178. priority,
  90179. /**
  90180. * 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
  90181. */
  90182. maximumSize,
  90183. /**
  90184. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90185. */
  90186. step) {
  90187. if (priority === void 0) { priority = 0; }
  90188. if (maximumSize === void 0) { maximumSize = 1024; }
  90189. if (step === void 0) { step = 0.5; }
  90190. var _this = _super.call(this, priority) || this;
  90191. _this.priority = priority;
  90192. _this.maximumSize = maximumSize;
  90193. _this.step = step;
  90194. return _this;
  90195. }
  90196. /**
  90197. * Gets a string describing the action executed by the current optimization
  90198. * @returns description string
  90199. */
  90200. TextureOptimization.prototype.getDescription = function () {
  90201. return "Reducing render target texture size to " + this.maximumSize;
  90202. };
  90203. /**
  90204. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90205. * @param scene defines the current scene where to apply this optimization
  90206. * @param optimizer defines the current optimizer
  90207. * @returns true if everything that can be done was applied
  90208. */
  90209. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90210. var allDone = true;
  90211. for (var index = 0; index < scene.textures.length; index++) {
  90212. var texture = scene.textures[index];
  90213. if (!texture.canRescale || texture.getContext) {
  90214. continue;
  90215. }
  90216. var currentSize = texture.getSize();
  90217. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90218. if (maxDimension > this.maximumSize) {
  90219. texture.scale(this.step);
  90220. allDone = false;
  90221. }
  90222. }
  90223. return allDone;
  90224. };
  90225. return TextureOptimization;
  90226. }(SceneOptimization));
  90227. BABYLON.TextureOptimization = TextureOptimization;
  90228. /**
  90229. * Defines an optimization used to increase or decrease the rendering resolution
  90230. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90231. */
  90232. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90233. __extends(HardwareScalingOptimization, _super);
  90234. /**
  90235. * Creates the HardwareScalingOptimization object
  90236. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90237. * @param maximumScale defines the maximum scale to use (2 by default)
  90238. * @param step defines the step to use between two passes (0.5 by default)
  90239. */
  90240. function HardwareScalingOptimization(
  90241. /**
  90242. * Defines the priority of this optimization (0 by default which means first in the list)
  90243. */
  90244. priority,
  90245. /**
  90246. * Defines the maximum scale to use (2 by default)
  90247. */
  90248. maximumScale,
  90249. /**
  90250. * Defines the step to use between two passes (0.5 by default)
  90251. */
  90252. step) {
  90253. if (priority === void 0) { priority = 0; }
  90254. if (maximumScale === void 0) { maximumScale = 2; }
  90255. if (step === void 0) { step = 0.25; }
  90256. var _this = _super.call(this, priority) || this;
  90257. _this.priority = priority;
  90258. _this.maximumScale = maximumScale;
  90259. _this.step = step;
  90260. _this._currentScale = -1;
  90261. _this._directionOffset = 1;
  90262. return _this;
  90263. }
  90264. /**
  90265. * Gets a string describing the action executed by the current optimization
  90266. * @return description string
  90267. */
  90268. HardwareScalingOptimization.prototype.getDescription = function () {
  90269. return "Setting hardware scaling level to " + this._currentScale;
  90270. };
  90271. /**
  90272. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90273. * @param scene defines the current scene where to apply this optimization
  90274. * @param optimizer defines the current optimizer
  90275. * @returns true if everything that can be done was applied
  90276. */
  90277. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90278. if (this._currentScale === -1) {
  90279. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90280. if (this._currentScale > this.maximumScale) {
  90281. this._directionOffset = -1;
  90282. }
  90283. }
  90284. this._currentScale += this._directionOffset * this.step;
  90285. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90286. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90287. };
  90288. ;
  90289. return HardwareScalingOptimization;
  90290. }(SceneOptimization));
  90291. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90292. /**
  90293. * Defines an optimization used to remove shadows
  90294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90295. */
  90296. var ShadowsOptimization = /** @class */ (function (_super) {
  90297. __extends(ShadowsOptimization, _super);
  90298. function ShadowsOptimization() {
  90299. return _super !== null && _super.apply(this, arguments) || this;
  90300. }
  90301. /**
  90302. * Gets a string describing the action executed by the current optimization
  90303. * @return description string
  90304. */
  90305. ShadowsOptimization.prototype.getDescription = function () {
  90306. return "Turning shadows on/off";
  90307. };
  90308. /**
  90309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90310. * @param scene defines the current scene where to apply this optimization
  90311. * @param optimizer defines the current optimizer
  90312. * @returns true if everything that can be done was applied
  90313. */
  90314. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90315. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90316. return true;
  90317. };
  90318. ;
  90319. return ShadowsOptimization;
  90320. }(SceneOptimization));
  90321. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90322. /**
  90323. * Defines an optimization used to turn post-processes off
  90324. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90325. */
  90326. var PostProcessesOptimization = /** @class */ (function (_super) {
  90327. __extends(PostProcessesOptimization, _super);
  90328. function PostProcessesOptimization() {
  90329. return _super !== null && _super.apply(this, arguments) || this;
  90330. }
  90331. /**
  90332. * Gets a string describing the action executed by the current optimization
  90333. * @return description string
  90334. */
  90335. PostProcessesOptimization.prototype.getDescription = function () {
  90336. return "Turning post-processes on/off";
  90337. };
  90338. /**
  90339. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90340. * @param scene defines the current scene where to apply this optimization
  90341. * @param optimizer defines the current optimizer
  90342. * @returns true if everything that can be done was applied
  90343. */
  90344. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90345. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90346. return true;
  90347. };
  90348. ;
  90349. return PostProcessesOptimization;
  90350. }(SceneOptimization));
  90351. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90352. /**
  90353. * Defines an optimization used to turn lens flares off
  90354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90355. */
  90356. var LensFlaresOptimization = /** @class */ (function (_super) {
  90357. __extends(LensFlaresOptimization, _super);
  90358. function LensFlaresOptimization() {
  90359. return _super !== null && _super.apply(this, arguments) || this;
  90360. }
  90361. /**
  90362. * Gets a string describing the action executed by the current optimization
  90363. * @return description string
  90364. */
  90365. LensFlaresOptimization.prototype.getDescription = function () {
  90366. return "Turning lens flares on/off";
  90367. };
  90368. /**
  90369. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90370. * @param scene defines the current scene where to apply this optimization
  90371. * @param optimizer defines the current optimizer
  90372. * @returns true if everything that can be done was applied
  90373. */
  90374. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90375. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90376. return true;
  90377. };
  90378. ;
  90379. return LensFlaresOptimization;
  90380. }(SceneOptimization));
  90381. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90382. /**
  90383. * Defines an optimization based on user defined callback.
  90384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90385. */
  90386. var CustomOptimization = /** @class */ (function (_super) {
  90387. __extends(CustomOptimization, _super);
  90388. function CustomOptimization() {
  90389. return _super !== null && _super.apply(this, arguments) || this;
  90390. }
  90391. /**
  90392. * Gets a string describing the action executed by the current optimization
  90393. * @returns description string
  90394. */
  90395. CustomOptimization.prototype.getDescription = function () {
  90396. if (this.onGetDescription) {
  90397. return this.onGetDescription();
  90398. }
  90399. return "Running user defined callback";
  90400. };
  90401. /**
  90402. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90403. * @param scene defines the current scene where to apply this optimization
  90404. * @param optimizer defines the current optimizer
  90405. * @returns true if everything that can be done was applied
  90406. */
  90407. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90408. if (this.onApply) {
  90409. return this.onApply(scene, optimizer);
  90410. }
  90411. return true;
  90412. };
  90413. ;
  90414. return CustomOptimization;
  90415. }(SceneOptimization));
  90416. BABYLON.CustomOptimization = CustomOptimization;
  90417. /**
  90418. * Defines an optimization used to turn particles off
  90419. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90420. */
  90421. var ParticlesOptimization = /** @class */ (function (_super) {
  90422. __extends(ParticlesOptimization, _super);
  90423. function ParticlesOptimization() {
  90424. return _super !== null && _super.apply(this, arguments) || this;
  90425. }
  90426. /**
  90427. * Gets a string describing the action executed by the current optimization
  90428. * @return description string
  90429. */
  90430. ParticlesOptimization.prototype.getDescription = function () {
  90431. return "Turning particles on/off";
  90432. };
  90433. /**
  90434. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90435. * @param scene defines the current scene where to apply this optimization
  90436. * @param optimizer defines the current optimizer
  90437. * @returns true if everything that can be done was applied
  90438. */
  90439. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90440. scene.particlesEnabled = optimizer.isInImprovementMode;
  90441. return true;
  90442. };
  90443. ;
  90444. return ParticlesOptimization;
  90445. }(SceneOptimization));
  90446. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90447. /**
  90448. * Defines an optimization used to turn render targets off
  90449. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90450. */
  90451. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90452. __extends(RenderTargetsOptimization, _super);
  90453. function RenderTargetsOptimization() {
  90454. return _super !== null && _super.apply(this, arguments) || this;
  90455. }
  90456. /**
  90457. * Gets a string describing the action executed by the current optimization
  90458. * @return description string
  90459. */
  90460. RenderTargetsOptimization.prototype.getDescription = function () {
  90461. return "Turning render targets off";
  90462. };
  90463. /**
  90464. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90465. * @param scene defines the current scene where to apply this optimization
  90466. * @param optimizer defines the current optimizer
  90467. * @returns true if everything that can be done was applied
  90468. */
  90469. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90470. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90471. return true;
  90472. };
  90473. ;
  90474. return RenderTargetsOptimization;
  90475. }(SceneOptimization));
  90476. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90477. /**
  90478. * Defines an optimization used to merge meshes with compatible materials
  90479. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90480. */
  90481. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90482. __extends(MergeMeshesOptimization, _super);
  90483. function MergeMeshesOptimization() {
  90484. var _this = _super !== null && _super.apply(this, arguments) || this;
  90485. _this._canBeMerged = function (abstractMesh) {
  90486. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90487. return false;
  90488. }
  90489. var mesh = abstractMesh;
  90490. if (!mesh.isVisible || !mesh.isEnabled()) {
  90491. return false;
  90492. }
  90493. if (mesh.instances.length > 0) {
  90494. return false;
  90495. }
  90496. if (mesh.skeleton || mesh.hasLODLevels) {
  90497. return false;
  90498. }
  90499. if (mesh.parent) {
  90500. return false;
  90501. }
  90502. return true;
  90503. };
  90504. return _this;
  90505. }
  90506. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90507. /**
  90508. * Gets or sets a boolean which defines if optimization octree has to be updated
  90509. */
  90510. get: function () {
  90511. return MergeMeshesOptimization._UpdateSelectionTree;
  90512. },
  90513. /**
  90514. * Gets or sets a boolean which defines if optimization octree has to be updated
  90515. */
  90516. set: function (value) {
  90517. MergeMeshesOptimization._UpdateSelectionTree = value;
  90518. },
  90519. enumerable: true,
  90520. configurable: true
  90521. });
  90522. /**
  90523. * Gets a string describing the action executed by the current optimization
  90524. * @return description string
  90525. */
  90526. MergeMeshesOptimization.prototype.getDescription = function () {
  90527. return "Merging similar meshes together";
  90528. };
  90529. /**
  90530. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90531. * @param scene defines the current scene where to apply this optimization
  90532. * @param optimizer defines the current optimizer
  90533. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90534. * @returns true if everything that can be done was applied
  90535. */
  90536. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90537. var globalPool = scene.meshes.slice(0);
  90538. var globalLength = globalPool.length;
  90539. for (var index = 0; index < globalLength; index++) {
  90540. var currentPool = new Array();
  90541. var current = globalPool[index];
  90542. // Checks
  90543. if (!this._canBeMerged(current)) {
  90544. continue;
  90545. }
  90546. currentPool.push(current);
  90547. // Find compatible meshes
  90548. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90549. var otherMesh = globalPool[subIndex];
  90550. if (!this._canBeMerged(otherMesh)) {
  90551. continue;
  90552. }
  90553. if (otherMesh.material !== current.material) {
  90554. continue;
  90555. }
  90556. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90557. continue;
  90558. }
  90559. currentPool.push(otherMesh);
  90560. globalLength--;
  90561. globalPool.splice(subIndex, 1);
  90562. subIndex--;
  90563. }
  90564. if (currentPool.length < 2) {
  90565. continue;
  90566. }
  90567. // Merge meshes
  90568. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90569. }
  90570. if (updateSelectionTree != undefined) {
  90571. if (updateSelectionTree) {
  90572. scene.createOrUpdateSelectionOctree();
  90573. }
  90574. }
  90575. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90576. scene.createOrUpdateSelectionOctree();
  90577. }
  90578. return true;
  90579. };
  90580. ;
  90581. MergeMeshesOptimization._UpdateSelectionTree = false;
  90582. return MergeMeshesOptimization;
  90583. }(SceneOptimization));
  90584. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90585. /**
  90586. * Defines a list of options used by SceneOptimizer
  90587. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90588. */
  90589. var SceneOptimizerOptions = /** @class */ (function () {
  90590. /**
  90591. * Creates a new list of options used by SceneOptimizer
  90592. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90593. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90594. */
  90595. function SceneOptimizerOptions(
  90596. /**
  90597. * Defines the target frame rate to reach (60 by default)
  90598. */
  90599. targetFrameRate,
  90600. /**
  90601. * Defines the interval between two checkes (2000ms by default)
  90602. */
  90603. trackerDuration) {
  90604. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90605. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90606. this.targetFrameRate = targetFrameRate;
  90607. this.trackerDuration = trackerDuration;
  90608. /**
  90609. * Gets the list of optimizations to apply
  90610. */
  90611. this.optimizations = new Array();
  90612. }
  90613. /**
  90614. * Add a new optimization
  90615. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90616. * @returns the current SceneOptimizerOptions
  90617. */
  90618. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90619. this.optimizations.push(optimization);
  90620. return this;
  90621. };
  90622. /**
  90623. * Add a new custom optimization
  90624. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90625. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90626. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90627. * @returns the current SceneOptimizerOptions
  90628. */
  90629. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90630. if (priority === void 0) { priority = 0; }
  90631. var optimization = new CustomOptimization(priority);
  90632. optimization.onApply = onApply;
  90633. optimization.onGetDescription = onGetDescription;
  90634. this.optimizations.push(optimization);
  90635. return this;
  90636. };
  90637. /**
  90638. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90639. * @param targetFrameRate defines the target frame rate (60 by default)
  90640. * @returns a SceneOptimizerOptions object
  90641. */
  90642. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90643. var result = new SceneOptimizerOptions(targetFrameRate);
  90644. var priority = 0;
  90645. result.addOptimization(new MergeMeshesOptimization(priority));
  90646. result.addOptimization(new ShadowsOptimization(priority));
  90647. result.addOptimization(new LensFlaresOptimization(priority));
  90648. // Next priority
  90649. priority++;
  90650. result.addOptimization(new PostProcessesOptimization(priority));
  90651. result.addOptimization(new ParticlesOptimization(priority));
  90652. // Next priority
  90653. priority++;
  90654. result.addOptimization(new TextureOptimization(priority, 1024));
  90655. return result;
  90656. };
  90657. /**
  90658. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90659. * @param targetFrameRate defines the target frame rate (60 by default)
  90660. * @returns a SceneOptimizerOptions object
  90661. */
  90662. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90663. var result = new SceneOptimizerOptions(targetFrameRate);
  90664. var priority = 0;
  90665. result.addOptimization(new MergeMeshesOptimization(priority));
  90666. result.addOptimization(new ShadowsOptimization(priority));
  90667. result.addOptimization(new LensFlaresOptimization(priority));
  90668. // Next priority
  90669. priority++;
  90670. result.addOptimization(new PostProcessesOptimization(priority));
  90671. result.addOptimization(new ParticlesOptimization(priority));
  90672. // Next priority
  90673. priority++;
  90674. result.addOptimization(new TextureOptimization(priority, 512));
  90675. // Next priority
  90676. priority++;
  90677. result.addOptimization(new RenderTargetsOptimization(priority));
  90678. // Next priority
  90679. priority++;
  90680. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90681. return result;
  90682. };
  90683. /**
  90684. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90685. * @param targetFrameRate defines the target frame rate (60 by default)
  90686. * @returns a SceneOptimizerOptions object
  90687. */
  90688. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90689. var result = new SceneOptimizerOptions(targetFrameRate);
  90690. var priority = 0;
  90691. result.addOptimization(new MergeMeshesOptimization(priority));
  90692. result.addOptimization(new ShadowsOptimization(priority));
  90693. result.addOptimization(new LensFlaresOptimization(priority));
  90694. // Next priority
  90695. priority++;
  90696. result.addOptimization(new PostProcessesOptimization(priority));
  90697. result.addOptimization(new ParticlesOptimization(priority));
  90698. // Next priority
  90699. priority++;
  90700. result.addOptimization(new TextureOptimization(priority, 256));
  90701. // Next priority
  90702. priority++;
  90703. result.addOptimization(new RenderTargetsOptimization(priority));
  90704. // Next priority
  90705. priority++;
  90706. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90707. return result;
  90708. };
  90709. return SceneOptimizerOptions;
  90710. }());
  90711. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90712. /**
  90713. * Class used to run optimizations in order to reach a target frame rate
  90714. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90715. */
  90716. var SceneOptimizer = /** @class */ (function () {
  90717. /**
  90718. * Creates a new SceneOptimizer
  90719. * @param scene defines the scene to work on
  90720. * @param options defines the options to use with the SceneOptimizer
  90721. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90722. * @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)
  90723. */
  90724. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90725. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90726. if (improvementMode === void 0) { improvementMode = false; }
  90727. var _this = this;
  90728. this._isRunning = false;
  90729. this._currentPriorityLevel = 0;
  90730. this._targetFrameRate = 60;
  90731. this._trackerDuration = 2000;
  90732. this._currentFrameRate = 0;
  90733. this._improvementMode = false;
  90734. /**
  90735. * Defines an observable called when the optimizer reaches the target frame rate
  90736. */
  90737. this.onSuccessObservable = new BABYLON.Observable();
  90738. /**
  90739. * Defines an observable called when the optimizer enables an optimization
  90740. */
  90741. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90742. /**
  90743. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90744. */
  90745. this.onFailureObservable = new BABYLON.Observable();
  90746. if (!options) {
  90747. this._options = new SceneOptimizerOptions();
  90748. }
  90749. else {
  90750. this._options = options;
  90751. }
  90752. if (this._options.targetFrameRate) {
  90753. this._targetFrameRate = this._options.targetFrameRate;
  90754. }
  90755. if (this._options.trackerDuration) {
  90756. this._trackerDuration = this._options.trackerDuration;
  90757. }
  90758. if (autoGeneratePriorities) {
  90759. var priority = 0;
  90760. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90761. var optim = _a[_i];
  90762. optim.priority = priority++;
  90763. }
  90764. }
  90765. this._improvementMode = improvementMode;
  90766. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90767. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90768. _this._sceneDisposeObserver = null;
  90769. _this.dispose();
  90770. });
  90771. }
  90772. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90773. /**
  90774. * Gets a boolean indicating if the optimizer is in improvement mode
  90775. */
  90776. get: function () {
  90777. return this._improvementMode;
  90778. },
  90779. enumerable: true,
  90780. configurable: true
  90781. });
  90782. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90783. /**
  90784. * Gets the current priority level (0 at start)
  90785. */
  90786. get: function () {
  90787. return this._currentPriorityLevel;
  90788. },
  90789. enumerable: true,
  90790. configurable: true
  90791. });
  90792. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90793. /**
  90794. * Gets the current frame rate checked by the SceneOptimizer
  90795. */
  90796. get: function () {
  90797. return this._currentFrameRate;
  90798. },
  90799. enumerable: true,
  90800. configurable: true
  90801. });
  90802. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90803. /**
  90804. * Gets or sets the current target frame rate (60 by default)
  90805. */
  90806. get: function () {
  90807. return this._targetFrameRate;
  90808. },
  90809. /**
  90810. * Gets or sets the current target frame rate (60 by default)
  90811. */
  90812. set: function (value) {
  90813. this._targetFrameRate = value;
  90814. },
  90815. enumerable: true,
  90816. configurable: true
  90817. });
  90818. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90819. /**
  90820. * Gets or sets the current interval between two checks (every 2000ms by default)
  90821. */
  90822. get: function () {
  90823. return this._trackerDuration;
  90824. },
  90825. /**
  90826. * Gets or sets the current interval between two checks (every 2000ms by default)
  90827. */
  90828. set: function (value) {
  90829. this._trackerDuration = value;
  90830. },
  90831. enumerable: true,
  90832. configurable: true
  90833. });
  90834. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90835. /**
  90836. * Gets the list of active optimizations
  90837. */
  90838. get: function () {
  90839. return this._options.optimizations;
  90840. },
  90841. enumerable: true,
  90842. configurable: true
  90843. });
  90844. /**
  90845. * Stops the current optimizer
  90846. */
  90847. SceneOptimizer.prototype.stop = function () {
  90848. this._isRunning = false;
  90849. };
  90850. /**
  90851. * Reset the optimizer to initial step (current priority level = 0)
  90852. */
  90853. SceneOptimizer.prototype.reset = function () {
  90854. this._currentPriorityLevel = 0;
  90855. };
  90856. /**
  90857. * Start the optimizer. By default it will try to reach a specific framerate
  90858. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90859. */
  90860. SceneOptimizer.prototype.start = function () {
  90861. var _this = this;
  90862. if (this._isRunning) {
  90863. return;
  90864. }
  90865. this._isRunning = true;
  90866. // Let's wait for the scene to be ready before running our check
  90867. this._scene.executeWhenReady(function () {
  90868. setTimeout(function () {
  90869. _this._checkCurrentState();
  90870. }, _this._trackerDuration);
  90871. });
  90872. };
  90873. SceneOptimizer.prototype._checkCurrentState = function () {
  90874. var _this = this;
  90875. if (!this._isRunning) {
  90876. return;
  90877. }
  90878. var scene = this._scene;
  90879. var options = this._options;
  90880. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90881. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90882. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90883. this._isRunning = false;
  90884. this.onSuccessObservable.notifyObservers(this);
  90885. return;
  90886. }
  90887. // Apply current level of optimizations
  90888. var allDone = true;
  90889. var noOptimizationApplied = true;
  90890. for (var index = 0; index < options.optimizations.length; index++) {
  90891. var optimization = options.optimizations[index];
  90892. if (optimization.priority === this._currentPriorityLevel) {
  90893. noOptimizationApplied = false;
  90894. allDone = allDone && optimization.apply(scene, this);
  90895. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90896. }
  90897. }
  90898. // If no optimization was applied, this is a failure :(
  90899. if (noOptimizationApplied) {
  90900. this._isRunning = false;
  90901. this.onFailureObservable.notifyObservers(this);
  90902. return;
  90903. }
  90904. // If all optimizations were done, move to next level
  90905. if (allDone) {
  90906. this._currentPriorityLevel++;
  90907. }
  90908. // Let's the system running for a specific amount of time before checking FPS
  90909. scene.executeWhenReady(function () {
  90910. setTimeout(function () {
  90911. _this._checkCurrentState();
  90912. }, _this._trackerDuration);
  90913. });
  90914. };
  90915. /**
  90916. * Release all resources
  90917. */
  90918. SceneOptimizer.prototype.dispose = function () {
  90919. this.stop();
  90920. this.onSuccessObservable.clear();
  90921. this.onFailureObservable.clear();
  90922. this.onNewOptimizationAppliedObservable.clear();
  90923. if (this._sceneDisposeObserver) {
  90924. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90925. }
  90926. };
  90927. /**
  90928. * Helper function to create a SceneOptimizer with one single line of code
  90929. * @param scene defines the scene to work on
  90930. * @param options defines the options to use with the SceneOptimizer
  90931. * @param onSuccess defines a callback to call on success
  90932. * @param onFailure defines a callback to call on failure
  90933. * @returns the new SceneOptimizer object
  90934. */
  90935. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90936. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90937. if (onSuccess) {
  90938. optimizer.onSuccessObservable.add(function () {
  90939. onSuccess();
  90940. });
  90941. }
  90942. if (onFailure) {
  90943. optimizer.onFailureObservable.add(function () {
  90944. onFailure();
  90945. });
  90946. }
  90947. optimizer.start();
  90948. return optimizer;
  90949. };
  90950. return SceneOptimizer;
  90951. }());
  90952. BABYLON.SceneOptimizer = SceneOptimizer;
  90953. })(BABYLON || (BABYLON = {}));
  90954. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90955. var BABYLON;
  90956. (function (BABYLON) {
  90957. var OutlineRenderer = /** @class */ (function () {
  90958. function OutlineRenderer(scene) {
  90959. this.zOffset = 1;
  90960. this._scene = scene;
  90961. }
  90962. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90963. var _this = this;
  90964. if (useOverlay === void 0) { useOverlay = false; }
  90965. var scene = this._scene;
  90966. var engine = this._scene.getEngine();
  90967. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90968. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90969. return;
  90970. }
  90971. var mesh = subMesh.getRenderingMesh();
  90972. var material = subMesh.getMaterial();
  90973. if (!material || !scene.activeCamera) {
  90974. return;
  90975. }
  90976. engine.enableEffect(this._effect);
  90977. // Logarithmic depth
  90978. if (material.useLogarithmicDepth) {
  90979. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90980. }
  90981. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90982. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90983. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90984. // Bones
  90985. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90986. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90987. }
  90988. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90989. // Alpha test
  90990. if (material && material.needAlphaTesting()) {
  90991. var alphaTexture = material.getAlphaTestTexture();
  90992. if (alphaTexture) {
  90993. this._effect.setTexture("diffuseSampler", alphaTexture);
  90994. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90995. }
  90996. }
  90997. engine.setZOffset(-this.zOffset);
  90998. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90999. engine.setZOffset(0);
  91000. };
  91001. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91002. var defines = [];
  91003. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91004. var mesh = subMesh.getMesh();
  91005. var material = subMesh.getMaterial();
  91006. if (material) {
  91007. // Alpha test
  91008. if (material.needAlphaTesting()) {
  91009. defines.push("#define ALPHATEST");
  91010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91011. attribs.push(BABYLON.VertexBuffer.UVKind);
  91012. defines.push("#define UV1");
  91013. }
  91014. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91016. defines.push("#define UV2");
  91017. }
  91018. }
  91019. //Logarithmic depth
  91020. if (material.useLogarithmicDepth) {
  91021. defines.push("#define LOGARITHMICDEPTH");
  91022. }
  91023. }
  91024. // Bones
  91025. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91028. if (mesh.numBoneInfluencers > 4) {
  91029. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91030. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91031. }
  91032. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91033. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91034. }
  91035. else {
  91036. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91037. }
  91038. // Instances
  91039. if (useInstances) {
  91040. defines.push("#define INSTANCES");
  91041. attribs.push("world0");
  91042. attribs.push("world1");
  91043. attribs.push("world2");
  91044. attribs.push("world3");
  91045. }
  91046. // Get correct effect
  91047. var join = defines.join("\n");
  91048. if (this._cachedDefines !== join) {
  91049. this._cachedDefines = join;
  91050. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91051. }
  91052. return this._effect.isReady();
  91053. };
  91054. return OutlineRenderer;
  91055. }());
  91056. BABYLON.OutlineRenderer = OutlineRenderer;
  91057. })(BABYLON || (BABYLON = {}));
  91058. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91059. var BABYLON;
  91060. (function (BABYLON) {
  91061. var FaceAdjacencies = /** @class */ (function () {
  91062. function FaceAdjacencies() {
  91063. this.edges = new Array();
  91064. this.edgesConnectedCount = 0;
  91065. }
  91066. return FaceAdjacencies;
  91067. }());
  91068. var EdgesRenderer = /** @class */ (function () {
  91069. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91070. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91071. if (epsilon === void 0) { epsilon = 0.95; }
  91072. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91073. this.edgesWidthScalerForOrthographic = 1000.0;
  91074. this.edgesWidthScalerForPerspective = 50.0;
  91075. this._linesPositions = new Array();
  91076. this._linesNormals = new Array();
  91077. this._linesIndices = new Array();
  91078. this._buffers = {};
  91079. this._checkVerticesInsteadOfIndices = false;
  91080. this._source = source;
  91081. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91082. this._epsilon = epsilon;
  91083. this._prepareRessources();
  91084. this._generateEdgesLines();
  91085. }
  91086. EdgesRenderer.prototype._prepareRessources = function () {
  91087. if (this._lineShader) {
  91088. return;
  91089. }
  91090. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91091. attributes: ["position", "normal"],
  91092. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91093. });
  91094. this._lineShader.disableDepthWrite = true;
  91095. this._lineShader.backFaceCulling = false;
  91096. };
  91097. EdgesRenderer.prototype._rebuild = function () {
  91098. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91099. if (buffer) {
  91100. buffer._rebuild();
  91101. }
  91102. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91103. if (buffer) {
  91104. buffer._rebuild();
  91105. }
  91106. var scene = this._source.getScene();
  91107. var engine = scene.getEngine();
  91108. this._ib = engine.createIndexBuffer(this._linesIndices);
  91109. };
  91110. EdgesRenderer.prototype.dispose = function () {
  91111. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91112. if (buffer) {
  91113. buffer.dispose();
  91114. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91115. }
  91116. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91117. if (buffer) {
  91118. buffer.dispose();
  91119. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91120. }
  91121. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91122. this._lineShader.dispose();
  91123. };
  91124. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91125. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91126. return 0;
  91127. }
  91128. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91129. return 1;
  91130. }
  91131. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91132. return 2;
  91133. }
  91134. return -1;
  91135. };
  91136. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91137. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91138. return 0;
  91139. }
  91140. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91141. return 1;
  91142. }
  91143. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91144. return 2;
  91145. }
  91146. return -1;
  91147. };
  91148. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91149. var needToCreateLine;
  91150. if (edge === undefined) {
  91151. needToCreateLine = true;
  91152. }
  91153. else {
  91154. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91155. needToCreateLine = dotProduct < this._epsilon;
  91156. }
  91157. if (needToCreateLine) {
  91158. var offset = this._linesPositions.length / 3;
  91159. var normal = p0.subtract(p1);
  91160. normal.normalize();
  91161. // Positions
  91162. this._linesPositions.push(p0.x);
  91163. this._linesPositions.push(p0.y);
  91164. this._linesPositions.push(p0.z);
  91165. this._linesPositions.push(p0.x);
  91166. this._linesPositions.push(p0.y);
  91167. this._linesPositions.push(p0.z);
  91168. this._linesPositions.push(p1.x);
  91169. this._linesPositions.push(p1.y);
  91170. this._linesPositions.push(p1.z);
  91171. this._linesPositions.push(p1.x);
  91172. this._linesPositions.push(p1.y);
  91173. this._linesPositions.push(p1.z);
  91174. // Normals
  91175. this._linesNormals.push(p1.x);
  91176. this._linesNormals.push(p1.y);
  91177. this._linesNormals.push(p1.z);
  91178. this._linesNormals.push(-1);
  91179. this._linesNormals.push(p1.x);
  91180. this._linesNormals.push(p1.y);
  91181. this._linesNormals.push(p1.z);
  91182. this._linesNormals.push(1);
  91183. this._linesNormals.push(p0.x);
  91184. this._linesNormals.push(p0.y);
  91185. this._linesNormals.push(p0.z);
  91186. this._linesNormals.push(-1);
  91187. this._linesNormals.push(p0.x);
  91188. this._linesNormals.push(p0.y);
  91189. this._linesNormals.push(p0.z);
  91190. this._linesNormals.push(1);
  91191. // Indices
  91192. this._linesIndices.push(offset);
  91193. this._linesIndices.push(offset + 1);
  91194. this._linesIndices.push(offset + 2);
  91195. this._linesIndices.push(offset);
  91196. this._linesIndices.push(offset + 2);
  91197. this._linesIndices.push(offset + 3);
  91198. }
  91199. };
  91200. EdgesRenderer.prototype._generateEdgesLines = function () {
  91201. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91202. var indices = this._source.getIndices();
  91203. if (!indices || !positions) {
  91204. return;
  91205. }
  91206. // First let's find adjacencies
  91207. var adjacencies = new Array();
  91208. var faceNormals = new Array();
  91209. var index;
  91210. var faceAdjacencies;
  91211. // Prepare faces
  91212. for (index = 0; index < indices.length; index += 3) {
  91213. faceAdjacencies = new FaceAdjacencies();
  91214. var p0Index = indices[index];
  91215. var p1Index = indices[index + 1];
  91216. var p2Index = indices[index + 2];
  91217. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91218. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91219. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91220. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91221. faceNormal.normalize();
  91222. faceNormals.push(faceNormal);
  91223. adjacencies.push(faceAdjacencies);
  91224. }
  91225. // Scan
  91226. for (index = 0; index < adjacencies.length; index++) {
  91227. faceAdjacencies = adjacencies[index];
  91228. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91229. var otherFaceAdjacencies = adjacencies[otherIndex];
  91230. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91231. break;
  91232. }
  91233. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91234. continue;
  91235. }
  91236. var otherP0 = indices[otherIndex * 3];
  91237. var otherP1 = indices[otherIndex * 3 + 1];
  91238. var otherP2 = indices[otherIndex * 3 + 2];
  91239. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91240. var otherEdgeIndex = 0;
  91241. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91242. continue;
  91243. }
  91244. switch (edgeIndex) {
  91245. case 0:
  91246. if (this._checkVerticesInsteadOfIndices) {
  91247. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91248. }
  91249. else {
  91250. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91251. }
  91252. break;
  91253. case 1:
  91254. if (this._checkVerticesInsteadOfIndices) {
  91255. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91256. }
  91257. else {
  91258. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91259. }
  91260. break;
  91261. case 2:
  91262. if (this._checkVerticesInsteadOfIndices) {
  91263. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91264. }
  91265. else {
  91266. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91267. }
  91268. break;
  91269. }
  91270. if (otherEdgeIndex === -1) {
  91271. continue;
  91272. }
  91273. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91274. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91275. faceAdjacencies.edgesConnectedCount++;
  91276. otherFaceAdjacencies.edgesConnectedCount++;
  91277. if (faceAdjacencies.edgesConnectedCount === 3) {
  91278. break;
  91279. }
  91280. }
  91281. }
  91282. }
  91283. // Create lines
  91284. for (index = 0; index < adjacencies.length; index++) {
  91285. // 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
  91286. var current = adjacencies[index];
  91287. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91288. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91289. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91290. }
  91291. // Merge into a single mesh
  91292. var engine = this._source.getScene().getEngine();
  91293. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91294. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91295. this._ib = engine.createIndexBuffer(this._linesIndices);
  91296. this._indicesCount = this._linesIndices.length;
  91297. };
  91298. EdgesRenderer.prototype.render = function () {
  91299. var scene = this._source.getScene();
  91300. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91301. return;
  91302. }
  91303. var engine = scene.getEngine();
  91304. this._lineShader._preBind();
  91305. // VBOs
  91306. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91307. scene.resetCachedMaterial();
  91308. this._lineShader.setColor4("color", this._source.edgesColor);
  91309. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91310. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91311. }
  91312. else {
  91313. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91314. }
  91315. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91316. this._lineShader.bind(this._source.getWorldMatrix());
  91317. // Draw order
  91318. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91319. this._lineShader.unbind();
  91320. engine.setDepthWrite(true);
  91321. };
  91322. return EdgesRenderer;
  91323. }());
  91324. BABYLON.EdgesRenderer = EdgesRenderer;
  91325. })(BABYLON || (BABYLON = {}));
  91326. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91327. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91328. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91329. s = arguments[i];
  91330. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91331. t[p] = s[p];
  91332. }
  91333. return t;
  91334. };
  91335. var BABYLON;
  91336. (function (BABYLON) {
  91337. /**
  91338. * The effect layer Helps adding post process effect blended with the main pass.
  91339. *
  91340. * This can be for instance use to generate glow or higlight effects on the scene.
  91341. *
  91342. * The effect layer class can not be used directly and is intented to inherited from to be
  91343. * customized per effects.
  91344. */
  91345. var EffectLayer = /** @class */ (function () {
  91346. /**
  91347. * Instantiates a new effect Layer and references it in the scene.
  91348. * @param name The name of the layer
  91349. * @param scene The scene to use the layer in
  91350. */
  91351. function EffectLayer(
  91352. /** The Friendly of the effect in the scene */
  91353. name, scene) {
  91354. this._vertexBuffers = {};
  91355. this._maxSize = 0;
  91356. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91357. this._shouldRender = true;
  91358. this._postProcesses = [];
  91359. this._textures = [];
  91360. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91361. /**
  91362. * The clear color of the texture used to generate the glow map.
  91363. */
  91364. this.neutralColor = new BABYLON.Color4();
  91365. /**
  91366. * Specifies wether the highlight layer is enabled or not.
  91367. */
  91368. this.isEnabled = true;
  91369. /**
  91370. * An event triggered when the effect layer has been disposed.
  91371. */
  91372. this.onDisposeObservable = new BABYLON.Observable();
  91373. /**
  91374. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91375. */
  91376. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91377. /**
  91378. * An event triggered when the generated texture is being merged in the scene.
  91379. */
  91380. this.onBeforeComposeObservable = new BABYLON.Observable();
  91381. /**
  91382. * An event triggered when the generated texture has been merged in the scene.
  91383. */
  91384. this.onAfterComposeObservable = new BABYLON.Observable();
  91385. /**
  91386. * An event triggered when the efffect layer changes its size.
  91387. */
  91388. this.onSizeChangedObservable = new BABYLON.Observable();
  91389. this.name = name;
  91390. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91391. this._engine = scene.getEngine();
  91392. this._maxSize = this._engine.getCaps().maxTextureSize;
  91393. this._scene.effectLayers.push(this);
  91394. // Generate Buffers
  91395. this._generateIndexBuffer();
  91396. this._genrateVertexBuffer();
  91397. }
  91398. Object.defineProperty(EffectLayer.prototype, "camera", {
  91399. /**
  91400. * Gets the camera attached to the layer.
  91401. */
  91402. get: function () {
  91403. return this._effectLayerOptions.camera;
  91404. },
  91405. enumerable: true,
  91406. configurable: true
  91407. });
  91408. /**
  91409. * Initializes the effect layer with the required options.
  91410. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91411. */
  91412. EffectLayer.prototype._init = function (options) {
  91413. // Adapt options
  91414. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91415. this._setMainTextureSize();
  91416. this._createMainTexture();
  91417. this._createTextureAndPostProcesses();
  91418. this._mergeEffect = this._createMergeEffect();
  91419. };
  91420. /**
  91421. * Generates the index buffer of the full screen quad blending to the main canvas.
  91422. */
  91423. EffectLayer.prototype._generateIndexBuffer = function () {
  91424. // Indices
  91425. var indices = [];
  91426. indices.push(0);
  91427. indices.push(1);
  91428. indices.push(2);
  91429. indices.push(0);
  91430. indices.push(2);
  91431. indices.push(3);
  91432. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91433. };
  91434. /**
  91435. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91436. */
  91437. EffectLayer.prototype._genrateVertexBuffer = function () {
  91438. // VBO
  91439. var vertices = [];
  91440. vertices.push(1, 1);
  91441. vertices.push(-1, 1);
  91442. vertices.push(-1, -1);
  91443. vertices.push(1, -1);
  91444. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91445. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91446. };
  91447. /**
  91448. * Sets the main texture desired size which is the closest power of two
  91449. * of the engine canvas size.
  91450. */
  91451. EffectLayer.prototype._setMainTextureSize = function () {
  91452. if (this._effectLayerOptions.mainTextureFixedSize) {
  91453. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91454. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91455. }
  91456. else {
  91457. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91458. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91459. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91460. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91461. }
  91462. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91463. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91464. };
  91465. /**
  91466. * Creates the main texture for the effect layer.
  91467. */
  91468. EffectLayer.prototype._createMainTexture = function () {
  91469. var _this = this;
  91470. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91471. width: this._mainTextureDesiredSize.width,
  91472. height: this._mainTextureDesiredSize.height
  91473. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91474. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91475. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91476. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91477. this._mainTexture.anisotropicFilteringLevel = 1;
  91478. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91479. this._mainTexture.renderParticles = false;
  91480. this._mainTexture.renderList = null;
  91481. this._mainTexture.ignoreCameraViewport = true;
  91482. // Custom render function
  91483. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91484. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91485. var index;
  91486. var engine = _this._scene.getEngine();
  91487. if (depthOnlySubMeshes.length) {
  91488. engine.setColorWrite(false);
  91489. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91490. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91491. }
  91492. engine.setColorWrite(true);
  91493. }
  91494. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91495. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91496. }
  91497. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91498. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91499. }
  91500. for (index = 0; index < transparentSubMeshes.length; index++) {
  91501. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91502. }
  91503. };
  91504. this._mainTexture.onClearObservable.add(function (engine) {
  91505. engine.clear(_this.neutralColor, true, true, true);
  91506. });
  91507. };
  91508. /**
  91509. * Checks for the readiness of the element composing the layer.
  91510. * @param subMesh the mesh to check for
  91511. * @param useInstances specify wether or not to use instances to render the mesh
  91512. * @param emissiveTexture the associated emissive texture used to generate the glow
  91513. * @return true if ready otherwise, false
  91514. */
  91515. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91516. var material = subMesh.getMaterial();
  91517. if (!material) {
  91518. return false;
  91519. }
  91520. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91521. return false;
  91522. }
  91523. var defines = [];
  91524. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91525. var mesh = subMesh.getMesh();
  91526. var uv1 = false;
  91527. var uv2 = false;
  91528. // Alpha test
  91529. if (material && material.needAlphaTesting()) {
  91530. var alphaTexture = material.getAlphaTestTexture();
  91531. if (alphaTexture) {
  91532. defines.push("#define ALPHATEST");
  91533. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91534. alphaTexture.coordinatesIndex === 1) {
  91535. defines.push("#define DIFFUSEUV2");
  91536. uv2 = true;
  91537. }
  91538. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91539. defines.push("#define DIFFUSEUV1");
  91540. uv1 = true;
  91541. }
  91542. }
  91543. }
  91544. // Emissive
  91545. if (emissiveTexture) {
  91546. defines.push("#define EMISSIVE");
  91547. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91548. emissiveTexture.coordinatesIndex === 1) {
  91549. defines.push("#define EMISSIVEUV2");
  91550. uv2 = true;
  91551. }
  91552. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91553. defines.push("#define EMISSIVEUV1");
  91554. uv1 = true;
  91555. }
  91556. }
  91557. if (uv1) {
  91558. attribs.push(BABYLON.VertexBuffer.UVKind);
  91559. defines.push("#define UV1");
  91560. }
  91561. if (uv2) {
  91562. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91563. defines.push("#define UV2");
  91564. }
  91565. // Bones
  91566. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91567. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91568. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91569. if (mesh.numBoneInfluencers > 4) {
  91570. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91571. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91572. }
  91573. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91574. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91575. }
  91576. else {
  91577. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91578. }
  91579. // Morph targets
  91580. var manager = mesh.morphTargetManager;
  91581. var morphInfluencers = 0;
  91582. if (manager) {
  91583. if (manager.numInfluencers > 0) {
  91584. defines.push("#define MORPHTARGETS");
  91585. morphInfluencers = manager.numInfluencers;
  91586. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91587. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91588. }
  91589. }
  91590. // Instances
  91591. if (useInstances) {
  91592. defines.push("#define INSTANCES");
  91593. attribs.push("world0");
  91594. attribs.push("world1");
  91595. attribs.push("world2");
  91596. attribs.push("world3");
  91597. }
  91598. // Get correct effect
  91599. var join = defines.join("\n");
  91600. if (this._cachedDefines !== join) {
  91601. this._cachedDefines = join;
  91602. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91603. }
  91604. return this._effectLayerMapGenerationEffect.isReady();
  91605. };
  91606. /**
  91607. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91608. */
  91609. EffectLayer.prototype.render = function () {
  91610. var currentEffect = this._mergeEffect;
  91611. // Check
  91612. if (!currentEffect.isReady())
  91613. return;
  91614. for (var i = 0; i < this._postProcesses.length; i++) {
  91615. if (!this._postProcesses[i].isReady()) {
  91616. return;
  91617. }
  91618. }
  91619. var engine = this._scene.getEngine();
  91620. this.onBeforeComposeObservable.notifyObservers(this);
  91621. // Render
  91622. engine.enableEffect(currentEffect);
  91623. engine.setState(false);
  91624. // VBOs
  91625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91626. // Cache
  91627. var previousAlphaMode = engine.getAlphaMode();
  91628. // Go Blend.
  91629. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91630. // Blends the map on the main canvas.
  91631. this._internalRender(currentEffect);
  91632. // Restore Alpha
  91633. engine.setAlphaMode(previousAlphaMode);
  91634. this.onAfterComposeObservable.notifyObservers(this);
  91635. // Handle size changes.
  91636. var size = this._mainTexture.getSize();
  91637. this._setMainTextureSize();
  91638. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91639. // Recreate RTT and post processes on size change.
  91640. this.onSizeChangedObservable.notifyObservers(this);
  91641. this._disposeTextureAndPostProcesses();
  91642. this._createMainTexture();
  91643. this._createTextureAndPostProcesses();
  91644. }
  91645. };
  91646. /**
  91647. * Determine if a given mesh will be used in the current effect.
  91648. * @param mesh mesh to test
  91649. * @returns true if the mesh will be used
  91650. */
  91651. EffectLayer.prototype.hasMesh = function (mesh) {
  91652. return true;
  91653. };
  91654. /**
  91655. * Returns true if the layer contains information to display, otherwise false.
  91656. * @returns true if the glow layer should be rendered
  91657. */
  91658. EffectLayer.prototype.shouldRender = function () {
  91659. return this.isEnabled && this._shouldRender;
  91660. };
  91661. /**
  91662. * Returns true if the mesh should render, otherwise false.
  91663. * @param mesh The mesh to render
  91664. * @returns true if it should render otherwise false
  91665. */
  91666. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91667. return true;
  91668. };
  91669. /**
  91670. * Returns true if the mesh should render, otherwise false.
  91671. * @param mesh The mesh to render
  91672. * @returns true if it should render otherwise false
  91673. */
  91674. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91675. return true;
  91676. };
  91677. /**
  91678. * Renders the submesh passed in parameter to the generation map.
  91679. */
  91680. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91681. var _this = this;
  91682. if (!this.shouldRender()) {
  91683. return;
  91684. }
  91685. var material = subMesh.getMaterial();
  91686. var mesh = subMesh.getRenderingMesh();
  91687. var scene = this._scene;
  91688. var engine = scene.getEngine();
  91689. if (!material) {
  91690. return;
  91691. }
  91692. // Do not block in blend mode.
  91693. if (material.needAlphaBlendingForMesh(mesh)) {
  91694. return;
  91695. }
  91696. // Culling
  91697. engine.setState(material.backFaceCulling);
  91698. // Managing instances
  91699. var batch = mesh._getInstancesRenderList(subMesh._id);
  91700. if (batch.mustReturn) {
  91701. return;
  91702. }
  91703. // Early Exit per mesh
  91704. if (!this._shouldRenderMesh(mesh)) {
  91705. return;
  91706. }
  91707. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91708. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91709. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91710. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91711. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91712. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91713. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91714. // Alpha test
  91715. if (material && material.needAlphaTesting()) {
  91716. var alphaTexture = material.getAlphaTestTexture();
  91717. if (alphaTexture) {
  91718. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91719. var textureMatrix = alphaTexture.getTextureMatrix();
  91720. if (textureMatrix) {
  91721. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91722. }
  91723. }
  91724. }
  91725. // Glow emissive only
  91726. if (this._emissiveTextureAndColor.texture) {
  91727. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91728. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91729. }
  91730. // Bones
  91731. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91732. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91733. }
  91734. // Morph targets
  91735. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91736. // Draw
  91737. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91738. }
  91739. else {
  91740. // Need to reset refresh rate of the shadowMap
  91741. this._mainTexture.resetRefreshCounter();
  91742. }
  91743. };
  91744. /**
  91745. * Rebuild the required buffers.
  91746. * @hidden Internal use only.
  91747. */
  91748. EffectLayer.prototype._rebuild = function () {
  91749. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91750. if (vb) {
  91751. vb._rebuild();
  91752. }
  91753. this._generateIndexBuffer();
  91754. };
  91755. /**
  91756. * Dispose only the render target textures and post process.
  91757. */
  91758. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91759. this._mainTexture.dispose();
  91760. for (var i = 0; i < this._postProcesses.length; i++) {
  91761. if (this._postProcesses[i]) {
  91762. this._postProcesses[i].dispose();
  91763. }
  91764. }
  91765. this._postProcesses = [];
  91766. for (var i = 0; i < this._textures.length; i++) {
  91767. if (this._textures[i]) {
  91768. this._textures[i].dispose();
  91769. }
  91770. }
  91771. this._textures = [];
  91772. };
  91773. /**
  91774. * Dispose the highlight layer and free resources.
  91775. */
  91776. EffectLayer.prototype.dispose = function () {
  91777. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91778. if (vertexBuffer) {
  91779. vertexBuffer.dispose();
  91780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91781. }
  91782. if (this._indexBuffer) {
  91783. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91784. this._indexBuffer = null;
  91785. }
  91786. // Clean textures and post processes
  91787. this._disposeTextureAndPostProcesses();
  91788. // Remove from scene
  91789. var index = this._scene.effectLayers.indexOf(this, 0);
  91790. if (index > -1) {
  91791. this._scene.effectLayers.splice(index, 1);
  91792. }
  91793. // Callback
  91794. this.onDisposeObservable.notifyObservers(this);
  91795. this.onDisposeObservable.clear();
  91796. this.onBeforeRenderMainTextureObservable.clear();
  91797. this.onBeforeComposeObservable.clear();
  91798. this.onAfterComposeObservable.clear();
  91799. this.onSizeChangedObservable.clear();
  91800. };
  91801. /**
  91802. * Gets the class name of the effect layer
  91803. * @returns the string with the class name of the effect layer
  91804. */
  91805. EffectLayer.prototype.getClassName = function () {
  91806. return "EffectLayer";
  91807. };
  91808. /**
  91809. * Creates an effect layer from parsed effect layer data
  91810. * @param parsedEffectLayer defines effect layer data
  91811. * @param scene defines the current scene
  91812. * @param rootUrl defines the root URL containing the effect layer information
  91813. * @returns a parsed effect Layer
  91814. */
  91815. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91816. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91817. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91818. };
  91819. __decorate([
  91820. BABYLON.serialize()
  91821. ], EffectLayer.prototype, "name", void 0);
  91822. __decorate([
  91823. BABYLON.serializeAsColor4()
  91824. ], EffectLayer.prototype, "neutralColor", void 0);
  91825. __decorate([
  91826. BABYLON.serialize()
  91827. ], EffectLayer.prototype, "isEnabled", void 0);
  91828. __decorate([
  91829. BABYLON.serializeAsCameraReference()
  91830. ], EffectLayer.prototype, "camera", null);
  91831. return EffectLayer;
  91832. }());
  91833. BABYLON.EffectLayer = EffectLayer;
  91834. })(BABYLON || (BABYLON = {}));
  91835. //# sourceMappingURL=babylon.effectLayer.js.map
  91836. var BABYLON;
  91837. (function (BABYLON) {
  91838. /**
  91839. * Special Glow Blur post process only blurring the alpha channel
  91840. * It enforces keeping the most luminous color in the color channel.
  91841. */
  91842. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91843. __extends(GlowBlurPostProcess, _super);
  91844. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91846. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91847. _this.direction = direction;
  91848. _this.kernel = kernel;
  91849. _this.onApplyObservable.add(function (effect) {
  91850. effect.setFloat2("screenSize", _this.width, _this.height);
  91851. effect.setVector2("direction", _this.direction);
  91852. effect.setFloat("blurWidth", _this.kernel);
  91853. });
  91854. return _this;
  91855. }
  91856. return GlowBlurPostProcess;
  91857. }(BABYLON.PostProcess));
  91858. /**
  91859. * The highlight layer Helps adding a glow effect around a mesh.
  91860. *
  91861. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91862. * glowy meshes to your scene.
  91863. *
  91864. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91865. */
  91866. var HighlightLayer = /** @class */ (function (_super) {
  91867. __extends(HighlightLayer, _super);
  91868. /**
  91869. * Instantiates a new highlight Layer and references it to the scene..
  91870. * @param name The name of the layer
  91871. * @param scene The scene to use the layer in
  91872. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91873. */
  91874. function HighlightLayer(name, scene, options) {
  91875. var _this = _super.call(this, name, scene) || this;
  91876. _this.name = name;
  91877. /**
  91878. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91879. */
  91880. _this.innerGlow = true;
  91881. /**
  91882. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91883. */
  91884. _this.outerGlow = true;
  91885. /**
  91886. * An event triggered when the highlight layer is being blurred.
  91887. */
  91888. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91889. /**
  91890. * An event triggered when the highlight layer has been blurred.
  91891. */
  91892. _this.onAfterBlurObservable = new BABYLON.Observable();
  91893. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91894. _this._meshes = {};
  91895. _this._excludedMeshes = {};
  91896. _this.neutralColor = HighlightLayer.NeutralColor;
  91897. // Warn on stencil
  91898. if (!_this._engine.isStencilEnable) {
  91899. 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 }");
  91900. }
  91901. // Adapt options
  91902. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91903. // Initialize the layer
  91904. _this._init({
  91905. alphaBlendingMode: _this._options.alphaBlendingMode,
  91906. camera: _this._options.camera,
  91907. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91908. mainTextureRatio: _this._options.mainTextureRatio
  91909. });
  91910. // Do not render as long as no meshes have been added
  91911. _this._shouldRender = false;
  91912. return _this;
  91913. }
  91914. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91915. /**
  91916. * Gets the horizontal size of the blur.
  91917. */
  91918. get: function () {
  91919. return this._horizontalBlurPostprocess.kernel;
  91920. },
  91921. /**
  91922. * Specifies the horizontal size of the blur.
  91923. */
  91924. set: function (value) {
  91925. this._horizontalBlurPostprocess.kernel = value;
  91926. },
  91927. enumerable: true,
  91928. configurable: true
  91929. });
  91930. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91931. /**
  91932. * Gets the vertical size of the blur.
  91933. */
  91934. get: function () {
  91935. return this._verticalBlurPostprocess.kernel;
  91936. },
  91937. /**
  91938. * Specifies the vertical size of the blur.
  91939. */
  91940. set: function (value) {
  91941. this._verticalBlurPostprocess.kernel = value;
  91942. },
  91943. enumerable: true,
  91944. configurable: true
  91945. });
  91946. /**
  91947. * Get the effect name of the layer.
  91948. * @return The effect name
  91949. */
  91950. HighlightLayer.prototype.getEffectName = function () {
  91951. return HighlightLayer.EffectName;
  91952. };
  91953. /**
  91954. * Create the merge effect. This is the shader use to blit the information back
  91955. * to the main canvas at the end of the scene rendering.
  91956. */
  91957. HighlightLayer.prototype._createMergeEffect = function () {
  91958. // Effect
  91959. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91960. };
  91961. /**
  91962. * Creates the render target textures and post processes used in the highlight layer.
  91963. */
  91964. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91965. var _this = this;
  91966. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91967. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91968. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91969. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91970. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91971. width: blurTextureWidth,
  91972. height: blurTextureHeight
  91973. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91974. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91975. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91976. this._blurTexture.anisotropicFilteringLevel = 16;
  91977. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91978. this._blurTexture.renderParticles = false;
  91979. this._blurTexture.ignoreCameraViewport = true;
  91980. this._textures = [this._blurTexture];
  91981. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91982. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91983. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91984. effect.setTexture("textureSampler", _this._mainTexture);
  91985. });
  91986. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91987. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91988. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91989. });
  91990. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91991. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91992. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91993. });
  91994. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91995. }
  91996. else {
  91997. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91998. width: blurTextureWidth,
  91999. height: blurTextureHeight
  92000. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92001. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92002. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92003. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92004. effect.setTexture("textureSampler", _this._mainTexture);
  92005. });
  92006. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92007. width: blurTextureWidth,
  92008. height: blurTextureHeight
  92009. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92010. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92011. }
  92012. this._mainTexture.onAfterUnbindObservable.add(function () {
  92013. _this.onBeforeBlurObservable.notifyObservers(_this);
  92014. var internalTexture = _this._blurTexture.getInternalTexture();
  92015. if (internalTexture) {
  92016. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92017. }
  92018. _this.onAfterBlurObservable.notifyObservers(_this);
  92019. });
  92020. // Prevent autoClear.
  92021. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92022. };
  92023. /**
  92024. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92025. */
  92026. HighlightLayer.prototype.needStencil = function () {
  92027. return true;
  92028. };
  92029. /**
  92030. * Checks for the readiness of the element composing the layer.
  92031. * @param subMesh the mesh to check for
  92032. * @param useInstances specify wether or not to use instances to render the mesh
  92033. * @param emissiveTexture the associated emissive texture used to generate the glow
  92034. * @return true if ready otherwise, false
  92035. */
  92036. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92037. var material = subMesh.getMaterial();
  92038. var mesh = subMesh.getRenderingMesh();
  92039. if (!material || !mesh || !this._meshes) {
  92040. return false;
  92041. }
  92042. var emissiveTexture = null;
  92043. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92044. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92045. emissiveTexture = material.emissiveTexture;
  92046. }
  92047. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92048. };
  92049. /**
  92050. * Implementation specific of rendering the generating effect on the main canvas.
  92051. * @param effect The effect used to render through
  92052. */
  92053. HighlightLayer.prototype._internalRender = function (effect) {
  92054. // Texture
  92055. effect.setTexture("textureSampler", this._blurTexture);
  92056. // Cache
  92057. var engine = this._engine;
  92058. var previousStencilBuffer = engine.getStencilBuffer();
  92059. var previousStencilFunction = engine.getStencilFunction();
  92060. var previousStencilMask = engine.getStencilMask();
  92061. var previousStencilOperationPass = engine.getStencilOperationPass();
  92062. var previousStencilOperationFail = engine.getStencilOperationFail();
  92063. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92064. var previousStencilReference = engine.getStencilFunctionReference();
  92065. // Stencil operations
  92066. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92067. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92068. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92069. // Draw order
  92070. engine.setStencilMask(0x00);
  92071. engine.setStencilBuffer(true);
  92072. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92073. // 2 passes inner outer
  92074. if (this.outerGlow) {
  92075. effect.setFloat("offset", 0);
  92076. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92078. }
  92079. if (this.innerGlow) {
  92080. effect.setFloat("offset", 1);
  92081. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92082. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92083. }
  92084. // Restore Cache
  92085. engine.setStencilFunction(previousStencilFunction);
  92086. engine.setStencilMask(previousStencilMask);
  92087. engine.setStencilBuffer(previousStencilBuffer);
  92088. engine.setStencilOperationPass(previousStencilOperationPass);
  92089. engine.setStencilOperationFail(previousStencilOperationFail);
  92090. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92091. engine.setStencilFunctionReference(previousStencilReference);
  92092. };
  92093. /**
  92094. * Returns true if the layer contains information to display, otherwise false.
  92095. */
  92096. HighlightLayer.prototype.shouldRender = function () {
  92097. if (_super.prototype.shouldRender.call(this)) {
  92098. return this._meshes ? true : false;
  92099. }
  92100. return false;
  92101. };
  92102. /**
  92103. * Returns true if the mesh should render, otherwise false.
  92104. * @param mesh The mesh to render
  92105. * @returns true if it should render otherwise false
  92106. */
  92107. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92108. // Excluded Mesh
  92109. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92110. return false;
  92111. }
  92112. ;
  92113. return true;
  92114. };
  92115. /**
  92116. * Sets the required values for both the emissive texture and and the main color.
  92117. */
  92118. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92119. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92120. if (highlightLayerMesh) {
  92121. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92122. }
  92123. else {
  92124. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92125. }
  92126. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92127. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92128. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92129. }
  92130. else {
  92131. this._emissiveTextureAndColor.texture = null;
  92132. }
  92133. };
  92134. /**
  92135. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92136. * @param mesh The mesh to exclude from the highlight layer
  92137. */
  92138. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92139. if (!this._excludedMeshes) {
  92140. return;
  92141. }
  92142. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92143. if (!meshExcluded) {
  92144. this._excludedMeshes[mesh.uniqueId] = {
  92145. mesh: mesh,
  92146. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92147. mesh.getEngine().setStencilBuffer(false);
  92148. }),
  92149. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92150. mesh.getEngine().setStencilBuffer(true);
  92151. }),
  92152. };
  92153. }
  92154. };
  92155. /**
  92156. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92157. * @param mesh The mesh to highlight
  92158. */
  92159. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92160. if (!this._excludedMeshes) {
  92161. return;
  92162. }
  92163. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92164. if (meshExcluded) {
  92165. if (meshExcluded.beforeRender) {
  92166. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92167. }
  92168. if (meshExcluded.afterRender) {
  92169. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92170. }
  92171. }
  92172. this._excludedMeshes[mesh.uniqueId] = null;
  92173. };
  92174. /**
  92175. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92176. * @param mesh mesh to test
  92177. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92178. */
  92179. HighlightLayer.prototype.hasMesh = function (mesh) {
  92180. if (!this._meshes) {
  92181. return false;
  92182. }
  92183. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92184. };
  92185. /**
  92186. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92187. * @param mesh The mesh to highlight
  92188. * @param color The color of the highlight
  92189. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92190. */
  92191. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92192. var _this = this;
  92193. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92194. if (!this._meshes) {
  92195. return;
  92196. }
  92197. var meshHighlight = this._meshes[mesh.uniqueId];
  92198. if (meshHighlight) {
  92199. meshHighlight.color = color;
  92200. }
  92201. else {
  92202. this._meshes[mesh.uniqueId] = {
  92203. mesh: mesh,
  92204. color: color,
  92205. // Lambda required for capture due to Observable this context
  92206. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92207. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92208. _this._defaultStencilReference(mesh);
  92209. }
  92210. else {
  92211. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92212. }
  92213. }),
  92214. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92215. glowEmissiveOnly: glowEmissiveOnly
  92216. };
  92217. }
  92218. this._shouldRender = true;
  92219. };
  92220. /**
  92221. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92222. * @param mesh The mesh to highlight
  92223. */
  92224. HighlightLayer.prototype.removeMesh = function (mesh) {
  92225. if (!this._meshes) {
  92226. return;
  92227. }
  92228. var meshHighlight = this._meshes[mesh.uniqueId];
  92229. if (meshHighlight) {
  92230. if (meshHighlight.observerHighlight) {
  92231. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92232. }
  92233. if (meshHighlight.observerDefault) {
  92234. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92235. }
  92236. delete this._meshes[mesh.uniqueId];
  92237. }
  92238. this._shouldRender = false;
  92239. for (var meshHighlightToCheck in this._meshes) {
  92240. if (this._meshes[meshHighlightToCheck]) {
  92241. this._shouldRender = true;
  92242. break;
  92243. }
  92244. }
  92245. };
  92246. /**
  92247. * Force the stencil to the normal expected value for none glowing parts
  92248. */
  92249. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92250. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92251. };
  92252. /**
  92253. * Free any resources and references associated to a mesh.
  92254. * Internal use
  92255. * @param mesh The mesh to free.
  92256. */
  92257. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92258. this.removeMesh(mesh);
  92259. this.removeExcludedMesh(mesh);
  92260. };
  92261. /**
  92262. * Dispose the highlight layer and free resources.
  92263. */
  92264. HighlightLayer.prototype.dispose = function () {
  92265. if (this._meshes) {
  92266. // Clean mesh references
  92267. for (var id in this._meshes) {
  92268. var meshHighlight = this._meshes[id];
  92269. if (meshHighlight && meshHighlight.mesh) {
  92270. if (meshHighlight.observerHighlight) {
  92271. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92272. }
  92273. if (meshHighlight.observerDefault) {
  92274. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92275. }
  92276. }
  92277. }
  92278. this._meshes = null;
  92279. }
  92280. if (this._excludedMeshes) {
  92281. for (var id in this._excludedMeshes) {
  92282. var meshHighlight = this._excludedMeshes[id];
  92283. if (meshHighlight) {
  92284. if (meshHighlight.beforeRender) {
  92285. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92286. }
  92287. if (meshHighlight.afterRender) {
  92288. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92289. }
  92290. }
  92291. }
  92292. this._excludedMeshes = null;
  92293. }
  92294. _super.prototype.dispose.call(this);
  92295. };
  92296. /**
  92297. * Gets the class name of the effect layer
  92298. * @returns the string with the class name of the effect layer
  92299. */
  92300. HighlightLayer.prototype.getClassName = function () {
  92301. return "HighlightLayer";
  92302. };
  92303. /**
  92304. * Serializes this Highlight layer
  92305. * @returns a serialized Highlight layer object
  92306. */
  92307. HighlightLayer.prototype.serialize = function () {
  92308. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92309. serializationObject.customType = "BABYLON.HighlightLayer";
  92310. // Highlighted meshes
  92311. serializationObject.meshes = [];
  92312. if (this._meshes) {
  92313. for (var m in this._meshes) {
  92314. var mesh = this._meshes[m];
  92315. if (mesh) {
  92316. serializationObject.meshes.push({
  92317. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92318. color: mesh.color.asArray(),
  92319. meshId: mesh.mesh.id
  92320. });
  92321. }
  92322. }
  92323. }
  92324. // Excluded meshes
  92325. serializationObject.excludedMeshes = [];
  92326. if (this._excludedMeshes) {
  92327. for (var e in this._excludedMeshes) {
  92328. var excludedMesh = this._excludedMeshes[e];
  92329. if (excludedMesh) {
  92330. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92331. }
  92332. }
  92333. }
  92334. return serializationObject;
  92335. };
  92336. /**
  92337. * Creates a Highlight layer from parsed Highlight layer data
  92338. * @param parsedHightlightLayer defines the Highlight layer data
  92339. * @param scene defines the current scene
  92340. * @param rootUrl defines the root URL containing the Highlight layer information
  92341. * @returns a parsed Highlight layer
  92342. */
  92343. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92344. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92345. var index;
  92346. // Excluded meshes
  92347. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92348. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92349. if (mesh) {
  92350. hl.addExcludedMesh(mesh);
  92351. }
  92352. }
  92353. // Included meshes
  92354. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92355. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92356. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92357. if (mesh) {
  92358. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92359. }
  92360. }
  92361. return hl;
  92362. };
  92363. /**
  92364. * Effect Name of the highlight layer.
  92365. */
  92366. HighlightLayer.EffectName = "HighlightLayer";
  92367. /**
  92368. * The neutral color used during the preparation of the glow effect.
  92369. * This is black by default as the blend operation is a blend operation.
  92370. */
  92371. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92372. /**
  92373. * Stencil value used for glowing meshes.
  92374. */
  92375. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92376. /**
  92377. * Stencil value used for the other meshes in the scene.
  92378. */
  92379. HighlightLayer.NormalMeshStencilReference = 0x01;
  92380. __decorate([
  92381. BABYLON.serialize()
  92382. ], HighlightLayer.prototype, "innerGlow", void 0);
  92383. __decorate([
  92384. BABYLON.serialize()
  92385. ], HighlightLayer.prototype, "outerGlow", void 0);
  92386. __decorate([
  92387. BABYLON.serialize()
  92388. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92389. __decorate([
  92390. BABYLON.serialize()
  92391. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92392. __decorate([
  92393. BABYLON.serialize("options")
  92394. ], HighlightLayer.prototype, "_options", void 0);
  92395. return HighlightLayer;
  92396. }(BABYLON.EffectLayer));
  92397. BABYLON.HighlightLayer = HighlightLayer;
  92398. })(BABYLON || (BABYLON = {}));
  92399. //# sourceMappingURL=babylon.highlightLayer.js.map
  92400. var BABYLON;
  92401. (function (BABYLON) {
  92402. /**
  92403. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92404. *
  92405. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92406. * glowy meshes to your scene.
  92407. *
  92408. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92409. */
  92410. var GlowLayer = /** @class */ (function (_super) {
  92411. __extends(GlowLayer, _super);
  92412. /**
  92413. * Instantiates a new glow Layer and references it to the scene.
  92414. * @param name The name of the layer
  92415. * @param scene The scene to use the layer in
  92416. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92417. */
  92418. function GlowLayer(name, scene, options) {
  92419. var _this = _super.call(this, name, scene) || this;
  92420. _this._intensity = 1.0;
  92421. _this._includedOnlyMeshes = [];
  92422. _this._excludedMeshes = [];
  92423. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92424. // Adapt options
  92425. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92426. // Initialize the layer
  92427. _this._init({
  92428. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92429. camera: _this._options.camera,
  92430. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92431. mainTextureRatio: _this._options.mainTextureRatio
  92432. });
  92433. return _this;
  92434. }
  92435. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92436. /**
  92437. * Gets the kernel size of the blur.
  92438. */
  92439. get: function () {
  92440. return this._horizontalBlurPostprocess1.kernel;
  92441. },
  92442. /**
  92443. * Sets the kernel size of the blur.
  92444. */
  92445. set: function (value) {
  92446. this._horizontalBlurPostprocess1.kernel = value;
  92447. this._verticalBlurPostprocess1.kernel = value;
  92448. this._horizontalBlurPostprocess2.kernel = value;
  92449. this._verticalBlurPostprocess2.kernel = value;
  92450. },
  92451. enumerable: true,
  92452. configurable: true
  92453. });
  92454. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92455. /**
  92456. * Gets the glow intensity.
  92457. */
  92458. get: function () {
  92459. return this._intensity;
  92460. },
  92461. /**
  92462. * Sets the glow intensity.
  92463. */
  92464. set: function (value) {
  92465. this._intensity = value;
  92466. },
  92467. enumerable: true,
  92468. configurable: true
  92469. });
  92470. /**
  92471. * Get the effect name of the layer.
  92472. * @return The effect name
  92473. */
  92474. GlowLayer.prototype.getEffectName = function () {
  92475. return GlowLayer.EffectName;
  92476. };
  92477. /**
  92478. * Create the merge effect. This is the shader use to blit the information back
  92479. * to the main canvas at the end of the scene rendering.
  92480. */
  92481. GlowLayer.prototype._createMergeEffect = function () {
  92482. // Effect
  92483. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92484. };
  92485. /**
  92486. * Creates the render target textures and post processes used in the glow layer.
  92487. */
  92488. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92489. var _this = this;
  92490. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92491. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92492. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92493. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92494. var textureType = 0;
  92495. if (this._engine.getCaps().textureHalfFloatRender) {
  92496. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92497. }
  92498. else {
  92499. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92500. }
  92501. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92502. width: blurTextureWidth,
  92503. height: blurTextureHeight
  92504. }, this._scene, false, true, textureType);
  92505. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92506. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92507. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92508. this._blurTexture1.renderParticles = false;
  92509. this._blurTexture1.ignoreCameraViewport = true;
  92510. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92511. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92512. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92513. width: blurTextureWidth2,
  92514. height: blurTextureHeight2
  92515. }, this._scene, false, true, textureType);
  92516. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92517. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92518. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92519. this._blurTexture2.renderParticles = false;
  92520. this._blurTexture2.ignoreCameraViewport = true;
  92521. this._textures = [this._blurTexture1, this._blurTexture2];
  92522. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92523. width: blurTextureWidth,
  92524. height: blurTextureHeight
  92525. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92526. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92527. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92528. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92529. effect.setTexture("textureSampler", _this._mainTexture);
  92530. });
  92531. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92532. width: blurTextureWidth,
  92533. height: blurTextureHeight
  92534. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92535. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92536. width: blurTextureWidth2,
  92537. height: blurTextureHeight2
  92538. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92539. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92540. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92541. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92542. effect.setTexture("textureSampler", _this._blurTexture1);
  92543. });
  92544. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92545. width: blurTextureWidth2,
  92546. height: blurTextureHeight2
  92547. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92548. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92549. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92550. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92551. this._mainTexture.samples = this._options.mainTextureSamples;
  92552. this._mainTexture.onAfterUnbindObservable.add(function () {
  92553. var internalTexture = _this._blurTexture1.getInternalTexture();
  92554. if (internalTexture) {
  92555. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92556. internalTexture = _this._blurTexture2.getInternalTexture();
  92557. if (internalTexture) {
  92558. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92559. }
  92560. }
  92561. });
  92562. // Prevent autoClear.
  92563. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92564. };
  92565. /**
  92566. * Checks for the readiness of the element composing the layer.
  92567. * @param subMesh the mesh to check for
  92568. * @param useInstances specify wether or not to use instances to render the mesh
  92569. * @param emissiveTexture the associated emissive texture used to generate the glow
  92570. * @return true if ready otherwise, false
  92571. */
  92572. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92573. var material = subMesh.getMaterial();
  92574. var mesh = subMesh.getRenderingMesh();
  92575. if (!material || !mesh) {
  92576. return false;
  92577. }
  92578. var emissiveTexture = material.emissiveTexture;
  92579. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92580. };
  92581. /**
  92582. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92583. */
  92584. GlowLayer.prototype.needStencil = function () {
  92585. return false;
  92586. };
  92587. /**
  92588. * Implementation specific of rendering the generating effect on the main canvas.
  92589. * @param effect The effect used to render through
  92590. */
  92591. GlowLayer.prototype._internalRender = function (effect) {
  92592. // Texture
  92593. effect.setTexture("textureSampler", this._blurTexture1);
  92594. effect.setTexture("textureSampler2", this._blurTexture2);
  92595. effect.setFloat("offset", this._intensity);
  92596. // Cache
  92597. var engine = this._engine;
  92598. var previousStencilBuffer = engine.getStencilBuffer();
  92599. // Draw order
  92600. engine.setStencilBuffer(false);
  92601. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92602. // Draw order
  92603. engine.setStencilBuffer(previousStencilBuffer);
  92604. };
  92605. /**
  92606. * Sets the required values for both the emissive texture and and the main color.
  92607. */
  92608. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92609. var textureLevel = 1.0;
  92610. if (this.customEmissiveTextureSelector) {
  92611. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92612. }
  92613. else {
  92614. if (material) {
  92615. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92616. if (this._emissiveTextureAndColor.texture) {
  92617. textureLevel = this._emissiveTextureAndColor.texture.level;
  92618. }
  92619. }
  92620. else {
  92621. this._emissiveTextureAndColor.texture = null;
  92622. }
  92623. }
  92624. if (this.customEmissiveColorSelector) {
  92625. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92626. }
  92627. else {
  92628. if (material.emissiveColor) {
  92629. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92630. }
  92631. else {
  92632. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92633. }
  92634. }
  92635. };
  92636. /**
  92637. * Returns true if the mesh should render, otherwise false.
  92638. * @param mesh The mesh to render
  92639. * @returns true if it should render otherwise false
  92640. */
  92641. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92642. return this.hasMesh(mesh);
  92643. };
  92644. /**
  92645. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92646. * @param mesh The mesh to exclude from the glow layer
  92647. */
  92648. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92649. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92650. this._excludedMeshes.push(mesh.uniqueId);
  92651. }
  92652. };
  92653. /**
  92654. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92655. * @param mesh The mesh to remove
  92656. */
  92657. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92658. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92659. if (index !== -1) {
  92660. this._excludedMeshes.splice(index, 1);
  92661. }
  92662. };
  92663. /**
  92664. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92665. * @param mesh The mesh to include in the glow layer
  92666. */
  92667. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92668. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92669. this._includedOnlyMeshes.push(mesh.uniqueId);
  92670. }
  92671. };
  92672. /**
  92673. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92674. * @param mesh The mesh to remove
  92675. */
  92676. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92677. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92678. if (index !== -1) {
  92679. this._includedOnlyMeshes.splice(index, 1);
  92680. }
  92681. };
  92682. /**
  92683. * Determine if a given mesh will be used in the glow layer
  92684. * @param mesh The mesh to test
  92685. * @returns true if the mesh will be highlighted by the current glow layer
  92686. */
  92687. GlowLayer.prototype.hasMesh = function (mesh) {
  92688. // Included Mesh
  92689. if (this._includedOnlyMeshes.length) {
  92690. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92691. }
  92692. ;
  92693. // Excluded Mesh
  92694. if (this._excludedMeshes.length) {
  92695. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92696. }
  92697. ;
  92698. return true;
  92699. };
  92700. /**
  92701. * Free any resources and references associated to a mesh.
  92702. * Internal use
  92703. * @param mesh The mesh to free.
  92704. */
  92705. GlowLayer.prototype._disposeMesh = function (mesh) {
  92706. this.removeIncludedOnlyMesh(mesh);
  92707. this.removeExcludedMesh(mesh);
  92708. };
  92709. /**
  92710. * Gets the class name of the effect layer
  92711. * @returns the string with the class name of the effect layer
  92712. */
  92713. GlowLayer.prototype.getClassName = function () {
  92714. return "GlowLayer";
  92715. };
  92716. /**
  92717. * Serializes this glow layer
  92718. * @returns a serialized glow layer object
  92719. */
  92720. GlowLayer.prototype.serialize = function () {
  92721. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92722. serializationObject.customType = "BABYLON.GlowLayer";
  92723. var index;
  92724. // Included meshes
  92725. serializationObject.includedMeshes = [];
  92726. if (this._includedOnlyMeshes.length) {
  92727. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92728. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92729. if (mesh) {
  92730. serializationObject.includedMeshes.push(mesh.id);
  92731. }
  92732. }
  92733. }
  92734. // Excluded meshes
  92735. serializationObject.excludedMeshes = [];
  92736. if (this._excludedMeshes.length) {
  92737. for (index = 0; index < this._excludedMeshes.length; index++) {
  92738. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92739. if (mesh) {
  92740. serializationObject.excludedMeshes.push(mesh.id);
  92741. }
  92742. }
  92743. }
  92744. return serializationObject;
  92745. };
  92746. /**
  92747. * Creates a Glow Layer from parsed glow layer data
  92748. * @param parsedGlowLayer defines glow layer data
  92749. * @param scene defines the current scene
  92750. * @param rootUrl defines the root URL containing the glow layer information
  92751. * @returns a parsed Glow Layer
  92752. */
  92753. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92754. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92755. var index;
  92756. // Excluded meshes
  92757. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92758. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92759. if (mesh) {
  92760. gl.addExcludedMesh(mesh);
  92761. }
  92762. }
  92763. // Included meshes
  92764. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92765. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92766. if (mesh) {
  92767. gl.addIncludedOnlyMesh(mesh);
  92768. }
  92769. }
  92770. return gl;
  92771. };
  92772. /**
  92773. * Effect Name of the layer.
  92774. */
  92775. GlowLayer.EffectName = "GlowLayer";
  92776. /**
  92777. * The default blur kernel size used for the glow.
  92778. */
  92779. GlowLayer.DefaultBlurKernelSize = 32;
  92780. /**
  92781. * The default texture size ratio used for the glow.
  92782. */
  92783. GlowLayer.DefaultTextureRatio = 0.5;
  92784. __decorate([
  92785. BABYLON.serialize()
  92786. ], GlowLayer.prototype, "blurKernelSize", null);
  92787. __decorate([
  92788. BABYLON.serialize()
  92789. ], GlowLayer.prototype, "intensity", null);
  92790. __decorate([
  92791. BABYLON.serialize("options")
  92792. ], GlowLayer.prototype, "_options", void 0);
  92793. return GlowLayer;
  92794. }(BABYLON.EffectLayer));
  92795. BABYLON.GlowLayer = GlowLayer;
  92796. })(BABYLON || (BABYLON = {}));
  92797. //# sourceMappingURL=babylon.glowLayer.js.map
  92798. var BABYLON;
  92799. (function (BABYLON) {
  92800. /**
  92801. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92802. */
  92803. var AssetTaskState;
  92804. (function (AssetTaskState) {
  92805. /**
  92806. * Initialization
  92807. */
  92808. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92809. /**
  92810. * Running
  92811. */
  92812. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92813. /**
  92814. * Done
  92815. */
  92816. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92817. /**
  92818. * Error
  92819. */
  92820. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92821. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92822. /**
  92823. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92824. */
  92825. var AbstractAssetTask = /** @class */ (function () {
  92826. /**
  92827. * Creates a new {BABYLON.AssetsManager}
  92828. * @param name defines the name of the task
  92829. */
  92830. function AbstractAssetTask(
  92831. /**
  92832. * Task name
  92833. */ name) {
  92834. this.name = name;
  92835. this._isCompleted = false;
  92836. this._taskState = AssetTaskState.INIT;
  92837. }
  92838. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92839. /**
  92840. * Get if the task is completed
  92841. */
  92842. get: function () {
  92843. return this._isCompleted;
  92844. },
  92845. enumerable: true,
  92846. configurable: true
  92847. });
  92848. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92849. /**
  92850. * Gets the current state of the task
  92851. */
  92852. get: function () {
  92853. return this._taskState;
  92854. },
  92855. enumerable: true,
  92856. configurable: true
  92857. });
  92858. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92859. /**
  92860. * Gets the current error object (if task is in error)
  92861. */
  92862. get: function () {
  92863. return this._errorObject;
  92864. },
  92865. enumerable: true,
  92866. configurable: true
  92867. });
  92868. /**
  92869. * Internal only
  92870. * @hidden
  92871. */
  92872. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92873. if (this._errorObject) {
  92874. return;
  92875. }
  92876. this._errorObject = {
  92877. message: message,
  92878. exception: exception
  92879. };
  92880. };
  92881. /**
  92882. * Execute the current task
  92883. * @param scene defines the scene where you want your assets to be loaded
  92884. * @param onSuccess is a callback called when the task is successfully executed
  92885. * @param onError is a callback called if an error occurs
  92886. */
  92887. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92888. var _this = this;
  92889. this._taskState = AssetTaskState.RUNNING;
  92890. this.runTask(scene, function () {
  92891. _this.onDoneCallback(onSuccess, onError);
  92892. }, function (msg, exception) {
  92893. _this.onErrorCallback(onError, msg, exception);
  92894. });
  92895. };
  92896. /**
  92897. * Execute the current task
  92898. * @param scene defines the scene where you want your assets to be loaded
  92899. * @param onSuccess is a callback called when the task is successfully executed
  92900. * @param onError is a callback called if an error occurs
  92901. */
  92902. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92903. throw new Error("runTask is not implemented");
  92904. };
  92905. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92906. this._taskState = AssetTaskState.ERROR;
  92907. this._errorObject = {
  92908. message: message,
  92909. exception: exception
  92910. };
  92911. if (this.onError) {
  92912. this.onError(this, message, exception);
  92913. }
  92914. onError();
  92915. };
  92916. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92917. try {
  92918. this._taskState = AssetTaskState.DONE;
  92919. this._isCompleted = true;
  92920. if (this.onSuccess) {
  92921. this.onSuccess(this);
  92922. }
  92923. onSuccess();
  92924. }
  92925. catch (e) {
  92926. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92927. }
  92928. };
  92929. return AbstractAssetTask;
  92930. }());
  92931. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92932. /**
  92933. * Class used to share progress information about assets loading
  92934. */
  92935. var AssetsProgressEvent = /** @class */ (function () {
  92936. /**
  92937. * Creates a {BABYLON.AssetsProgressEvent}
  92938. * @param remainingCount defines the number of remaining tasks to process
  92939. * @param totalCount defines the total number of tasks
  92940. * @param task defines the task that was just processed
  92941. */
  92942. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92943. this.remainingCount = remainingCount;
  92944. this.totalCount = totalCount;
  92945. this.task = task;
  92946. }
  92947. return AssetsProgressEvent;
  92948. }());
  92949. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92950. /**
  92951. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92952. */
  92953. var MeshAssetTask = /** @class */ (function (_super) {
  92954. __extends(MeshAssetTask, _super);
  92955. /**
  92956. * Creates a new {BABYLON.MeshAssetTask}
  92957. * @param name defines the name of the task
  92958. * @param meshesNames defines the list of mesh's names you want to load
  92959. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92960. * @param sceneFilename defines the filename of the scene to load from
  92961. */
  92962. function MeshAssetTask(
  92963. /**
  92964. * Defines the name of the task
  92965. */
  92966. name,
  92967. /**
  92968. * Defines the list of mesh's names you want to load
  92969. */
  92970. meshesNames,
  92971. /**
  92972. * Defines the root url to use as a base to load your meshes and associated resources
  92973. */
  92974. rootUrl,
  92975. /**
  92976. * Defines the filename of the scene to load from
  92977. */
  92978. sceneFilename) {
  92979. var _this = _super.call(this, name) || this;
  92980. _this.name = name;
  92981. _this.meshesNames = meshesNames;
  92982. _this.rootUrl = rootUrl;
  92983. _this.sceneFilename = sceneFilename;
  92984. return _this;
  92985. }
  92986. /**
  92987. * Execute the current task
  92988. * @param scene defines the scene where you want your assets to be loaded
  92989. * @param onSuccess is a callback called when the task is successfully executed
  92990. * @param onError is a callback called if an error occurs
  92991. */
  92992. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92993. var _this = this;
  92994. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92995. _this.loadedMeshes = meshes;
  92996. _this.loadedParticleSystems = particleSystems;
  92997. _this.loadedSkeletons = skeletons;
  92998. onSuccess();
  92999. }, null, function (scene, message, exception) {
  93000. onError(message, exception);
  93001. });
  93002. };
  93003. return MeshAssetTask;
  93004. }(AbstractAssetTask));
  93005. BABYLON.MeshAssetTask = MeshAssetTask;
  93006. /**
  93007. * Define a task used by {BABYLON.AssetsManager} to load text content
  93008. */
  93009. var TextFileAssetTask = /** @class */ (function (_super) {
  93010. __extends(TextFileAssetTask, _super);
  93011. /**
  93012. * Creates a new TextFileAssetTask object
  93013. * @param name defines the name of the task
  93014. * @param url defines the location of the file to load
  93015. */
  93016. function TextFileAssetTask(
  93017. /**
  93018. * Defines the name of the task
  93019. */
  93020. name,
  93021. /**
  93022. * Defines the location of the file to load
  93023. */
  93024. url) {
  93025. var _this = _super.call(this, name) || this;
  93026. _this.name = name;
  93027. _this.url = url;
  93028. return _this;
  93029. }
  93030. /**
  93031. * Execute the current task
  93032. * @param scene defines the scene where you want your assets to be loaded
  93033. * @param onSuccess is a callback called when the task is successfully executed
  93034. * @param onError is a callback called if an error occurs
  93035. */
  93036. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93037. var _this = this;
  93038. scene._loadFile(this.url, function (data) {
  93039. _this.text = data;
  93040. onSuccess();
  93041. }, undefined, false, false, function (request, exception) {
  93042. if (request) {
  93043. onError(request.status + " " + request.statusText, exception);
  93044. }
  93045. });
  93046. };
  93047. return TextFileAssetTask;
  93048. }(AbstractAssetTask));
  93049. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93050. /**
  93051. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93052. */
  93053. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93054. __extends(BinaryFileAssetTask, _super);
  93055. /**
  93056. * Creates a new BinaryFileAssetTask object
  93057. * @param name defines the name of the new task
  93058. * @param url defines the location of the file to load
  93059. */
  93060. function BinaryFileAssetTask(
  93061. /**
  93062. * Defines the name of the task
  93063. */
  93064. name,
  93065. /**
  93066. * Defines the location of the file to load
  93067. */
  93068. url) {
  93069. var _this = _super.call(this, name) || this;
  93070. _this.name = name;
  93071. _this.url = url;
  93072. return _this;
  93073. }
  93074. /**
  93075. * Execute the current task
  93076. * @param scene defines the scene where you want your assets to be loaded
  93077. * @param onSuccess is a callback called when the task is successfully executed
  93078. * @param onError is a callback called if an error occurs
  93079. */
  93080. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93081. var _this = this;
  93082. scene._loadFile(this.url, function (data) {
  93083. _this.data = data;
  93084. onSuccess();
  93085. }, undefined, true, true, function (request, exception) {
  93086. if (request) {
  93087. onError(request.status + " " + request.statusText, exception);
  93088. }
  93089. });
  93090. };
  93091. return BinaryFileAssetTask;
  93092. }(AbstractAssetTask));
  93093. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93094. /**
  93095. * Define a task used by {BABYLON.AssetsManager} to load images
  93096. */
  93097. var ImageAssetTask = /** @class */ (function (_super) {
  93098. __extends(ImageAssetTask, _super);
  93099. /**
  93100. * Creates a new ImageAssetTask
  93101. * @param name defines the name of the task
  93102. * @param url defines the location of the image to load
  93103. */
  93104. function ImageAssetTask(
  93105. /**
  93106. * Defines the name of the task
  93107. */
  93108. name,
  93109. /**
  93110. * Defines the location of the image to load
  93111. */
  93112. url) {
  93113. var _this = _super.call(this, name) || this;
  93114. _this.name = name;
  93115. _this.url = url;
  93116. return _this;
  93117. }
  93118. /**
  93119. * Execute the current task
  93120. * @param scene defines the scene where you want your assets to be loaded
  93121. * @param onSuccess is a callback called when the task is successfully executed
  93122. * @param onError is a callback called if an error occurs
  93123. */
  93124. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93125. var _this = this;
  93126. var img = new Image();
  93127. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93128. img.onload = function () {
  93129. _this.image = img;
  93130. onSuccess();
  93131. };
  93132. img.onerror = function (err) {
  93133. onError("Error loading image", err);
  93134. };
  93135. img.src = this.url;
  93136. };
  93137. return ImageAssetTask;
  93138. }(AbstractAssetTask));
  93139. BABYLON.ImageAssetTask = ImageAssetTask;
  93140. /**
  93141. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93142. */
  93143. var TextureAssetTask = /** @class */ (function (_super) {
  93144. __extends(TextureAssetTask, _super);
  93145. /**
  93146. * Creates a new TextureAssetTask object
  93147. * @param name defines the name of the task
  93148. * @param url defines the location of the file to load
  93149. * @param noMipmap defines if mipmap should not be generated (default is false)
  93150. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93151. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93152. */
  93153. function TextureAssetTask(
  93154. /**
  93155. * Defines the name of the task
  93156. */
  93157. name,
  93158. /**
  93159. * Defines the location of the file to load
  93160. */
  93161. url,
  93162. /**
  93163. * Defines if mipmap should not be generated (default is false)
  93164. */
  93165. noMipmap,
  93166. /**
  93167. * Defines if texture must be inverted on Y axis (default is false)
  93168. */
  93169. invertY,
  93170. /**
  93171. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93172. */
  93173. samplingMode) {
  93174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93175. var _this = _super.call(this, name) || this;
  93176. _this.name = name;
  93177. _this.url = url;
  93178. _this.noMipmap = noMipmap;
  93179. _this.invertY = invertY;
  93180. _this.samplingMode = samplingMode;
  93181. return _this;
  93182. }
  93183. /**
  93184. * Execute the current task
  93185. * @param scene defines the scene where you want your assets to be loaded
  93186. * @param onSuccess is a callback called when the task is successfully executed
  93187. * @param onError is a callback called if an error occurs
  93188. */
  93189. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93190. var onload = function () {
  93191. onSuccess();
  93192. };
  93193. var onerror = function (message, exception) {
  93194. onError(message, exception);
  93195. };
  93196. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93197. };
  93198. return TextureAssetTask;
  93199. }(AbstractAssetTask));
  93200. BABYLON.TextureAssetTask = TextureAssetTask;
  93201. /**
  93202. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93203. */
  93204. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93205. __extends(CubeTextureAssetTask, _super);
  93206. /**
  93207. * Creates a new CubeTextureAssetTask
  93208. * @param name defines the name of the task
  93209. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93210. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93211. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93212. * @param files defines the explicit list of files (undefined by default)
  93213. */
  93214. function CubeTextureAssetTask(
  93215. /**
  93216. * Defines the name of the task
  93217. */
  93218. name,
  93219. /**
  93220. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93221. */
  93222. url,
  93223. /**
  93224. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93225. */
  93226. extensions,
  93227. /**
  93228. * Defines if mipmaps should not be generated (default is false)
  93229. */
  93230. noMipmap,
  93231. /**
  93232. * Defines the explicit list of files (undefined by default)
  93233. */
  93234. files) {
  93235. var _this = _super.call(this, name) || this;
  93236. _this.name = name;
  93237. _this.url = url;
  93238. _this.extensions = extensions;
  93239. _this.noMipmap = noMipmap;
  93240. _this.files = files;
  93241. return _this;
  93242. }
  93243. /**
  93244. * Execute the current task
  93245. * @param scene defines the scene where you want your assets to be loaded
  93246. * @param onSuccess is a callback called when the task is successfully executed
  93247. * @param onError is a callback called if an error occurs
  93248. */
  93249. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93250. var onload = function () {
  93251. onSuccess();
  93252. };
  93253. var onerror = function (message, exception) {
  93254. onError(message, exception);
  93255. };
  93256. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93257. };
  93258. return CubeTextureAssetTask;
  93259. }(AbstractAssetTask));
  93260. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93261. /**
  93262. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93263. */
  93264. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93265. __extends(HDRCubeTextureAssetTask, _super);
  93266. /**
  93267. * Creates a new HDRCubeTextureAssetTask object
  93268. * @param name defines the name of the task
  93269. * @param url defines the location of the file to load
  93270. * @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.
  93271. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93272. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93273. * @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)
  93274. * @param reserved Internal use only
  93275. */
  93276. function HDRCubeTextureAssetTask(
  93277. /**
  93278. * Defines the name of the task
  93279. */
  93280. name,
  93281. /**
  93282. * Defines the location of the file to load
  93283. */
  93284. url,
  93285. /**
  93286. * Defines the desired size (the more it increases the longer the generation will be)
  93287. */
  93288. size,
  93289. /**
  93290. * Defines if mipmaps should not be generated (default is false)
  93291. */
  93292. noMipmap,
  93293. /**
  93294. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93295. */
  93296. generateHarmonics,
  93297. /**
  93298. * 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)
  93299. */
  93300. gammaSpace,
  93301. /**
  93302. * Internal Use Only
  93303. */
  93304. reserved) {
  93305. if (noMipmap === void 0) { noMipmap = false; }
  93306. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93307. if (gammaSpace === void 0) { gammaSpace = false; }
  93308. if (reserved === void 0) { reserved = false; }
  93309. var _this = _super.call(this, name) || this;
  93310. _this.name = name;
  93311. _this.url = url;
  93312. _this.size = size;
  93313. _this.noMipmap = noMipmap;
  93314. _this.generateHarmonics = generateHarmonics;
  93315. _this.gammaSpace = gammaSpace;
  93316. _this.reserved = reserved;
  93317. return _this;
  93318. }
  93319. /**
  93320. * Execute the current task
  93321. * @param scene defines the scene where you want your assets to be loaded
  93322. * @param onSuccess is a callback called when the task is successfully executed
  93323. * @param onError is a callback called if an error occurs
  93324. */
  93325. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93326. var onload = function () {
  93327. onSuccess();
  93328. };
  93329. var onerror = function (message, exception) {
  93330. onError(message, exception);
  93331. };
  93332. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93333. };
  93334. return HDRCubeTextureAssetTask;
  93335. }(AbstractAssetTask));
  93336. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93337. /**
  93338. * This class can be used to easily import assets into a scene
  93339. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93340. */
  93341. var AssetsManager = /** @class */ (function () {
  93342. /**
  93343. * Creates a new AssetsManager
  93344. * @param scene defines the scene to work on
  93345. */
  93346. function AssetsManager(scene) {
  93347. this._isLoading = false;
  93348. this._tasks = new Array();
  93349. this._waitingTasksCount = 0;
  93350. this._totalTasksCount = 0;
  93351. /**
  93352. * Observable called when all tasks are processed
  93353. */
  93354. this.onTaskSuccessObservable = new BABYLON.Observable();
  93355. /**
  93356. * Observable called when a task had an error
  93357. */
  93358. this.onTaskErrorObservable = new BABYLON.Observable();
  93359. /**
  93360. * Observable called when a task is successful
  93361. */
  93362. this.onTasksDoneObservable = new BABYLON.Observable();
  93363. /**
  93364. * Observable called when a task is done (whatever the result is)
  93365. */
  93366. this.onProgressObservable = new BABYLON.Observable();
  93367. /**
  93368. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93369. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93370. */
  93371. this.useDefaultLoadingScreen = true;
  93372. this._scene = scene;
  93373. }
  93374. /**
  93375. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93376. * @param taskName defines the name of the new task
  93377. * @param meshesNames defines the name of meshes to load
  93378. * @param rootUrl defines the root url to use to locate files
  93379. * @param sceneFilename defines the filename of the scene file
  93380. * @returns a new {BABYLON.MeshAssetTask} object
  93381. */
  93382. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93383. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93384. this._tasks.push(task);
  93385. return task;
  93386. };
  93387. /**
  93388. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93389. * @param taskName defines the name of the new task
  93390. * @param url defines the url of the file to load
  93391. * @returns a new {BABYLON.TextFileAssetTask} object
  93392. */
  93393. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93394. var task = new TextFileAssetTask(taskName, url);
  93395. this._tasks.push(task);
  93396. return task;
  93397. };
  93398. /**
  93399. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93400. * @param taskName defines the name of the new task
  93401. * @param url defines the url of the file to load
  93402. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93403. */
  93404. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93405. var task = new BinaryFileAssetTask(taskName, url);
  93406. this._tasks.push(task);
  93407. return task;
  93408. };
  93409. /**
  93410. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93411. * @param taskName defines the name of the new task
  93412. * @param url defines the url of the file to load
  93413. * @returns a new {BABYLON.ImageAssetTask} object
  93414. */
  93415. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93416. var task = new ImageAssetTask(taskName, url);
  93417. this._tasks.push(task);
  93418. return task;
  93419. };
  93420. /**
  93421. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93422. * @param taskName defines the name of the new task
  93423. * @param url defines the url of the file to load
  93424. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93425. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93426. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93427. * @returns a new {BABYLON.TextureAssetTask} object
  93428. */
  93429. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93431. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93432. this._tasks.push(task);
  93433. return task;
  93434. };
  93435. /**
  93436. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93437. * @param taskName defines the name of the new task
  93438. * @param url defines the url of the file to load
  93439. * @param extensions defines the extension to use to load the cube map (can be null)
  93440. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93441. * @param files defines the list of files to load (can be null)
  93442. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93443. */
  93444. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93445. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93446. this._tasks.push(task);
  93447. return task;
  93448. };
  93449. /**
  93450. *
  93451. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93452. * @param taskName defines the name of the new task
  93453. * @param url defines the url of the file to load
  93454. * @param size defines the size you want for the cubemap (can be null)
  93455. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93456. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93457. * @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)
  93458. * @param reserved Internal use only
  93459. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93460. */
  93461. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93462. if (noMipmap === void 0) { noMipmap = false; }
  93463. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93464. if (gammaSpace === void 0) { gammaSpace = false; }
  93465. if (reserved === void 0) { reserved = false; }
  93466. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93467. this._tasks.push(task);
  93468. return task;
  93469. };
  93470. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93471. var _this = this;
  93472. this._waitingTasksCount--;
  93473. try {
  93474. if (task.taskState === AssetTaskState.DONE) {
  93475. // Let's remove successfull tasks
  93476. BABYLON.Tools.SetImmediate(function () {
  93477. var index = _this._tasks.indexOf(task);
  93478. if (index > -1) {
  93479. _this._tasks.splice(index, 1);
  93480. }
  93481. });
  93482. }
  93483. if (this.onProgress) {
  93484. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93485. }
  93486. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93487. }
  93488. catch (e) {
  93489. BABYLON.Tools.Error("Error running progress callbacks.");
  93490. console.log(e);
  93491. }
  93492. if (this._waitingTasksCount === 0) {
  93493. try {
  93494. if (this.onFinish) {
  93495. this.onFinish(this._tasks);
  93496. }
  93497. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93498. }
  93499. catch (e) {
  93500. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93501. console.log(e);
  93502. }
  93503. this._isLoading = false;
  93504. this._scene.getEngine().hideLoadingUI();
  93505. }
  93506. };
  93507. AssetsManager.prototype._runTask = function (task) {
  93508. var _this = this;
  93509. var done = function () {
  93510. try {
  93511. if (_this.onTaskSuccess) {
  93512. _this.onTaskSuccess(task);
  93513. }
  93514. _this.onTaskSuccessObservable.notifyObservers(task);
  93515. _this._decreaseWaitingTasksCount(task);
  93516. }
  93517. catch (e) {
  93518. error("Error executing task success callbacks", e);
  93519. }
  93520. };
  93521. var error = function (message, exception) {
  93522. task._setErrorObject(message, exception);
  93523. if (_this.onTaskError) {
  93524. _this.onTaskError(task);
  93525. }
  93526. _this.onTaskErrorObservable.notifyObservers(task);
  93527. _this._decreaseWaitingTasksCount(task);
  93528. };
  93529. task.run(this._scene, done, error);
  93530. };
  93531. /**
  93532. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93533. * @return the current instance of the {BABYLON.AssetsManager}
  93534. */
  93535. AssetsManager.prototype.reset = function () {
  93536. this._isLoading = false;
  93537. this._tasks = new Array();
  93538. return this;
  93539. };
  93540. /**
  93541. * Start the loading process
  93542. * @return the current instance of the {BABYLON.AssetsManager}
  93543. */
  93544. AssetsManager.prototype.load = function () {
  93545. if (this._isLoading) {
  93546. return this;
  93547. }
  93548. this._isLoading = true;
  93549. this._waitingTasksCount = this._tasks.length;
  93550. this._totalTasksCount = this._tasks.length;
  93551. if (this._waitingTasksCount === 0) {
  93552. this._isLoading = false;
  93553. if (this.onFinish) {
  93554. this.onFinish(this._tasks);
  93555. }
  93556. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93557. return this;
  93558. }
  93559. if (this.useDefaultLoadingScreen) {
  93560. this._scene.getEngine().displayLoadingUI();
  93561. }
  93562. for (var index = 0; index < this._tasks.length; index++) {
  93563. var task = this._tasks[index];
  93564. this._runTask(task);
  93565. }
  93566. return this;
  93567. };
  93568. return AssetsManager;
  93569. }());
  93570. BABYLON.AssetsManager = AssetsManager;
  93571. })(BABYLON || (BABYLON = {}));
  93572. //# sourceMappingURL=babylon.assetsManager.js.map
  93573. var BABYLON;
  93574. (function (BABYLON) {
  93575. var serializedGeometries = [];
  93576. var serializeGeometry = function (geometry, serializationGeometries) {
  93577. if (serializedGeometries[geometry.id]) {
  93578. return;
  93579. }
  93580. if (geometry.doNotSerialize) {
  93581. return;
  93582. }
  93583. if (geometry instanceof BABYLON.BoxGeometry) {
  93584. serializationGeometries.boxes.push(geometry.serialize());
  93585. }
  93586. else if (geometry instanceof BABYLON.SphereGeometry) {
  93587. serializationGeometries.spheres.push(geometry.serialize());
  93588. }
  93589. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93590. serializationGeometries.cylinders.push(geometry.serialize());
  93591. }
  93592. else if (geometry instanceof BABYLON.TorusGeometry) {
  93593. serializationGeometries.toruses.push(geometry.serialize());
  93594. }
  93595. else if (geometry instanceof BABYLON.GroundGeometry) {
  93596. serializationGeometries.grounds.push(geometry.serialize());
  93597. }
  93598. else if (geometry instanceof BABYLON.Plane) {
  93599. serializationGeometries.planes.push(geometry.serialize());
  93600. }
  93601. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93602. serializationGeometries.torusKnots.push(geometry.serialize());
  93603. }
  93604. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93605. throw new Error("Unknown primitive type");
  93606. }
  93607. else {
  93608. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93609. }
  93610. serializedGeometries[geometry.id] = true;
  93611. };
  93612. var serializeMesh = function (mesh, serializationScene) {
  93613. var serializationObject = {};
  93614. // Geometry
  93615. var geometry = mesh._geometry;
  93616. if (geometry) {
  93617. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93618. // 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
  93619. serializeGeometry(geometry, serializationScene.geometries);
  93620. }
  93621. }
  93622. // Custom
  93623. if (mesh.serialize) {
  93624. mesh.serialize(serializationObject);
  93625. }
  93626. return serializationObject;
  93627. };
  93628. var finalizeSingleMesh = function (mesh, serializationObject) {
  93629. //only works if the mesh is already loaded
  93630. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93631. //serialize material
  93632. if (mesh.material) {
  93633. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93634. serializationObject.materials = serializationObject.materials || [];
  93635. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93636. serializationObject.materials.push(mesh.material.serialize());
  93637. }
  93638. }
  93639. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93640. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93641. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93642. serializationObject.multiMaterials.push(mesh.material.serialize());
  93643. }
  93644. }
  93645. }
  93646. //serialize geometry
  93647. var geometry = mesh._geometry;
  93648. if (geometry) {
  93649. if (!serializationObject.geometries) {
  93650. serializationObject.geometries = {};
  93651. serializationObject.geometries.boxes = [];
  93652. serializationObject.geometries.spheres = [];
  93653. serializationObject.geometries.cylinders = [];
  93654. serializationObject.geometries.toruses = [];
  93655. serializationObject.geometries.grounds = [];
  93656. serializationObject.geometries.planes = [];
  93657. serializationObject.geometries.torusKnots = [];
  93658. serializationObject.geometries.vertexData = [];
  93659. }
  93660. serializeGeometry(geometry, serializationObject.geometries);
  93661. }
  93662. // Skeletons
  93663. if (mesh.skeleton) {
  93664. serializationObject.skeletons = serializationObject.skeletons || [];
  93665. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93666. }
  93667. //serialize the actual mesh
  93668. serializationObject.meshes = serializationObject.meshes || [];
  93669. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93670. }
  93671. };
  93672. var SceneSerializer = /** @class */ (function () {
  93673. function SceneSerializer() {
  93674. }
  93675. SceneSerializer.ClearCache = function () {
  93676. serializedGeometries = [];
  93677. };
  93678. SceneSerializer.Serialize = function (scene) {
  93679. var serializationObject = {};
  93680. SceneSerializer.ClearCache();
  93681. // Scene
  93682. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93683. serializationObject.autoClear = scene.autoClear;
  93684. serializationObject.clearColor = scene.clearColor.asArray();
  93685. serializationObject.ambientColor = scene.ambientColor.asArray();
  93686. serializationObject.gravity = scene.gravity.asArray();
  93687. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93688. serializationObject.workerCollisions = scene.workerCollisions;
  93689. // Fog
  93690. if (scene.fogMode && scene.fogMode !== 0) {
  93691. serializationObject.fogMode = scene.fogMode;
  93692. serializationObject.fogColor = scene.fogColor.asArray();
  93693. serializationObject.fogStart = scene.fogStart;
  93694. serializationObject.fogEnd = scene.fogEnd;
  93695. serializationObject.fogDensity = scene.fogDensity;
  93696. }
  93697. //Physics
  93698. if (scene.isPhysicsEnabled()) {
  93699. var physicEngine = scene.getPhysicsEngine();
  93700. if (physicEngine) {
  93701. serializationObject.physicsEnabled = true;
  93702. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93703. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93704. }
  93705. }
  93706. // Metadata
  93707. if (scene.metadata) {
  93708. serializationObject.metadata = scene.metadata;
  93709. }
  93710. // Morph targets
  93711. serializationObject.morphTargetManagers = [];
  93712. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93713. var abstractMesh = _a[_i];
  93714. var manager = abstractMesh.morphTargetManager;
  93715. if (manager) {
  93716. serializationObject.morphTargetManagers.push(manager.serialize());
  93717. }
  93718. }
  93719. // Lights
  93720. serializationObject.lights = [];
  93721. var index;
  93722. var light;
  93723. for (index = 0; index < scene.lights.length; index++) {
  93724. light = scene.lights[index];
  93725. if (!light.doNotSerialize) {
  93726. serializationObject.lights.push(light.serialize());
  93727. }
  93728. }
  93729. // Cameras
  93730. serializationObject.cameras = [];
  93731. for (index = 0; index < scene.cameras.length; index++) {
  93732. var camera = scene.cameras[index];
  93733. if (!camera.doNotSerialize) {
  93734. serializationObject.cameras.push(camera.serialize());
  93735. }
  93736. }
  93737. if (scene.activeCamera) {
  93738. serializationObject.activeCameraID = scene.activeCamera.id;
  93739. }
  93740. // Animations
  93741. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93742. // Materials
  93743. serializationObject.materials = [];
  93744. serializationObject.multiMaterials = [];
  93745. var material;
  93746. for (index = 0; index < scene.materials.length; index++) {
  93747. material = scene.materials[index];
  93748. if (!material.doNotSerialize) {
  93749. serializationObject.materials.push(material.serialize());
  93750. }
  93751. }
  93752. // MultiMaterials
  93753. serializationObject.multiMaterials = [];
  93754. for (index = 0; index < scene.multiMaterials.length; index++) {
  93755. var multiMaterial = scene.multiMaterials[index];
  93756. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93757. }
  93758. // Environment texture
  93759. if (scene.environmentTexture) {
  93760. serializationObject.environmentTexture = scene.environmentTexture.name;
  93761. }
  93762. // Skeletons
  93763. serializationObject.skeletons = [];
  93764. for (index = 0; index < scene.skeletons.length; index++) {
  93765. var skeleton = scene.skeletons[index];
  93766. if (!skeleton.doNotSerialize) {
  93767. serializationObject.skeletons.push(skeleton.serialize());
  93768. }
  93769. }
  93770. // Transform nodes
  93771. serializationObject.transformNodes = [];
  93772. for (index = 0; index < scene.transformNodes.length; index++) {
  93773. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93774. }
  93775. // Geometries
  93776. serializationObject.geometries = {};
  93777. serializationObject.geometries.boxes = [];
  93778. serializationObject.geometries.spheres = [];
  93779. serializationObject.geometries.cylinders = [];
  93780. serializationObject.geometries.toruses = [];
  93781. serializationObject.geometries.grounds = [];
  93782. serializationObject.geometries.planes = [];
  93783. serializationObject.geometries.torusKnots = [];
  93784. serializationObject.geometries.vertexData = [];
  93785. serializedGeometries = [];
  93786. var geometries = scene.getGeometries();
  93787. for (index = 0; index < geometries.length; index++) {
  93788. var geometry = geometries[index];
  93789. if (geometry.isReady()) {
  93790. serializeGeometry(geometry, serializationObject.geometries);
  93791. }
  93792. }
  93793. // Meshes
  93794. serializationObject.meshes = [];
  93795. for (index = 0; index < scene.meshes.length; index++) {
  93796. var abstractMesh = scene.meshes[index];
  93797. if (abstractMesh instanceof BABYLON.Mesh) {
  93798. var mesh = abstractMesh;
  93799. if (!mesh.doNotSerialize) {
  93800. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93801. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93802. }
  93803. }
  93804. }
  93805. }
  93806. // Particles Systems
  93807. serializationObject.particleSystems = [];
  93808. for (index = 0; index < scene.particleSystems.length; index++) {
  93809. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93810. }
  93811. // Lens flares
  93812. serializationObject.lensFlareSystems = [];
  93813. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93814. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93815. }
  93816. // Shadows
  93817. serializationObject.shadowGenerators = [];
  93818. for (index = 0; index < scene.lights.length; index++) {
  93819. light = scene.lights[index];
  93820. var shadowGenerator = light.getShadowGenerator();
  93821. if (shadowGenerator) {
  93822. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93823. }
  93824. }
  93825. // Action Manager
  93826. if (scene.actionManager) {
  93827. serializationObject.actions = scene.actionManager.serialize("scene");
  93828. }
  93829. // Audio
  93830. serializationObject.sounds = [];
  93831. for (index = 0; index < scene.soundTracks.length; index++) {
  93832. var soundtrack = scene.soundTracks[index];
  93833. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93834. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93835. }
  93836. }
  93837. // Effect layers
  93838. serializationObject.effectLayers = [];
  93839. for (index = 0; index < scene.effectLayers.length; index++) {
  93840. var layer = scene.effectLayers[index];
  93841. if (layer.serialize) {
  93842. serializationObject.effectLayers.push(layer.serialize());
  93843. }
  93844. }
  93845. return serializationObject;
  93846. };
  93847. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93848. if (withParents === void 0) { withParents = false; }
  93849. if (withChildren === void 0) { withChildren = false; }
  93850. var serializationObject = {};
  93851. SceneSerializer.ClearCache();
  93852. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93853. if (withParents || withChildren) {
  93854. //deliberate for loop! not for each, appended should be processed as well.
  93855. for (var i = 0; i < toSerialize.length; ++i) {
  93856. if (withChildren) {
  93857. toSerialize[i].getDescendants().forEach(function (node) {
  93858. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93859. toSerialize.push(node);
  93860. }
  93861. });
  93862. }
  93863. //make sure the array doesn't contain the object already
  93864. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93865. toSerialize.push(toSerialize[i].parent);
  93866. }
  93867. }
  93868. }
  93869. toSerialize.forEach(function (mesh) {
  93870. finalizeSingleMesh(mesh, serializationObject);
  93871. });
  93872. return serializationObject;
  93873. };
  93874. return SceneSerializer;
  93875. }());
  93876. BABYLON.SceneSerializer = SceneSerializer;
  93877. })(BABYLON || (BABYLON = {}));
  93878. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93879. var BABYLON;
  93880. (function (BABYLON) {
  93881. var ReflectionProbe = /** @class */ (function () {
  93882. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93883. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93884. var _this = this;
  93885. this.name = name;
  93886. this._viewMatrix = BABYLON.Matrix.Identity();
  93887. this._target = BABYLON.Vector3.Zero();
  93888. this._add = BABYLON.Vector3.Zero();
  93889. this._invertYAxis = false;
  93890. this.position = BABYLON.Vector3.Zero();
  93891. this._scene = scene;
  93892. this._scene.reflectionProbes.push(this);
  93893. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93894. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93895. switch (faceIndex) {
  93896. case 0:
  93897. _this._add.copyFromFloats(1, 0, 0);
  93898. break;
  93899. case 1:
  93900. _this._add.copyFromFloats(-1, 0, 0);
  93901. break;
  93902. case 2:
  93903. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93904. break;
  93905. case 3:
  93906. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93907. break;
  93908. case 4:
  93909. _this._add.copyFromFloats(0, 0, 1);
  93910. break;
  93911. case 5:
  93912. _this._add.copyFromFloats(0, 0, -1);
  93913. break;
  93914. }
  93915. if (_this._attachedMesh) {
  93916. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93917. }
  93918. _this.position.addToRef(_this._add, _this._target);
  93919. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93920. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93921. scene._forcedViewPosition = _this.position;
  93922. });
  93923. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93924. scene._forcedViewPosition = null;
  93925. scene.updateTransformMatrix(true);
  93926. });
  93927. if (scene.activeCamera) {
  93928. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93929. }
  93930. }
  93931. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93932. get: function () {
  93933. return this._renderTargetTexture.samples;
  93934. },
  93935. set: function (value) {
  93936. this._renderTargetTexture.samples = value;
  93937. },
  93938. enumerable: true,
  93939. configurable: true
  93940. });
  93941. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93942. get: function () {
  93943. return this._renderTargetTexture.refreshRate;
  93944. },
  93945. set: function (value) {
  93946. this._renderTargetTexture.refreshRate = value;
  93947. },
  93948. enumerable: true,
  93949. configurable: true
  93950. });
  93951. ReflectionProbe.prototype.getScene = function () {
  93952. return this._scene;
  93953. };
  93954. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93955. get: function () {
  93956. return this._renderTargetTexture;
  93957. },
  93958. enumerable: true,
  93959. configurable: true
  93960. });
  93961. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93962. get: function () {
  93963. return this._renderTargetTexture.renderList;
  93964. },
  93965. enumerable: true,
  93966. configurable: true
  93967. });
  93968. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93969. this._attachedMesh = mesh;
  93970. };
  93971. /**
  93972. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93973. *
  93974. * @param renderingGroupId The rendering group id corresponding to its index
  93975. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93976. */
  93977. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93978. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93979. };
  93980. ReflectionProbe.prototype.dispose = function () {
  93981. var index = this._scene.reflectionProbes.indexOf(this);
  93982. if (index !== -1) {
  93983. // Remove from the scene if found
  93984. this._scene.reflectionProbes.splice(index, 1);
  93985. }
  93986. if (this._renderTargetTexture) {
  93987. this._renderTargetTexture.dispose();
  93988. this._renderTargetTexture = null;
  93989. }
  93990. };
  93991. return ReflectionProbe;
  93992. }());
  93993. BABYLON.ReflectionProbe = ReflectionProbe;
  93994. })(BABYLON || (BABYLON = {}));
  93995. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93996. var BABYLON;
  93997. (function (BABYLON) {
  93998. var Layer = /** @class */ (function () {
  93999. function Layer(name, imgUrl, scene, isBackground, color) {
  94000. this.name = name;
  94001. this.scale = new BABYLON.Vector2(1, 1);
  94002. this.offset = new BABYLON.Vector2(0, 0);
  94003. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94004. this.layerMask = 0x0FFFFFFF;
  94005. this._vertexBuffers = {};
  94006. // Events
  94007. /**
  94008. * An event triggered when the layer is disposed.
  94009. */
  94010. this.onDisposeObservable = new BABYLON.Observable();
  94011. /**
  94012. * An event triggered before rendering the scene
  94013. */
  94014. this.onBeforeRenderObservable = new BABYLON.Observable();
  94015. /**
  94016. * An event triggered after rendering the scene
  94017. */
  94018. this.onAfterRenderObservable = new BABYLON.Observable();
  94019. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94020. this.isBackground = isBackground === undefined ? true : isBackground;
  94021. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94022. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94023. this._scene.layers.push(this);
  94024. var engine = this._scene.getEngine();
  94025. // VBO
  94026. var vertices = [];
  94027. vertices.push(1, 1);
  94028. vertices.push(-1, 1);
  94029. vertices.push(-1, -1);
  94030. vertices.push(1, -1);
  94031. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94032. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94033. this._createIndexBuffer();
  94034. // Effects
  94035. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94036. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94037. }
  94038. Object.defineProperty(Layer.prototype, "onDispose", {
  94039. set: function (callback) {
  94040. if (this._onDisposeObserver) {
  94041. this.onDisposeObservable.remove(this._onDisposeObserver);
  94042. }
  94043. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94044. },
  94045. enumerable: true,
  94046. configurable: true
  94047. });
  94048. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94049. set: function (callback) {
  94050. if (this._onBeforeRenderObserver) {
  94051. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94052. }
  94053. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94054. },
  94055. enumerable: true,
  94056. configurable: true
  94057. });
  94058. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94059. set: function (callback) {
  94060. if (this._onAfterRenderObserver) {
  94061. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94062. }
  94063. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94064. },
  94065. enumerable: true,
  94066. configurable: true
  94067. });
  94068. Layer.prototype._createIndexBuffer = function () {
  94069. var engine = this._scene.getEngine();
  94070. // Indices
  94071. var indices = [];
  94072. indices.push(0);
  94073. indices.push(1);
  94074. indices.push(2);
  94075. indices.push(0);
  94076. indices.push(2);
  94077. indices.push(3);
  94078. this._indexBuffer = engine.createIndexBuffer(indices);
  94079. };
  94080. Layer.prototype._rebuild = function () {
  94081. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94082. if (vb) {
  94083. vb._rebuild();
  94084. }
  94085. this._createIndexBuffer();
  94086. };
  94087. Layer.prototype.render = function () {
  94088. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94089. // Check
  94090. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94091. return;
  94092. var engine = this._scene.getEngine();
  94093. this.onBeforeRenderObservable.notifyObservers(this);
  94094. // Render
  94095. engine.enableEffect(currentEffect);
  94096. engine.setState(false);
  94097. // Texture
  94098. currentEffect.setTexture("textureSampler", this.texture);
  94099. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94100. // Color
  94101. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94102. // Scale / offset
  94103. currentEffect.setVector2("offset", this.offset);
  94104. currentEffect.setVector2("scale", this.scale);
  94105. // VBOs
  94106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94107. // Draw order
  94108. if (!this.alphaTest) {
  94109. engine.setAlphaMode(this.alphaBlendingMode);
  94110. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94111. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94112. }
  94113. else {
  94114. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94115. }
  94116. this.onAfterRenderObservable.notifyObservers(this);
  94117. };
  94118. Layer.prototype.dispose = function () {
  94119. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94120. if (vertexBuffer) {
  94121. vertexBuffer.dispose();
  94122. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94123. }
  94124. if (this._indexBuffer) {
  94125. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94126. this._indexBuffer = null;
  94127. }
  94128. if (this.texture) {
  94129. this.texture.dispose();
  94130. this.texture = null;
  94131. }
  94132. // Remove from scene
  94133. var index = this._scene.layers.indexOf(this);
  94134. this._scene.layers.splice(index, 1);
  94135. // Callback
  94136. this.onDisposeObservable.notifyObservers(this);
  94137. this.onDisposeObservable.clear();
  94138. this.onAfterRenderObservable.clear();
  94139. this.onBeforeRenderObservable.clear();
  94140. };
  94141. return Layer;
  94142. }());
  94143. BABYLON.Layer = Layer;
  94144. })(BABYLON || (BABYLON = {}));
  94145. //# sourceMappingURL=babylon.layer.js.map
  94146. var BABYLON;
  94147. (function (BABYLON) {
  94148. var TextureTools = /** @class */ (function () {
  94149. function TextureTools() {
  94150. }
  94151. /**
  94152. * Uses the GPU to create a copy texture rescaled at a given size
  94153. * @param texture Texture to copy from
  94154. * @param width Desired width
  94155. * @param height Desired height
  94156. * @return Generated texture
  94157. */
  94158. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94159. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94160. var scene = texture.getScene();
  94161. var engine = scene.getEngine();
  94162. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94163. rtt.wrapU = texture.wrapU;
  94164. rtt.wrapV = texture.wrapV;
  94165. rtt.uOffset = texture.uOffset;
  94166. rtt.vOffset = texture.vOffset;
  94167. rtt.uScale = texture.uScale;
  94168. rtt.vScale = texture.vScale;
  94169. rtt.uAng = texture.uAng;
  94170. rtt.vAng = texture.vAng;
  94171. rtt.wAng = texture.wAng;
  94172. rtt.coordinatesIndex = texture.coordinatesIndex;
  94173. rtt.level = texture.level;
  94174. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94175. rtt._texture.isReady = false;
  94176. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94177. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94178. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94179. passPostProcess.getEffect().executeWhenCompiled(function () {
  94180. passPostProcess.onApply = function (effect) {
  94181. effect.setTexture("textureSampler", texture);
  94182. };
  94183. var internalTexture = rtt.getInternalTexture();
  94184. if (internalTexture) {
  94185. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94186. engine.unBindFramebuffer(internalTexture);
  94187. rtt.disposeFramebufferObjects();
  94188. passPostProcess.dispose();
  94189. internalTexture.isReady = true;
  94190. }
  94191. });
  94192. return rtt;
  94193. };
  94194. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94195. if (!scene._environmentBRDFTexture) {
  94196. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94197. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94198. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94199. scene._environmentBRDFTexture = texture;
  94200. }
  94201. return scene._environmentBRDFTexture;
  94202. };
  94203. 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=";
  94204. return TextureTools;
  94205. }());
  94206. BABYLON.TextureTools = TextureTools;
  94207. })(BABYLON || (BABYLON = {}));
  94208. //# sourceMappingURL=babylon.textureTools.js.map
  94209. var BABYLON;
  94210. (function (BABYLON) {
  94211. var FramingBehavior = /** @class */ (function () {
  94212. function FramingBehavior() {
  94213. this._mode = FramingBehavior.FitFrustumSidesMode;
  94214. this._radiusScale = 1.0;
  94215. this._positionScale = 0.5;
  94216. this._defaultElevation = 0.3;
  94217. this._elevationReturnTime = 1500;
  94218. this._elevationReturnWaitTime = 1000;
  94219. this._zoomStopsAnimation = false;
  94220. this._framingTime = 1500;
  94221. this._isPointerDown = false;
  94222. this._lastInteractionTime = -Infinity;
  94223. // Framing control
  94224. this._animatables = new Array();
  94225. this._betaIsAnimating = false;
  94226. }
  94227. Object.defineProperty(FramingBehavior.prototype, "name", {
  94228. get: function () {
  94229. return "Framing";
  94230. },
  94231. enumerable: true,
  94232. configurable: true
  94233. });
  94234. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94235. /**
  94236. * Gets current mode used by the behavior.
  94237. */
  94238. get: function () {
  94239. return this._mode;
  94240. },
  94241. /**
  94242. * Sets the current mode used by the behavior
  94243. */
  94244. set: function (mode) {
  94245. this._mode = mode;
  94246. },
  94247. enumerable: true,
  94248. configurable: true
  94249. });
  94250. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94251. /**
  94252. * Gets the scale applied to the radius
  94253. */
  94254. get: function () {
  94255. return this._radiusScale;
  94256. },
  94257. /**
  94258. * Sets the scale applied to the radius (1 by default)
  94259. */
  94260. set: function (radius) {
  94261. this._radiusScale = radius;
  94262. },
  94263. enumerable: true,
  94264. configurable: true
  94265. });
  94266. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94267. /**
  94268. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94269. */
  94270. get: function () {
  94271. return this._positionScale;
  94272. },
  94273. /**
  94274. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94275. */
  94276. set: function (scale) {
  94277. this._positionScale = scale;
  94278. },
  94279. enumerable: true,
  94280. configurable: true
  94281. });
  94282. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94283. /**
  94284. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94285. * behaviour is triggered, in radians.
  94286. */
  94287. get: function () {
  94288. return this._defaultElevation;
  94289. },
  94290. /**
  94291. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94292. * behaviour is triggered, in radians.
  94293. */
  94294. set: function (elevation) {
  94295. this._defaultElevation = elevation;
  94296. },
  94297. enumerable: true,
  94298. configurable: true
  94299. });
  94300. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94301. /**
  94302. * Gets the time (in milliseconds) taken to return to the default beta position.
  94303. * Negative value indicates camera should not return to default.
  94304. */
  94305. get: function () {
  94306. return this._elevationReturnTime;
  94307. },
  94308. /**
  94309. * Sets the time (in milliseconds) taken to return to the default beta position.
  94310. * Negative value indicates camera should not return to default.
  94311. */
  94312. set: function (speed) {
  94313. this._elevationReturnTime = speed;
  94314. },
  94315. enumerable: true,
  94316. configurable: true
  94317. });
  94318. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94319. /**
  94320. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94321. */
  94322. get: function () {
  94323. return this._elevationReturnWaitTime;
  94324. },
  94325. /**
  94326. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94327. */
  94328. set: function (time) {
  94329. this._elevationReturnWaitTime = time;
  94330. },
  94331. enumerable: true,
  94332. configurable: true
  94333. });
  94334. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94335. /**
  94336. * Gets the flag that indicates if user zooming should stop animation.
  94337. */
  94338. get: function () {
  94339. return this._zoomStopsAnimation;
  94340. },
  94341. /**
  94342. * Sets the flag that indicates if user zooming should stop animation.
  94343. */
  94344. set: function (flag) {
  94345. this._zoomStopsAnimation = flag;
  94346. },
  94347. enumerable: true,
  94348. configurable: true
  94349. });
  94350. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94351. /**
  94352. * Gets the transition time when framing the mesh, in milliseconds
  94353. */
  94354. get: function () {
  94355. return this._framingTime;
  94356. },
  94357. /**
  94358. * Sets the transition time when framing the mesh, in milliseconds
  94359. */
  94360. set: function (time) {
  94361. this._framingTime = time;
  94362. },
  94363. enumerable: true,
  94364. configurable: true
  94365. });
  94366. FramingBehavior.prototype.init = function () {
  94367. // Do notihng
  94368. };
  94369. FramingBehavior.prototype.attach = function (camera) {
  94370. var _this = this;
  94371. this._attachedCamera = camera;
  94372. var scene = this._attachedCamera.getScene();
  94373. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94374. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94375. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94376. _this._isPointerDown = true;
  94377. return;
  94378. }
  94379. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94380. _this._isPointerDown = false;
  94381. }
  94382. });
  94383. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94384. if (mesh) {
  94385. _this.zoomOnMesh(mesh);
  94386. }
  94387. });
  94388. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94389. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94390. _this._applyUserInteraction();
  94391. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94392. // back to the default position after a given timeout
  94393. _this._maintainCameraAboveGround();
  94394. });
  94395. };
  94396. FramingBehavior.prototype.detach = function () {
  94397. if (!this._attachedCamera) {
  94398. return;
  94399. }
  94400. var scene = this._attachedCamera.getScene();
  94401. if (this._onPrePointerObservableObserver) {
  94402. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94403. }
  94404. if (this._onAfterCheckInputsObserver) {
  94405. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94406. }
  94407. if (this._onMeshTargetChangedObserver) {
  94408. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94409. }
  94410. this._attachedCamera = null;
  94411. };
  94412. /**
  94413. * Targets the given mesh and updates zoom level accordingly.
  94414. * @param mesh The mesh to target.
  94415. * @param radius Optional. If a cached radius position already exists, overrides default.
  94416. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94417. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94418. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94419. */
  94420. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94421. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94422. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94423. mesh.computeWorldMatrix(true);
  94424. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94425. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94426. };
  94427. /**
  94428. * Targets the given mesh with its children and updates zoom level accordingly.
  94429. * @param mesh The mesh to target.
  94430. * @param radius Optional. If a cached radius position already exists, overrides default.
  94431. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94432. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94433. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94434. */
  94435. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94436. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94437. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94438. mesh.computeWorldMatrix(true);
  94439. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94440. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94441. };
  94442. /**
  94443. * Targets the given meshes with their children and updates zoom level accordingly.
  94444. * @param meshes The mesh to target.
  94445. * @param radius Optional. If a cached radius position already exists, overrides default.
  94446. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94447. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94448. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94449. */
  94450. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94451. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94452. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94453. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94454. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94455. for (var i = 0; i < meshes.length; i++) {
  94456. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94457. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94458. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94459. }
  94460. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94461. };
  94462. /**
  94463. * Targets the given mesh and updates zoom level accordingly.
  94464. * @param mesh The mesh to target.
  94465. * @param radius Optional. If a cached radius position already exists, overrides default.
  94466. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94467. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94468. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94469. */
  94470. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94471. var _this = this;
  94472. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94473. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94474. var zoomTarget;
  94475. if (!this._attachedCamera) {
  94476. return;
  94477. }
  94478. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94479. var bottom = minimumWorld.y;
  94480. var top = maximumWorld.y;
  94481. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94482. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94483. if (focusOnOriginXZ) {
  94484. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94485. }
  94486. else {
  94487. var centerWorld = minimumWorld.add(radiusWorld);
  94488. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94489. }
  94490. if (!this._vectorTransition) {
  94491. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94492. }
  94493. this._betaIsAnimating = true;
  94494. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94495. if (animatable) {
  94496. this._animatables.push(animatable);
  94497. }
  94498. // sets the radius and lower radius bounds
  94499. // Small delta ensures camera is not always at lower zoom limit.
  94500. var radius = 0;
  94501. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94502. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94503. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94504. radius = position;
  94505. }
  94506. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94507. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94508. if (this._attachedCamera.lowerRadiusLimit === null) {
  94509. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94510. }
  94511. }
  94512. // Set sensibilities
  94513. var extend = maximumWorld.subtract(minimumWorld).length();
  94514. this._attachedCamera.panningSensibility = 5000 / extend;
  94515. this._attachedCamera.wheelPrecision = 100 / radius;
  94516. // transition to new radius
  94517. if (!this._radiusTransition) {
  94518. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94519. }
  94520. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94521. _this.stopAllAnimations();
  94522. if (onAnimationEnd) {
  94523. onAnimationEnd();
  94524. }
  94525. if (_this._attachedCamera) {
  94526. _this._attachedCamera.storeState();
  94527. }
  94528. });
  94529. if (animatable) {
  94530. this._animatables.push(animatable);
  94531. }
  94532. };
  94533. /**
  94534. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94535. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94536. * frustum width.
  94537. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94538. * to fully enclose the mesh in the viewing frustum.
  94539. */
  94540. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94541. var size = maximumWorld.subtract(minimumWorld);
  94542. var boxVectorGlobalDiagonal = size.length();
  94543. var frustumSlope = this._getFrustumSlope();
  94544. // Formula for setting distance
  94545. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94546. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94547. // Horizon distance
  94548. var radius = radiusWithoutFraming * this._radiusScale;
  94549. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94550. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94551. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94552. var camera = this._attachedCamera;
  94553. if (!camera) {
  94554. return 0;
  94555. }
  94556. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94557. // Don't exceed the requested limit
  94558. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94559. }
  94560. // Don't exceed the upper radius limit
  94561. if (camera.upperRadiusLimit) {
  94562. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94563. }
  94564. return distance;
  94565. };
  94566. /**
  94567. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94568. * is automatically returned to its default position (expected to be above ground plane).
  94569. */
  94570. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94571. var _this = this;
  94572. if (this._elevationReturnTime < 0) {
  94573. return;
  94574. }
  94575. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94576. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94577. var limitBeta = Math.PI * 0.5;
  94578. // Bring the camera back up if below the ground plane
  94579. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94580. this._betaIsAnimating = true;
  94581. //Transition to new position
  94582. this.stopAllAnimations();
  94583. if (!this._betaTransition) {
  94584. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94585. }
  94586. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94587. _this._clearAnimationLocks();
  94588. _this.stopAllAnimations();
  94589. });
  94590. if (animatabe) {
  94591. this._animatables.push(animatabe);
  94592. }
  94593. }
  94594. };
  94595. /**
  94596. * Returns the frustum slope based on the canvas ratio and camera FOV
  94597. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94598. */
  94599. FramingBehavior.prototype._getFrustumSlope = function () {
  94600. // Calculate the viewport ratio
  94601. // Aspect Ratio is Height/Width.
  94602. var camera = this._attachedCamera;
  94603. if (!camera) {
  94604. return BABYLON.Vector2.Zero();
  94605. }
  94606. var engine = camera.getScene().getEngine();
  94607. var aspectRatio = engine.getAspectRatio(camera);
  94608. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94609. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94610. var frustumSlopeY = Math.tan(camera.fov / 2);
  94611. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94612. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94613. // along the forward vector.
  94614. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94615. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94616. };
  94617. /**
  94618. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94619. */
  94620. FramingBehavior.prototype._clearAnimationLocks = function () {
  94621. this._betaIsAnimating = false;
  94622. };
  94623. /**
  94624. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94625. */
  94626. FramingBehavior.prototype._applyUserInteraction = function () {
  94627. if (this.isUserIsMoving) {
  94628. this._lastInteractionTime = BABYLON.Tools.Now;
  94629. this.stopAllAnimations();
  94630. this._clearAnimationLocks();
  94631. }
  94632. };
  94633. /**
  94634. * Stops and removes all animations that have been applied to the camera
  94635. */
  94636. FramingBehavior.prototype.stopAllAnimations = function () {
  94637. if (this._attachedCamera) {
  94638. this._attachedCamera.animations = [];
  94639. }
  94640. while (this._animatables.length) {
  94641. if (this._animatables[0]) {
  94642. this._animatables[0].onAnimationEnd = null;
  94643. this._animatables[0].stop();
  94644. }
  94645. this._animatables.shift();
  94646. }
  94647. };
  94648. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94649. /**
  94650. * Gets a value indicating if the user is moving the camera
  94651. */
  94652. get: function () {
  94653. if (!this._attachedCamera) {
  94654. return false;
  94655. }
  94656. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94657. this._attachedCamera.inertialBetaOffset !== 0 ||
  94658. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94659. this._attachedCamera.inertialPanningX !== 0 ||
  94660. this._attachedCamera.inertialPanningY !== 0 ||
  94661. this._isPointerDown;
  94662. },
  94663. enumerable: true,
  94664. configurable: true
  94665. });
  94666. /**
  94667. * The easing function used by animations
  94668. */
  94669. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94670. /**
  94671. * The easing mode used by animations
  94672. */
  94673. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94674. // Statics
  94675. /**
  94676. * The camera can move all the way towards the mesh.
  94677. */
  94678. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94679. /**
  94680. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94681. */
  94682. FramingBehavior.FitFrustumSidesMode = 1;
  94683. return FramingBehavior;
  94684. }());
  94685. BABYLON.FramingBehavior = FramingBehavior;
  94686. })(BABYLON || (BABYLON = {}));
  94687. //# sourceMappingURL=babylon.framingBehavior.js.map
  94688. var BABYLON;
  94689. (function (BABYLON) {
  94690. /**
  94691. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94692. */
  94693. var BouncingBehavior = /** @class */ (function () {
  94694. function BouncingBehavior() {
  94695. /**
  94696. * The duration of the animation, in milliseconds
  94697. */
  94698. this.transitionDuration = 450;
  94699. /**
  94700. * Length of the distance animated by the transition when lower radius is reached
  94701. */
  94702. this.lowerRadiusTransitionRange = 2;
  94703. /**
  94704. * Length of the distance animated by the transition when upper radius is reached
  94705. */
  94706. this.upperRadiusTransitionRange = -2;
  94707. this._autoTransitionRange = false;
  94708. // Animations
  94709. this._radiusIsAnimating = false;
  94710. this._radiusBounceTransition = null;
  94711. this._animatables = new Array();
  94712. }
  94713. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94714. get: function () {
  94715. return "Bouncing";
  94716. },
  94717. enumerable: true,
  94718. configurable: true
  94719. });
  94720. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94721. /**
  94722. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94723. */
  94724. get: function () {
  94725. return this._autoTransitionRange;
  94726. },
  94727. /**
  94728. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94729. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94730. */
  94731. set: function (value) {
  94732. var _this = this;
  94733. if (this._autoTransitionRange === value) {
  94734. return;
  94735. }
  94736. this._autoTransitionRange = value;
  94737. var camera = this._attachedCamera;
  94738. if (!camera) {
  94739. return;
  94740. }
  94741. if (value) {
  94742. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94743. if (!mesh) {
  94744. return;
  94745. }
  94746. mesh.computeWorldMatrix(true);
  94747. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94748. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94749. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94750. });
  94751. }
  94752. else if (this._onMeshTargetChangedObserver) {
  94753. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94754. }
  94755. },
  94756. enumerable: true,
  94757. configurable: true
  94758. });
  94759. BouncingBehavior.prototype.init = function () {
  94760. // Do notihng
  94761. };
  94762. BouncingBehavior.prototype.attach = function (camera) {
  94763. var _this = this;
  94764. this._attachedCamera = camera;
  94765. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94766. if (!_this._attachedCamera) {
  94767. return;
  94768. }
  94769. // Add the bounce animation to the lower radius limit
  94770. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94771. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94772. }
  94773. // Add the bounce animation to the upper radius limit
  94774. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94775. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94776. }
  94777. });
  94778. };
  94779. BouncingBehavior.prototype.detach = function () {
  94780. if (!this._attachedCamera) {
  94781. return;
  94782. }
  94783. if (this._onAfterCheckInputsObserver) {
  94784. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94785. }
  94786. if (this._onMeshTargetChangedObserver) {
  94787. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94788. }
  94789. this._attachedCamera = null;
  94790. };
  94791. /**
  94792. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94793. * @param radiusLimit The limit to check against.
  94794. * @return Bool to indicate if at limit.
  94795. */
  94796. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94797. if (!this._attachedCamera) {
  94798. return false;
  94799. }
  94800. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94801. return true;
  94802. }
  94803. return false;
  94804. };
  94805. /**
  94806. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94807. * @param radiusDelta The delta by which to animate to. Can be negative.
  94808. */
  94809. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94810. var _this = this;
  94811. if (!this._attachedCamera) {
  94812. return;
  94813. }
  94814. if (!this._radiusBounceTransition) {
  94815. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94816. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94817. }
  94818. // Prevent zoom until bounce has completed
  94819. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94820. this._attachedCamera.wheelPrecision = Infinity;
  94821. this._attachedCamera.inertialRadiusOffset = 0;
  94822. // Animate to the radius limit
  94823. this.stopAllAnimations();
  94824. this._radiusIsAnimating = true;
  94825. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94826. if (animatable) {
  94827. this._animatables.push(animatable);
  94828. }
  94829. };
  94830. /**
  94831. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94832. */
  94833. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94834. this._radiusIsAnimating = false;
  94835. if (this._attachedCamera) {
  94836. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94837. }
  94838. };
  94839. /**
  94840. * Stops and removes all animations that have been applied to the camera
  94841. */
  94842. BouncingBehavior.prototype.stopAllAnimations = function () {
  94843. if (this._attachedCamera) {
  94844. this._attachedCamera.animations = [];
  94845. }
  94846. while (this._animatables.length) {
  94847. this._animatables[0].onAnimationEnd = null;
  94848. this._animatables[0].stop();
  94849. this._animatables.shift();
  94850. }
  94851. };
  94852. /**
  94853. * The easing function used by animations
  94854. */
  94855. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94856. /**
  94857. * The easing mode used by animations
  94858. */
  94859. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94860. return BouncingBehavior;
  94861. }());
  94862. BABYLON.BouncingBehavior = BouncingBehavior;
  94863. })(BABYLON || (BABYLON = {}));
  94864. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94865. var BABYLON;
  94866. (function (BABYLON) {
  94867. var AutoRotationBehavior = /** @class */ (function () {
  94868. function AutoRotationBehavior() {
  94869. this._zoomStopsAnimation = false;
  94870. this._idleRotationSpeed = 0.05;
  94871. this._idleRotationWaitTime = 2000;
  94872. this._idleRotationSpinupTime = 2000;
  94873. this._isPointerDown = false;
  94874. this._lastFrameTime = null;
  94875. this._lastInteractionTime = -Infinity;
  94876. this._cameraRotationSpeed = 0;
  94877. this._lastFrameRadius = 0;
  94878. }
  94879. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94880. get: function () {
  94881. return "AutoRotation";
  94882. },
  94883. enumerable: true,
  94884. configurable: true
  94885. });
  94886. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94887. /**
  94888. * Gets the flag that indicates if user zooming should stop animation.
  94889. */
  94890. get: function () {
  94891. return this._zoomStopsAnimation;
  94892. },
  94893. /**
  94894. * Sets the flag that indicates if user zooming should stop animation.
  94895. */
  94896. set: function (flag) {
  94897. this._zoomStopsAnimation = flag;
  94898. },
  94899. enumerable: true,
  94900. configurable: true
  94901. });
  94902. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94903. /**
  94904. * Gets the default speed at which the camera rotates around the model.
  94905. */
  94906. get: function () {
  94907. return this._idleRotationSpeed;
  94908. },
  94909. /**
  94910. * Sets the default speed at which the camera rotates around the model.
  94911. */
  94912. set: function (speed) {
  94913. this._idleRotationSpeed = speed;
  94914. },
  94915. enumerable: true,
  94916. configurable: true
  94917. });
  94918. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94919. /**
  94920. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94921. */
  94922. get: function () {
  94923. return this._idleRotationWaitTime;
  94924. },
  94925. /**
  94926. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94927. */
  94928. set: function (time) {
  94929. this._idleRotationWaitTime = time;
  94930. },
  94931. enumerable: true,
  94932. configurable: true
  94933. });
  94934. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94935. /**
  94936. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94937. */
  94938. get: function () {
  94939. return this._idleRotationSpinupTime;
  94940. },
  94941. /**
  94942. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94943. */
  94944. set: function (time) {
  94945. this._idleRotationSpinupTime = time;
  94946. },
  94947. enumerable: true,
  94948. configurable: true
  94949. });
  94950. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94951. /**
  94952. * Gets a value indicating if the camera is currently rotating because of this behavior
  94953. */
  94954. get: function () {
  94955. return Math.abs(this._cameraRotationSpeed) > 0;
  94956. },
  94957. enumerable: true,
  94958. configurable: true
  94959. });
  94960. AutoRotationBehavior.prototype.init = function () {
  94961. // Do notihng
  94962. };
  94963. AutoRotationBehavior.prototype.attach = function (camera) {
  94964. var _this = this;
  94965. this._attachedCamera = camera;
  94966. var scene = this._attachedCamera.getScene();
  94967. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94968. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94969. _this._isPointerDown = true;
  94970. return;
  94971. }
  94972. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94973. _this._isPointerDown = false;
  94974. }
  94975. });
  94976. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94977. var now = BABYLON.Tools.Now;
  94978. var dt = 0;
  94979. if (_this._lastFrameTime != null) {
  94980. dt = now - _this._lastFrameTime;
  94981. }
  94982. _this._lastFrameTime = now;
  94983. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94984. _this._applyUserInteraction();
  94985. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94986. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94987. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94988. // Step camera rotation by rotation speed
  94989. if (_this._attachedCamera) {
  94990. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94991. }
  94992. });
  94993. };
  94994. AutoRotationBehavior.prototype.detach = function () {
  94995. if (!this._attachedCamera) {
  94996. return;
  94997. }
  94998. var scene = this._attachedCamera.getScene();
  94999. if (this._onPrePointerObservableObserver) {
  95000. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95001. }
  95002. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95003. this._attachedCamera = null;
  95004. };
  95005. /**
  95006. * Returns true if user is scrolling.
  95007. * @return true if user is scrolling.
  95008. */
  95009. AutoRotationBehavior.prototype._userIsZooming = function () {
  95010. if (!this._attachedCamera) {
  95011. return false;
  95012. }
  95013. return this._attachedCamera.inertialRadiusOffset !== 0;
  95014. };
  95015. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95016. if (!this._attachedCamera) {
  95017. return false;
  95018. }
  95019. var zoomHasHitLimit = false;
  95020. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95021. zoomHasHitLimit = true;
  95022. }
  95023. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95024. this._lastFrameRadius = this._attachedCamera.radius;
  95025. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95026. };
  95027. /**
  95028. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95029. */
  95030. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95031. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95032. this._lastInteractionTime = BABYLON.Tools.Now;
  95033. }
  95034. };
  95035. // Tools
  95036. AutoRotationBehavior.prototype._userIsMoving = function () {
  95037. if (!this._attachedCamera) {
  95038. return false;
  95039. }
  95040. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95041. this._attachedCamera.inertialBetaOffset !== 0 ||
  95042. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95043. this._attachedCamera.inertialPanningX !== 0 ||
  95044. this._attachedCamera.inertialPanningY !== 0 ||
  95045. this._isPointerDown;
  95046. };
  95047. return AutoRotationBehavior;
  95048. }());
  95049. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95050. })(BABYLON || (BABYLON = {}));
  95051. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95052. var BABYLON;
  95053. (function (BABYLON) {
  95054. var NullEngineOptions = /** @class */ (function () {
  95055. function NullEngineOptions() {
  95056. this.renderWidth = 512;
  95057. this.renderHeight = 256;
  95058. this.textureSize = 512;
  95059. this.deterministicLockstep = false;
  95060. this.lockstepMaxSteps = 4;
  95061. }
  95062. return NullEngineOptions;
  95063. }());
  95064. BABYLON.NullEngineOptions = NullEngineOptions;
  95065. /**
  95066. * The null engine class provides support for headless version of babylon.js.
  95067. * This can be used in server side scenario or for testing purposes
  95068. */
  95069. var NullEngine = /** @class */ (function (_super) {
  95070. __extends(NullEngine, _super);
  95071. function NullEngine(options) {
  95072. if (options === void 0) { options = new NullEngineOptions(); }
  95073. var _this = _super.call(this, null) || this;
  95074. if (options.deterministicLockstep === undefined) {
  95075. options.deterministicLockstep = false;
  95076. }
  95077. if (options.lockstepMaxSteps === undefined) {
  95078. options.lockstepMaxSteps = 4;
  95079. }
  95080. _this._options = options;
  95081. // Init caps
  95082. // We consider we are on a webgl1 capable device
  95083. _this._caps = new BABYLON.EngineCapabilities();
  95084. _this._caps.maxTexturesImageUnits = 16;
  95085. _this._caps.maxVertexTextureImageUnits = 16;
  95086. _this._caps.maxTextureSize = 512;
  95087. _this._caps.maxCubemapTextureSize = 512;
  95088. _this._caps.maxRenderTextureSize = 512;
  95089. _this._caps.maxVertexAttribs = 16;
  95090. _this._caps.maxVaryingVectors = 16;
  95091. _this._caps.maxFragmentUniformVectors = 16;
  95092. _this._caps.maxVertexUniformVectors = 16;
  95093. // Extensions
  95094. _this._caps.standardDerivatives = false;
  95095. _this._caps.astc = null;
  95096. _this._caps.s3tc = null;
  95097. _this._caps.pvrtc = null;
  95098. _this._caps.etc1 = null;
  95099. _this._caps.etc2 = null;
  95100. _this._caps.textureAnisotropicFilterExtension = null;
  95101. _this._caps.maxAnisotropy = 0;
  95102. _this._caps.uintIndices = false;
  95103. _this._caps.fragmentDepthSupported = false;
  95104. _this._caps.highPrecisionShaderSupported = true;
  95105. _this._caps.colorBufferFloat = false;
  95106. _this._caps.textureFloat = false;
  95107. _this._caps.textureFloatLinearFiltering = false;
  95108. _this._caps.textureFloatRender = false;
  95109. _this._caps.textureHalfFloat = false;
  95110. _this._caps.textureHalfFloatLinearFiltering = false;
  95111. _this._caps.textureHalfFloatRender = false;
  95112. _this._caps.textureLOD = false;
  95113. _this._caps.drawBuffersExtension = false;
  95114. _this._caps.depthTextureExtension = false;
  95115. _this._caps.vertexArrayObject = false;
  95116. _this._caps.instancedArrays = false;
  95117. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95118. // Wrappers
  95119. if (typeof URL === "undefined") {
  95120. URL = {
  95121. createObjectURL: function () { },
  95122. revokeObjectURL: function () { }
  95123. };
  95124. }
  95125. if (typeof Blob === "undefined") {
  95126. Blob = function () { };
  95127. }
  95128. return _this;
  95129. }
  95130. NullEngine.prototype.isDeterministicLockStep = function () {
  95131. return this._options.deterministicLockstep;
  95132. };
  95133. NullEngine.prototype.getLockstepMaxSteps = function () {
  95134. return this._options.lockstepMaxSteps;
  95135. };
  95136. NullEngine.prototype.getHardwareScalingLevel = function () {
  95137. return 1.0;
  95138. };
  95139. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95140. return {
  95141. capacity: 0,
  95142. references: 1,
  95143. is32Bits: false
  95144. };
  95145. };
  95146. NullEngine.prototype.createIndexBuffer = function (indices) {
  95147. return {
  95148. capacity: 0,
  95149. references: 1,
  95150. is32Bits: false
  95151. };
  95152. };
  95153. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95154. if (stencil === void 0) { stencil = false; }
  95155. };
  95156. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95157. if (useScreen === void 0) { useScreen = false; }
  95158. if (!useScreen && this._currentRenderTarget) {
  95159. return this._currentRenderTarget.width;
  95160. }
  95161. return this._options.renderWidth;
  95162. };
  95163. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95164. if (useScreen === void 0) { useScreen = false; }
  95165. if (!useScreen && this._currentRenderTarget) {
  95166. return this._currentRenderTarget.height;
  95167. }
  95168. return this._options.renderHeight;
  95169. };
  95170. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95171. this._cachedViewport = viewport;
  95172. };
  95173. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95174. return {
  95175. transformFeedback: null,
  95176. __SPECTOR_rebuildProgram: null
  95177. };
  95178. };
  95179. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95180. return [];
  95181. };
  95182. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95183. return [];
  95184. };
  95185. NullEngine.prototype.bindSamplers = function (effect) {
  95186. this._currentEffect = null;
  95187. };
  95188. NullEngine.prototype.enableEffect = function (effect) {
  95189. this._currentEffect = effect;
  95190. if (effect.onBind) {
  95191. effect.onBind(effect);
  95192. }
  95193. effect.onBindObservable.notifyObservers(effect);
  95194. };
  95195. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95196. if (zOffset === void 0) { zOffset = 0; }
  95197. if (reverseSide === void 0) { reverseSide = false; }
  95198. };
  95199. NullEngine.prototype.setIntArray = function (uniform, array) {
  95200. };
  95201. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95202. };
  95203. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95204. };
  95205. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95206. };
  95207. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95208. };
  95209. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95210. };
  95211. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95212. };
  95213. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95214. };
  95215. NullEngine.prototype.setArray = function (uniform, array) {
  95216. };
  95217. NullEngine.prototype.setArray2 = function (uniform, array) {
  95218. };
  95219. NullEngine.prototype.setArray3 = function (uniform, array) {
  95220. };
  95221. NullEngine.prototype.setArray4 = function (uniform, array) {
  95222. };
  95223. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95224. };
  95225. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95226. };
  95227. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95228. };
  95229. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95230. };
  95231. NullEngine.prototype.setFloat = function (uniform, value) {
  95232. };
  95233. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95234. };
  95235. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95236. };
  95237. NullEngine.prototype.setBool = function (uniform, bool) {
  95238. };
  95239. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95240. };
  95241. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95242. };
  95243. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95244. };
  95245. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95246. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95247. if (this._alphaMode === mode) {
  95248. return;
  95249. }
  95250. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95251. if (!noDepthWriteChange) {
  95252. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95253. }
  95254. this._alphaMode = mode;
  95255. };
  95256. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95257. };
  95258. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95259. if (this.preventCacheWipeBetweenFrames) {
  95260. return;
  95261. }
  95262. this.resetTextureCache();
  95263. this._currentEffect = null;
  95264. if (bruteForce) {
  95265. this._currentProgram = null;
  95266. this._stencilState.reset();
  95267. this._depthCullingState.reset();
  95268. this._alphaState.reset();
  95269. }
  95270. this._cachedVertexBuffers = null;
  95271. this._cachedIndexBuffer = null;
  95272. this._cachedEffectForVertexBuffers = null;
  95273. };
  95274. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95275. };
  95276. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95277. };
  95278. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95279. };
  95280. NullEngine.prototype._createTexture = function () {
  95281. return {};
  95282. };
  95283. NullEngine.prototype._releaseTexture = function (texture) {
  95284. };
  95285. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95287. if (onLoad === void 0) { onLoad = null; }
  95288. if (onError === void 0) { onError = null; }
  95289. if (buffer === void 0) { buffer = null; }
  95290. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95291. var url = String(urlArg);
  95292. texture.url = url;
  95293. texture.generateMipMaps = !noMipmap;
  95294. texture.samplingMode = samplingMode;
  95295. texture.invertY = invertY;
  95296. texture.baseWidth = this._options.textureSize;
  95297. texture.baseHeight = this._options.textureSize;
  95298. texture.width = this._options.textureSize;
  95299. texture.height = this._options.textureSize;
  95300. if (format) {
  95301. texture.format = format;
  95302. }
  95303. texture.isReady = true;
  95304. if (onLoad) {
  95305. onLoad();
  95306. }
  95307. return texture;
  95308. };
  95309. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95310. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95311. if (options !== undefined && typeof options === "object") {
  95312. fullOptions.generateMipMaps = options.generateMipMaps;
  95313. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95314. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95315. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95316. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95317. }
  95318. else {
  95319. fullOptions.generateMipMaps = options;
  95320. fullOptions.generateDepthBuffer = true;
  95321. fullOptions.generateStencilBuffer = false;
  95322. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95323. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95324. }
  95325. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95326. var width = size.width || size;
  95327. var height = size.height || size;
  95328. texture._depthStencilBuffer = {};
  95329. texture._framebuffer = {};
  95330. texture.baseWidth = width;
  95331. texture.baseHeight = height;
  95332. texture.width = width;
  95333. texture.height = height;
  95334. texture.isReady = true;
  95335. texture.samples = 1;
  95336. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95337. texture.samplingMode = fullOptions.samplingMode;
  95338. texture.type = fullOptions.type;
  95339. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95340. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95341. return texture;
  95342. };
  95343. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95344. texture.samplingMode = samplingMode;
  95345. };
  95346. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95347. if (this._currentRenderTarget) {
  95348. this.unBindFramebuffer(this._currentRenderTarget);
  95349. }
  95350. this._currentRenderTarget = texture;
  95351. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95352. if (this._cachedViewport && !forceFullscreenViewport) {
  95353. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95354. }
  95355. };
  95356. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95357. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95358. this._currentRenderTarget = null;
  95359. if (onBeforeUnbind) {
  95360. if (texture._MSAAFramebuffer) {
  95361. this._currentFramebuffer = texture._framebuffer;
  95362. }
  95363. onBeforeUnbind();
  95364. }
  95365. this._currentFramebuffer = null;
  95366. };
  95367. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95368. var vbo = {
  95369. capacity: 1,
  95370. references: 1,
  95371. is32Bits: false
  95372. };
  95373. return vbo;
  95374. };
  95375. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95376. if (offset === void 0) { offset = 0; }
  95377. };
  95378. /**
  95379. * Updates a dynamic vertex buffer.
  95380. * @param vertexBuffer the vertex buffer to update
  95381. * @param data the data used to update the vertex buffer
  95382. * @param byteOffset the byte offset of the data (optional)
  95383. * @param byteLength the byte length of the data (optional)
  95384. */
  95385. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95386. };
  95387. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95388. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95389. this._boundTexturesCache[this._activeChannel] = texture;
  95390. }
  95391. };
  95392. NullEngine.prototype._bindTexture = function (channel, texture) {
  95393. if (channel < 0) {
  95394. return;
  95395. }
  95396. this._bindTextureDirectly(0, texture);
  95397. };
  95398. NullEngine.prototype._releaseBuffer = function (buffer) {
  95399. buffer.references--;
  95400. if (buffer.references === 0) {
  95401. return true;
  95402. }
  95403. return false;
  95404. };
  95405. NullEngine.prototype.releaseEffects = function () {
  95406. };
  95407. return NullEngine;
  95408. }(BABYLON.Engine));
  95409. BABYLON.NullEngine = NullEngine;
  95410. })(BABYLON || (BABYLON = {}));
  95411. //# sourceMappingURL=babylon.nullEngine.js.map
  95412. var BABYLON;
  95413. (function (BABYLON) {
  95414. /**
  95415. * This class can be used to get instrumentation data from a Babylon engine
  95416. */
  95417. var EngineInstrumentation = /** @class */ (function () {
  95418. function EngineInstrumentation(engine) {
  95419. this.engine = engine;
  95420. this._captureGPUFrameTime = false;
  95421. this._gpuFrameTime = new BABYLON.PerfCounter();
  95422. this._captureShaderCompilationTime = false;
  95423. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95424. // Observers
  95425. this._onBeginFrameObserver = null;
  95426. this._onEndFrameObserver = null;
  95427. this._onBeforeShaderCompilationObserver = null;
  95428. this._onAfterShaderCompilationObserver = null;
  95429. }
  95430. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95431. // Properties
  95432. /**
  95433. * Gets the perf counter used for GPU frame time
  95434. */
  95435. get: function () {
  95436. return this._gpuFrameTime;
  95437. },
  95438. enumerable: true,
  95439. configurable: true
  95440. });
  95441. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95442. /**
  95443. * Gets the GPU frame time capture status
  95444. */
  95445. get: function () {
  95446. return this._captureGPUFrameTime;
  95447. },
  95448. /**
  95449. * Enable or disable the GPU frame time capture
  95450. */
  95451. set: function (value) {
  95452. var _this = this;
  95453. if (value === this._captureGPUFrameTime) {
  95454. return;
  95455. }
  95456. this._captureGPUFrameTime = value;
  95457. if (value) {
  95458. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95459. if (!_this._gpuFrameTimeToken) {
  95460. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95461. }
  95462. });
  95463. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95464. if (!_this._gpuFrameTimeToken) {
  95465. return;
  95466. }
  95467. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95468. if (time > -1) {
  95469. _this._gpuFrameTimeToken = null;
  95470. _this._gpuFrameTime.fetchNewFrame();
  95471. _this._gpuFrameTime.addCount(time, true);
  95472. }
  95473. });
  95474. }
  95475. else {
  95476. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95477. this._onBeginFrameObserver = null;
  95478. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95479. this._onEndFrameObserver = null;
  95480. }
  95481. },
  95482. enumerable: true,
  95483. configurable: true
  95484. });
  95485. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95486. /**
  95487. * Gets the perf counter used for shader compilation time
  95488. */
  95489. get: function () {
  95490. return this._shaderCompilationTime;
  95491. },
  95492. enumerable: true,
  95493. configurable: true
  95494. });
  95495. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95496. /**
  95497. * Gets the shader compilation time capture status
  95498. */
  95499. get: function () {
  95500. return this._captureShaderCompilationTime;
  95501. },
  95502. /**
  95503. * Enable or disable the shader compilation time capture
  95504. */
  95505. set: function (value) {
  95506. var _this = this;
  95507. if (value === this._captureShaderCompilationTime) {
  95508. return;
  95509. }
  95510. this._captureShaderCompilationTime = value;
  95511. if (value) {
  95512. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95513. _this._shaderCompilationTime.fetchNewFrame();
  95514. _this._shaderCompilationTime.beginMonitoring();
  95515. });
  95516. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95517. _this._shaderCompilationTime.endMonitoring();
  95518. });
  95519. }
  95520. else {
  95521. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95522. this._onBeforeShaderCompilationObserver = null;
  95523. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95524. this._onAfterShaderCompilationObserver = null;
  95525. }
  95526. },
  95527. enumerable: true,
  95528. configurable: true
  95529. });
  95530. EngineInstrumentation.prototype.dispose = function () {
  95531. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95532. this._onBeginFrameObserver = null;
  95533. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95534. this._onEndFrameObserver = null;
  95535. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95536. this._onBeforeShaderCompilationObserver = null;
  95537. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95538. this._onAfterShaderCompilationObserver = null;
  95539. this.engine = null;
  95540. };
  95541. return EngineInstrumentation;
  95542. }());
  95543. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95544. })(BABYLON || (BABYLON = {}));
  95545. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95546. var BABYLON;
  95547. (function (BABYLON) {
  95548. /**
  95549. * This class can be used to get instrumentation data from a Babylon engine
  95550. */
  95551. var SceneInstrumentation = /** @class */ (function () {
  95552. function SceneInstrumentation(scene) {
  95553. var _this = this;
  95554. this.scene = scene;
  95555. this._captureActiveMeshesEvaluationTime = false;
  95556. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95557. this._captureRenderTargetsRenderTime = false;
  95558. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95559. this._captureFrameTime = false;
  95560. this._frameTime = new BABYLON.PerfCounter();
  95561. this._captureRenderTime = false;
  95562. this._renderTime = new BABYLON.PerfCounter();
  95563. this._captureInterFrameTime = false;
  95564. this._interFrameTime = new BABYLON.PerfCounter();
  95565. this._captureParticlesRenderTime = false;
  95566. this._particlesRenderTime = new BABYLON.PerfCounter();
  95567. this._captureSpritesRenderTime = false;
  95568. this._spritesRenderTime = new BABYLON.PerfCounter();
  95569. this._capturePhysicsTime = false;
  95570. this._physicsTime = new BABYLON.PerfCounter();
  95571. this._captureAnimationsTime = false;
  95572. this._animationsTime = new BABYLON.PerfCounter();
  95573. // Observers
  95574. this._onBeforeActiveMeshesEvaluationObserver = null;
  95575. this._onAfterActiveMeshesEvaluationObserver = null;
  95576. this._onBeforeRenderTargetsRenderObserver = null;
  95577. this._onAfterRenderTargetsRenderObserver = null;
  95578. this._onAfterRenderObserver = null;
  95579. this._onBeforeDrawPhaseObserver = null;
  95580. this._onAfterDrawPhaseObserver = null;
  95581. this._onBeforeAnimationsObserver = null;
  95582. this._onBeforeParticlesRenderingObserver = null;
  95583. this._onAfterParticlesRenderingObserver = null;
  95584. this._onBeforeSpritesRenderingObserver = null;
  95585. this._onAfterSpritesRenderingObserver = null;
  95586. this._onBeforePhysicsObserver = null;
  95587. this._onAfterPhysicsObserver = null;
  95588. this._onAfterAnimationsObserver = null;
  95589. // Before render
  95590. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95591. if (_this._captureActiveMeshesEvaluationTime) {
  95592. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95593. }
  95594. if (_this._captureRenderTargetsRenderTime) {
  95595. _this._renderTargetsRenderTime.fetchNewFrame();
  95596. }
  95597. if (_this._captureFrameTime) {
  95598. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95599. _this._frameTime.beginMonitoring();
  95600. }
  95601. if (_this._captureInterFrameTime) {
  95602. _this._interFrameTime.endMonitoring();
  95603. }
  95604. if (_this._captureParticlesRenderTime) {
  95605. _this._particlesRenderTime.fetchNewFrame();
  95606. }
  95607. if (_this._captureSpritesRenderTime) {
  95608. _this._spritesRenderTime.fetchNewFrame();
  95609. }
  95610. if (_this._captureAnimationsTime) {
  95611. _this._animationsTime.beginMonitoring();
  95612. }
  95613. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95614. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95615. });
  95616. // After render
  95617. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95618. if (_this._captureFrameTime) {
  95619. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95620. _this._frameTime.endMonitoring();
  95621. }
  95622. if (_this._captureRenderTime) {
  95623. _this._renderTime.endMonitoring(false);
  95624. }
  95625. if (_this._captureInterFrameTime) {
  95626. _this._interFrameTime.beginMonitoring();
  95627. }
  95628. });
  95629. }
  95630. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95631. // Properties
  95632. /**
  95633. * Gets the perf counter used for active meshes evaluation time
  95634. */
  95635. get: function () {
  95636. return this._activeMeshesEvaluationTime;
  95637. },
  95638. enumerable: true,
  95639. configurable: true
  95640. });
  95641. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95642. /**
  95643. * Gets the active meshes evaluation time capture status
  95644. */
  95645. get: function () {
  95646. return this._captureActiveMeshesEvaluationTime;
  95647. },
  95648. /**
  95649. * Enable or disable the active meshes evaluation time capture
  95650. */
  95651. set: function (value) {
  95652. var _this = this;
  95653. if (value === this._captureActiveMeshesEvaluationTime) {
  95654. return;
  95655. }
  95656. this._captureActiveMeshesEvaluationTime = value;
  95657. if (value) {
  95658. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95659. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95660. _this._activeMeshesEvaluationTime.beginMonitoring();
  95661. });
  95662. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95663. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95664. _this._activeMeshesEvaluationTime.endMonitoring();
  95665. });
  95666. }
  95667. else {
  95668. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95669. this._onBeforeActiveMeshesEvaluationObserver = null;
  95670. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95671. this._onAfterActiveMeshesEvaluationObserver = null;
  95672. }
  95673. },
  95674. enumerable: true,
  95675. configurable: true
  95676. });
  95677. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95678. /**
  95679. * Gets the perf counter used for render targets render time
  95680. */
  95681. get: function () {
  95682. return this._renderTargetsRenderTime;
  95683. },
  95684. enumerable: true,
  95685. configurable: true
  95686. });
  95687. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95688. /**
  95689. * Gets the render targets render time capture status
  95690. */
  95691. get: function () {
  95692. return this._captureRenderTargetsRenderTime;
  95693. },
  95694. /**
  95695. * Enable or disable the render targets render time capture
  95696. */
  95697. set: function (value) {
  95698. var _this = this;
  95699. if (value === this._captureRenderTargetsRenderTime) {
  95700. return;
  95701. }
  95702. this._captureRenderTargetsRenderTime = value;
  95703. if (value) {
  95704. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95705. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95706. _this._renderTargetsRenderTime.beginMonitoring();
  95707. });
  95708. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95709. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95710. _this._renderTargetsRenderTime.endMonitoring(false);
  95711. });
  95712. }
  95713. else {
  95714. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95715. this._onBeforeRenderTargetsRenderObserver = null;
  95716. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95717. this._onAfterRenderTargetsRenderObserver = null;
  95718. }
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95724. /**
  95725. * Gets the perf counter used for particles render time
  95726. */
  95727. get: function () {
  95728. return this._particlesRenderTime;
  95729. },
  95730. enumerable: true,
  95731. configurable: true
  95732. });
  95733. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95734. /**
  95735. * Gets the particles render time capture status
  95736. */
  95737. get: function () {
  95738. return this._captureParticlesRenderTime;
  95739. },
  95740. /**
  95741. * Enable or disable the particles render time capture
  95742. */
  95743. set: function (value) {
  95744. var _this = this;
  95745. if (value === this._captureParticlesRenderTime) {
  95746. return;
  95747. }
  95748. this._captureParticlesRenderTime = value;
  95749. if (value) {
  95750. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95751. BABYLON.Tools.StartPerformanceCounter("Particles");
  95752. _this._particlesRenderTime.beginMonitoring();
  95753. });
  95754. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95755. BABYLON.Tools.EndPerformanceCounter("Particles");
  95756. _this._particlesRenderTime.endMonitoring(false);
  95757. });
  95758. }
  95759. else {
  95760. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95761. this._onBeforeParticlesRenderingObserver = null;
  95762. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95763. this._onAfterParticlesRenderingObserver = null;
  95764. }
  95765. },
  95766. enumerable: true,
  95767. configurable: true
  95768. });
  95769. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95770. /**
  95771. * Gets the perf counter used for sprites render time
  95772. */
  95773. get: function () {
  95774. return this._spritesRenderTime;
  95775. },
  95776. enumerable: true,
  95777. configurable: true
  95778. });
  95779. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95780. /**
  95781. * Gets the sprites render time capture status
  95782. */
  95783. get: function () {
  95784. return this._captureSpritesRenderTime;
  95785. },
  95786. /**
  95787. * Enable or disable the sprites render time capture
  95788. */
  95789. set: function (value) {
  95790. var _this = this;
  95791. if (value === this._captureSpritesRenderTime) {
  95792. return;
  95793. }
  95794. this._captureSpritesRenderTime = value;
  95795. if (value) {
  95796. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95797. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95798. _this._spritesRenderTime.beginMonitoring();
  95799. });
  95800. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95801. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95802. _this._spritesRenderTime.endMonitoring(false);
  95803. });
  95804. }
  95805. else {
  95806. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95807. this._onBeforeSpritesRenderingObserver = null;
  95808. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95809. this._onAfterSpritesRenderingObserver = null;
  95810. }
  95811. },
  95812. enumerable: true,
  95813. configurable: true
  95814. });
  95815. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95816. /**
  95817. * Gets the perf counter used for physics time
  95818. */
  95819. get: function () {
  95820. return this._physicsTime;
  95821. },
  95822. enumerable: true,
  95823. configurable: true
  95824. });
  95825. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95826. /**
  95827. * Gets the physics time capture status
  95828. */
  95829. get: function () {
  95830. return this._capturePhysicsTime;
  95831. },
  95832. /**
  95833. * Enable or disable the physics time capture
  95834. */
  95835. set: function (value) {
  95836. var _this = this;
  95837. if (value === this._capturePhysicsTime) {
  95838. return;
  95839. }
  95840. this._capturePhysicsTime = value;
  95841. if (value) {
  95842. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95843. BABYLON.Tools.StartPerformanceCounter("Physics");
  95844. _this._physicsTime.beginMonitoring();
  95845. });
  95846. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95847. BABYLON.Tools.EndPerformanceCounter("Physics");
  95848. _this._physicsTime.endMonitoring();
  95849. });
  95850. }
  95851. else {
  95852. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95853. this._onBeforePhysicsObserver = null;
  95854. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95855. this._onAfterPhysicsObserver = null;
  95856. }
  95857. },
  95858. enumerable: true,
  95859. configurable: true
  95860. });
  95861. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95862. /**
  95863. * Gets the perf counter used for animations time
  95864. */
  95865. get: function () {
  95866. return this._animationsTime;
  95867. },
  95868. enumerable: true,
  95869. configurable: true
  95870. });
  95871. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95872. /**
  95873. * Gets the animations time capture status
  95874. */
  95875. get: function () {
  95876. return this._captureAnimationsTime;
  95877. },
  95878. /**
  95879. * Enable or disable the animations time capture
  95880. */
  95881. set: function (value) {
  95882. var _this = this;
  95883. if (value === this._captureAnimationsTime) {
  95884. return;
  95885. }
  95886. this._captureAnimationsTime = value;
  95887. if (value) {
  95888. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95889. _this._animationsTime.endMonitoring();
  95890. });
  95891. }
  95892. else {
  95893. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95894. this._onAfterAnimationsObserver = null;
  95895. }
  95896. },
  95897. enumerable: true,
  95898. configurable: true
  95899. });
  95900. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95901. /**
  95902. * Gets the perf counter used for frame time capture
  95903. */
  95904. get: function () {
  95905. return this._frameTime;
  95906. },
  95907. enumerable: true,
  95908. configurable: true
  95909. });
  95910. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95911. /**
  95912. * Gets the frame time capture status
  95913. */
  95914. get: function () {
  95915. return this._captureFrameTime;
  95916. },
  95917. /**
  95918. * Enable or disable the frame time capture
  95919. */
  95920. set: function (value) {
  95921. this._captureFrameTime = value;
  95922. },
  95923. enumerable: true,
  95924. configurable: true
  95925. });
  95926. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95927. /**
  95928. * Gets the perf counter used for inter-frames time capture
  95929. */
  95930. get: function () {
  95931. return this._interFrameTime;
  95932. },
  95933. enumerable: true,
  95934. configurable: true
  95935. });
  95936. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95937. /**
  95938. * Gets the inter-frames time capture status
  95939. */
  95940. get: function () {
  95941. return this._captureInterFrameTime;
  95942. },
  95943. /**
  95944. * Enable or disable the inter-frames time capture
  95945. */
  95946. set: function (value) {
  95947. this._captureInterFrameTime = value;
  95948. },
  95949. enumerable: true,
  95950. configurable: true
  95951. });
  95952. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95953. /**
  95954. * Gets the perf counter used for render time capture
  95955. */
  95956. get: function () {
  95957. return this._renderTime;
  95958. },
  95959. enumerable: true,
  95960. configurable: true
  95961. });
  95962. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95963. /**
  95964. * Gets the render time capture status
  95965. */
  95966. get: function () {
  95967. return this._captureRenderTime;
  95968. },
  95969. /**
  95970. * Enable or disable the render time capture
  95971. */
  95972. set: function (value) {
  95973. var _this = this;
  95974. if (value === this._captureRenderTime) {
  95975. return;
  95976. }
  95977. this._captureRenderTime = value;
  95978. if (value) {
  95979. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95980. _this._renderTime.beginMonitoring();
  95981. BABYLON.Tools.StartPerformanceCounter("Main render");
  95982. });
  95983. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95984. _this._renderTime.endMonitoring(false);
  95985. BABYLON.Tools.EndPerformanceCounter("Main render");
  95986. });
  95987. }
  95988. else {
  95989. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95990. this._onBeforeDrawPhaseObserver = null;
  95991. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95992. this._onAfterDrawPhaseObserver = null;
  95993. }
  95994. },
  95995. enumerable: true,
  95996. configurable: true
  95997. });
  95998. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95999. /**
  96000. * Gets the perf counter used for draw calls
  96001. */
  96002. get: function () {
  96003. return this.scene.getEngine()._drawCalls;
  96004. },
  96005. enumerable: true,
  96006. configurable: true
  96007. });
  96008. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96009. /**
  96010. * Gets the perf counter used for texture collisions
  96011. */
  96012. get: function () {
  96013. return this.scene.getEngine()._textureCollisions;
  96014. },
  96015. enumerable: true,
  96016. configurable: true
  96017. });
  96018. SceneInstrumentation.prototype.dispose = function () {
  96019. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96020. this._onAfterRenderObserver = null;
  96021. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96022. this._onBeforeActiveMeshesEvaluationObserver = null;
  96023. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96024. this._onAfterActiveMeshesEvaluationObserver = null;
  96025. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96026. this._onBeforeRenderTargetsRenderObserver = null;
  96027. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96028. this._onAfterRenderTargetsRenderObserver = null;
  96029. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96030. this._onBeforeAnimationsObserver = null;
  96031. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96032. this._onBeforeParticlesRenderingObserver = null;
  96033. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96034. this._onAfterParticlesRenderingObserver = null;
  96035. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96036. this._onBeforeSpritesRenderingObserver = null;
  96037. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96038. this._onAfterSpritesRenderingObserver = null;
  96039. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96040. this._onBeforeDrawPhaseObserver = null;
  96041. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96042. this._onAfterDrawPhaseObserver = null;
  96043. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96044. this._onBeforePhysicsObserver = null;
  96045. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96046. this._onAfterPhysicsObserver = null;
  96047. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96048. this._onAfterAnimationsObserver = null;
  96049. this.scene = null;
  96050. };
  96051. return SceneInstrumentation;
  96052. }());
  96053. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96054. })(BABYLON || (BABYLON = {}));
  96055. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96056. var BABYLON;
  96057. (function (BABYLON) {
  96058. /**
  96059. * @hidden
  96060. **/
  96061. var _TimeToken = /** @class */ (function () {
  96062. function _TimeToken() {
  96063. this._timeElapsedQueryEnded = false;
  96064. }
  96065. return _TimeToken;
  96066. }());
  96067. BABYLON._TimeToken = _TimeToken;
  96068. })(BABYLON || (BABYLON = {}));
  96069. //# sourceMappingURL=babylon.timeToken.js.map
  96070. var BABYLON;
  96071. (function (BABYLON) {
  96072. /**
  96073. * Background material defines definition.
  96074. * @hidden Mainly internal Use
  96075. */
  96076. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96077. __extends(BackgroundMaterialDefines, _super);
  96078. /**
  96079. * Constructor of the defines.
  96080. */
  96081. function BackgroundMaterialDefines() {
  96082. var _this = _super.call(this) || this;
  96083. /**
  96084. * True if the diffuse texture is in use.
  96085. */
  96086. _this.DIFFUSE = false;
  96087. /**
  96088. * The direct UV channel to use.
  96089. */
  96090. _this.DIFFUSEDIRECTUV = 0;
  96091. /**
  96092. * True if the diffuse texture is in gamma space.
  96093. */
  96094. _this.GAMMADIFFUSE = false;
  96095. /**
  96096. * True if the diffuse texture has opacity in the alpha channel.
  96097. */
  96098. _this.DIFFUSEHASALPHA = false;
  96099. /**
  96100. * True if you want the material to fade to transparent at grazing angle.
  96101. */
  96102. _this.OPACITYFRESNEL = false;
  96103. /**
  96104. * True if an extra blur needs to be added in the reflection.
  96105. */
  96106. _this.REFLECTIONBLUR = false;
  96107. /**
  96108. * True if you want the material to fade to reflection at grazing angle.
  96109. */
  96110. _this.REFLECTIONFRESNEL = false;
  96111. /**
  96112. * True if you want the material to falloff as far as you move away from the scene center.
  96113. */
  96114. _this.REFLECTIONFALLOFF = false;
  96115. /**
  96116. * False if the current Webgl implementation does not support the texture lod extension.
  96117. */
  96118. _this.TEXTURELODSUPPORT = false;
  96119. /**
  96120. * True to ensure the data are premultiplied.
  96121. */
  96122. _this.PREMULTIPLYALPHA = false;
  96123. /**
  96124. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96125. */
  96126. _this.USERGBCOLOR = false;
  96127. /**
  96128. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96129. * stays aligned with the desired configuration.
  96130. */
  96131. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96132. /**
  96133. * True to add noise in order to reduce the banding effect.
  96134. */
  96135. _this.NOISE = false;
  96136. /**
  96137. * is the reflection texture in BGR color scheme?
  96138. * Mainly used to solve a bug in ios10 video tag
  96139. */
  96140. _this.REFLECTIONBGR = false;
  96141. _this.IMAGEPROCESSING = false;
  96142. _this.VIGNETTE = false;
  96143. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96144. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96145. _this.TONEMAPPING = false;
  96146. _this.CONTRAST = false;
  96147. _this.COLORCURVES = false;
  96148. _this.COLORGRADING = false;
  96149. _this.COLORGRADING3D = false;
  96150. _this.SAMPLER3DGREENDEPTH = false;
  96151. _this.SAMPLER3DBGRMAP = false;
  96152. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96153. _this.EXPOSURE = false;
  96154. // Reflection.
  96155. _this.REFLECTION = false;
  96156. _this.REFLECTIONMAP_3D = false;
  96157. _this.REFLECTIONMAP_SPHERICAL = false;
  96158. _this.REFLECTIONMAP_PLANAR = false;
  96159. _this.REFLECTIONMAP_CUBIC = false;
  96160. _this.REFLECTIONMAP_PROJECTION = false;
  96161. _this.REFLECTIONMAP_SKYBOX = false;
  96162. _this.REFLECTIONMAP_EXPLICIT = false;
  96163. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96164. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96165. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96166. _this.INVERTCUBICMAP = false;
  96167. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96168. _this.LODINREFLECTIONALPHA = false;
  96169. _this.GAMMAREFLECTION = false;
  96170. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96171. // Default BJS.
  96172. _this.MAINUV1 = false;
  96173. _this.MAINUV2 = false;
  96174. _this.UV1 = false;
  96175. _this.UV2 = false;
  96176. _this.CLIPPLANE = false;
  96177. _this.POINTSIZE = false;
  96178. _this.FOG = false;
  96179. _this.NORMAL = false;
  96180. _this.NUM_BONE_INFLUENCERS = 0;
  96181. _this.BonesPerMesh = 0;
  96182. _this.INSTANCES = false;
  96183. _this.SHADOWFLOAT = false;
  96184. _this.rebuild();
  96185. return _this;
  96186. }
  96187. return BackgroundMaterialDefines;
  96188. }(BABYLON.MaterialDefines));
  96189. /**
  96190. * Background material used to create an efficient environement around your scene.
  96191. */
  96192. var BackgroundMaterial = /** @class */ (function (_super) {
  96193. __extends(BackgroundMaterial, _super);
  96194. /**
  96195. * Instantiates a Background Material in the given scene
  96196. * @param name The friendly name of the material
  96197. * @param scene The scene to add the material to
  96198. */
  96199. function BackgroundMaterial(name, scene) {
  96200. var _this = _super.call(this, name, scene) || this;
  96201. /**
  96202. * Key light Color (multiply against the environement texture)
  96203. */
  96204. _this.primaryColor = BABYLON.Color3.White();
  96205. _this._primaryColorShadowLevel = 0;
  96206. _this._primaryColorHighlightLevel = 0;
  96207. /**
  96208. * Reflection Texture used in the material.
  96209. * Should be author in a specific way for the best result (refer to the documentation).
  96210. */
  96211. _this.reflectionTexture = null;
  96212. /**
  96213. * Reflection Texture level of blur.
  96214. *
  96215. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96216. * texture twice.
  96217. */
  96218. _this.reflectionBlur = 0;
  96219. /**
  96220. * Diffuse Texture used in the material.
  96221. * Should be author in a specific way for the best result (refer to the documentation).
  96222. */
  96223. _this.diffuseTexture = null;
  96224. _this._shadowLights = null;
  96225. /**
  96226. * Specify the list of lights casting shadow on the material.
  96227. * All scene shadow lights will be included if null.
  96228. */
  96229. _this.shadowLights = null;
  96230. /**
  96231. * Helps adjusting the shadow to a softer level if required.
  96232. * 0 means black shadows and 1 means no shadows.
  96233. */
  96234. _this.shadowLevel = 0;
  96235. /**
  96236. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96237. * It is usually zero but might be interesting to modify according to your setup.
  96238. */
  96239. _this.sceneCenter = BABYLON.Vector3.Zero();
  96240. /**
  96241. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96242. * This helps ensuring a nice transition when the camera goes under the ground.
  96243. */
  96244. _this.opacityFresnel = true;
  96245. /**
  96246. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96247. * This helps adding a mirror texture on the ground.
  96248. */
  96249. _this.reflectionFresnel = false;
  96250. /**
  96251. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96252. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96253. */
  96254. _this.reflectionFalloffDistance = 0.0;
  96255. /**
  96256. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96257. */
  96258. _this.reflectionAmount = 1.0;
  96259. /**
  96260. * This specifies the weight of the reflection at grazing angle.
  96261. */
  96262. _this.reflectionReflectance0 = 0.05;
  96263. /**
  96264. * This specifies the weight of the reflection at a perpendicular point of view.
  96265. */
  96266. _this.reflectionReflectance90 = 0.5;
  96267. /**
  96268. * Helps to directly use the maps channels instead of their level.
  96269. */
  96270. _this.useRGBColor = true;
  96271. /**
  96272. * This helps reducing the banding effect that could occur on the background.
  96273. */
  96274. _this.enableNoise = false;
  96275. _this._fovMultiplier = 1.0;
  96276. /**
  96277. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96278. */
  96279. _this.useEquirectangularFOV = false;
  96280. _this._maxSimultaneousLights = 4;
  96281. /**
  96282. * Number of Simultaneous lights allowed on the material.
  96283. */
  96284. _this.maxSimultaneousLights = 4;
  96285. /**
  96286. * Keep track of the image processing observer to allow dispose and replace.
  96287. */
  96288. _this._imageProcessingObserver = null;
  96289. /**
  96290. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96291. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96292. */
  96293. _this.switchToBGR = false;
  96294. // Temp values kept as cache in the material.
  96295. _this._renderTargets = new BABYLON.SmartArray(16);
  96296. _this._reflectionControls = BABYLON.Vector4.Zero();
  96297. _this._white = BABYLON.Color3.White();
  96298. _this._primaryShadowColor = BABYLON.Color3.Black();
  96299. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96300. // Setup the default processing configuration to the scene.
  96301. _this._attachImageProcessingConfiguration(null);
  96302. _this.getRenderTargetTextures = function () {
  96303. _this._renderTargets.reset();
  96304. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96305. _this._renderTargets.push(_this._diffuseTexture);
  96306. }
  96307. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96308. _this._renderTargets.push(_this._reflectionTexture);
  96309. }
  96310. return _this._renderTargets;
  96311. };
  96312. return _this;
  96313. }
  96314. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96315. /**
  96316. * Experimental Internal Use Only.
  96317. *
  96318. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96319. * This acts as a helper to set the primary color to a more "human friendly" value.
  96320. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96321. * output color as close as possible from the chosen value.
  96322. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96323. * part of lighting setup.)
  96324. */
  96325. get: function () {
  96326. return this.__perceptualColor;
  96327. },
  96328. set: function (value) {
  96329. this.__perceptualColor = value;
  96330. this._computePrimaryColorFromPerceptualColor();
  96331. this._markAllSubMeshesAsLightsDirty();
  96332. },
  96333. enumerable: true,
  96334. configurable: true
  96335. });
  96336. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96337. /**
  96338. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96339. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96340. */
  96341. get: function () {
  96342. return this._primaryColorShadowLevel;
  96343. },
  96344. set: function (value) {
  96345. this._primaryColorShadowLevel = value;
  96346. this._computePrimaryColors();
  96347. this._markAllSubMeshesAsLightsDirty();
  96348. },
  96349. enumerable: true,
  96350. configurable: true
  96351. });
  96352. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96353. /**
  96354. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96355. * The primary color is used at the level chosen to define what the white area would look.
  96356. */
  96357. get: function () {
  96358. return this._primaryColorHighlightLevel;
  96359. },
  96360. set: function (value) {
  96361. this._primaryColorHighlightLevel = value;
  96362. this._computePrimaryColors();
  96363. this._markAllSubMeshesAsLightsDirty();
  96364. },
  96365. enumerable: true,
  96366. configurable: true
  96367. });
  96368. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96369. /**
  96370. * Sets the reflection reflectance fresnel values according to the default standard
  96371. * empirically know to work well :-)
  96372. */
  96373. set: function (value) {
  96374. var reflectionWeight = value;
  96375. if (reflectionWeight < 0.5) {
  96376. reflectionWeight = reflectionWeight * 2.0;
  96377. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96378. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96379. }
  96380. else {
  96381. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96382. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96383. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96384. }
  96385. },
  96386. enumerable: true,
  96387. configurable: true
  96388. });
  96389. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96390. /**
  96391. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96392. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96393. * Recommended to be keep at 1.0 except for special cases.
  96394. */
  96395. get: function () {
  96396. return this._fovMultiplier;
  96397. },
  96398. set: function (value) {
  96399. if (isNaN(value)) {
  96400. value = 1.0;
  96401. }
  96402. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96403. },
  96404. enumerable: true,
  96405. configurable: true
  96406. });
  96407. /**
  96408. * Attaches a new image processing configuration to the PBR Material.
  96409. * @param configuration (if null the scene configuration will be use)
  96410. */
  96411. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96412. var _this = this;
  96413. if (configuration === this._imageProcessingConfiguration) {
  96414. return;
  96415. }
  96416. // Detaches observer.
  96417. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96418. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96419. }
  96420. // Pick the scene configuration if needed.
  96421. if (!configuration) {
  96422. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96423. }
  96424. else {
  96425. this._imageProcessingConfiguration = configuration;
  96426. }
  96427. // Attaches observer.
  96428. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96429. _this._computePrimaryColorFromPerceptualColor();
  96430. _this._markAllSubMeshesAsImageProcessingDirty();
  96431. });
  96432. };
  96433. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96434. /**
  96435. * Gets the image processing configuration used either in this material.
  96436. */
  96437. get: function () {
  96438. return this._imageProcessingConfiguration;
  96439. },
  96440. /**
  96441. * Sets the Default image processing configuration used either in the this material.
  96442. *
  96443. * If sets to null, the scene one is in use.
  96444. */
  96445. set: function (value) {
  96446. this._attachImageProcessingConfiguration(value);
  96447. // Ensure the effect will be rebuilt.
  96448. this._markAllSubMeshesAsTexturesDirty();
  96449. },
  96450. enumerable: true,
  96451. configurable: true
  96452. });
  96453. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96454. /**
  96455. * Gets wether the color curves effect is enabled.
  96456. */
  96457. get: function () {
  96458. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96459. },
  96460. /**
  96461. * Sets wether the color curves effect is enabled.
  96462. */
  96463. set: function (value) {
  96464. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96470. /**
  96471. * Gets wether the color grading effect is enabled.
  96472. */
  96473. get: function () {
  96474. return this.imageProcessingConfiguration.colorGradingEnabled;
  96475. },
  96476. /**
  96477. * Gets wether the color grading effect is enabled.
  96478. */
  96479. set: function (value) {
  96480. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96486. /**
  96487. * Gets wether tonemapping is enabled or not.
  96488. */
  96489. get: function () {
  96490. return this._imageProcessingConfiguration.toneMappingEnabled;
  96491. },
  96492. /**
  96493. * Sets wether tonemapping is enabled or not
  96494. */
  96495. set: function (value) {
  96496. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96497. },
  96498. enumerable: true,
  96499. configurable: true
  96500. });
  96501. ;
  96502. ;
  96503. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96504. /**
  96505. * The camera exposure used on this material.
  96506. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96507. * This corresponds to a photographic exposure.
  96508. */
  96509. get: function () {
  96510. return this._imageProcessingConfiguration.exposure;
  96511. },
  96512. /**
  96513. * The camera exposure used on this material.
  96514. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96515. * This corresponds to a photographic exposure.
  96516. */
  96517. set: function (value) {
  96518. this._imageProcessingConfiguration.exposure = value;
  96519. },
  96520. enumerable: true,
  96521. configurable: true
  96522. });
  96523. ;
  96524. ;
  96525. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96526. /**
  96527. * Gets The camera contrast used on this material.
  96528. */
  96529. get: function () {
  96530. return this._imageProcessingConfiguration.contrast;
  96531. },
  96532. /**
  96533. * Sets The camera contrast used on this material.
  96534. */
  96535. set: function (value) {
  96536. this._imageProcessingConfiguration.contrast = value;
  96537. },
  96538. enumerable: true,
  96539. configurable: true
  96540. });
  96541. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96542. /**
  96543. * Gets the Color Grading 2D Lookup Texture.
  96544. */
  96545. get: function () {
  96546. return this._imageProcessingConfiguration.colorGradingTexture;
  96547. },
  96548. /**
  96549. * Sets the Color Grading 2D Lookup Texture.
  96550. */
  96551. set: function (value) {
  96552. this.imageProcessingConfiguration.colorGradingTexture = value;
  96553. },
  96554. enumerable: true,
  96555. configurable: true
  96556. });
  96557. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96558. /**
  96559. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96560. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96561. * 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;
  96562. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96563. */
  96564. get: function () {
  96565. return this.imageProcessingConfiguration.colorCurves;
  96566. },
  96567. /**
  96568. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96569. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96570. * 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;
  96571. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96572. */
  96573. set: function (value) {
  96574. this.imageProcessingConfiguration.colorCurves = value;
  96575. },
  96576. enumerable: true,
  96577. configurable: true
  96578. });
  96579. /**
  96580. * The entire material has been created in order to prevent overdraw.
  96581. * @returns false
  96582. */
  96583. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96584. return true;
  96585. };
  96586. /**
  96587. * The entire material has been created in order to prevent overdraw.
  96588. * @returns true if blending is enable
  96589. */
  96590. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96591. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96592. };
  96593. /**
  96594. * Checks wether the material is ready to be rendered for a given mesh.
  96595. * @param mesh The mesh to render
  96596. * @param subMesh The submesh to check against
  96597. * @param useInstances Specify wether or not the material is used with instances
  96598. * @returns true if all the dependencies are ready (Textures, Effects...)
  96599. */
  96600. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96601. var _this = this;
  96602. if (useInstances === void 0) { useInstances = false; }
  96603. if (subMesh.effect && this.isFrozen) {
  96604. if (this._wasPreviouslyReady) {
  96605. return true;
  96606. }
  96607. }
  96608. if (!subMesh._materialDefines) {
  96609. subMesh._materialDefines = new BackgroundMaterialDefines();
  96610. }
  96611. var scene = this.getScene();
  96612. var defines = subMesh._materialDefines;
  96613. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96614. if (defines._renderId === scene.getRenderId()) {
  96615. return true;
  96616. }
  96617. }
  96618. var engine = scene.getEngine();
  96619. // Lights
  96620. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96621. defines._needNormals = true;
  96622. // Textures
  96623. if (defines._areTexturesDirty) {
  96624. defines._needUVs = false;
  96625. if (scene.texturesEnabled) {
  96626. if (scene.getEngine().getCaps().textureLOD) {
  96627. defines.TEXTURELODSUPPORT = true;
  96628. }
  96629. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96630. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96631. return false;
  96632. }
  96633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96634. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96635. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96636. defines.OPACITYFRESNEL = this._opacityFresnel;
  96637. }
  96638. else {
  96639. defines.DIFFUSE = false;
  96640. defines.DIFFUSEHASALPHA = false;
  96641. defines.GAMMADIFFUSE = false;
  96642. defines.OPACITYFRESNEL = false;
  96643. }
  96644. var reflectionTexture = this._reflectionTexture;
  96645. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96646. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96647. return false;
  96648. }
  96649. defines.REFLECTION = true;
  96650. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96651. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96652. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96653. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96654. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96655. defines.REFLECTIONBGR = this.switchToBGR;
  96656. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96657. defines.INVERTCUBICMAP = true;
  96658. }
  96659. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96660. switch (reflectionTexture.coordinatesMode) {
  96661. case BABYLON.Texture.EXPLICIT_MODE:
  96662. defines.REFLECTIONMAP_EXPLICIT = true;
  96663. break;
  96664. case BABYLON.Texture.PLANAR_MODE:
  96665. defines.REFLECTIONMAP_PLANAR = true;
  96666. break;
  96667. case BABYLON.Texture.PROJECTION_MODE:
  96668. defines.REFLECTIONMAP_PROJECTION = true;
  96669. break;
  96670. case BABYLON.Texture.SKYBOX_MODE:
  96671. defines.REFLECTIONMAP_SKYBOX = true;
  96672. break;
  96673. case BABYLON.Texture.SPHERICAL_MODE:
  96674. defines.REFLECTIONMAP_SPHERICAL = true;
  96675. break;
  96676. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96677. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96678. break;
  96679. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96680. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96681. break;
  96682. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96683. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96684. break;
  96685. case BABYLON.Texture.CUBIC_MODE:
  96686. case BABYLON.Texture.INVCUBIC_MODE:
  96687. default:
  96688. defines.REFLECTIONMAP_CUBIC = true;
  96689. break;
  96690. }
  96691. if (this.reflectionFresnel) {
  96692. defines.REFLECTIONFRESNEL = true;
  96693. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96694. this._reflectionControls.x = this.reflectionAmount;
  96695. this._reflectionControls.y = this.reflectionReflectance0;
  96696. this._reflectionControls.z = this.reflectionReflectance90;
  96697. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96698. }
  96699. else {
  96700. defines.REFLECTIONFRESNEL = false;
  96701. defines.REFLECTIONFALLOFF = false;
  96702. }
  96703. }
  96704. else {
  96705. defines.REFLECTION = false;
  96706. defines.REFLECTIONFRESNEL = false;
  96707. defines.REFLECTIONFALLOFF = false;
  96708. defines.REFLECTIONBLUR = false;
  96709. defines.REFLECTIONMAP_3D = false;
  96710. defines.REFLECTIONMAP_SPHERICAL = false;
  96711. defines.REFLECTIONMAP_PLANAR = false;
  96712. defines.REFLECTIONMAP_CUBIC = false;
  96713. defines.REFLECTIONMAP_PROJECTION = false;
  96714. defines.REFLECTIONMAP_SKYBOX = false;
  96715. defines.REFLECTIONMAP_EXPLICIT = false;
  96716. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96717. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96718. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96719. defines.INVERTCUBICMAP = false;
  96720. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96721. defines.LODINREFLECTIONALPHA = false;
  96722. defines.GAMMAREFLECTION = false;
  96723. }
  96724. }
  96725. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96726. defines.USERGBCOLOR = this._useRGBColor;
  96727. defines.NOISE = this._enableNoise;
  96728. }
  96729. if (defines._areLightsDirty) {
  96730. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96731. }
  96732. if (defines._areImageProcessingDirty) {
  96733. if (!this._imageProcessingConfiguration.isReady()) {
  96734. return false;
  96735. }
  96736. this._imageProcessingConfiguration.prepareDefines(defines);
  96737. }
  96738. // Misc.
  96739. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96740. // Values that need to be evaluated on every frame
  96741. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96742. // Attribs
  96743. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96744. if (mesh) {
  96745. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96746. mesh.createNormals(true);
  96747. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96748. }
  96749. }
  96750. }
  96751. // Get correct effect
  96752. if (defines.isDirty) {
  96753. defines.markAsProcessed();
  96754. scene.resetCachedMaterial();
  96755. // Fallbacks
  96756. var fallbacks = new BABYLON.EffectFallbacks();
  96757. if (defines.FOG) {
  96758. fallbacks.addFallback(0, "FOG");
  96759. }
  96760. if (defines.POINTSIZE) {
  96761. fallbacks.addFallback(1, "POINTSIZE");
  96762. }
  96763. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96764. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96765. fallbacks.addCPUSkinningFallback(0, mesh);
  96766. }
  96767. //Attributes
  96768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96769. if (defines.NORMAL) {
  96770. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96771. }
  96772. if (defines.UV1) {
  96773. attribs.push(BABYLON.VertexBuffer.UVKind);
  96774. }
  96775. if (defines.UV2) {
  96776. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96777. }
  96778. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96779. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96780. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96781. "vFogInfos", "vFogColor", "pointSize",
  96782. "vClipPlane", "mBones",
  96783. "vPrimaryColor", "vPrimaryColorShadow",
  96784. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96785. "shadowLevel", "alpha",
  96786. "vBackgroundCenter", "vReflectionControl",
  96787. "vDiffuseInfos", "diffuseMatrix",
  96788. ];
  96789. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96790. var uniformBuffers = ["Material", "Scene"];
  96791. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96792. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96793. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96794. uniformsNames: uniforms,
  96795. uniformBuffersNames: uniformBuffers,
  96796. samplers: samplers,
  96797. defines: defines,
  96798. maxSimultaneousLights: this._maxSimultaneousLights
  96799. });
  96800. var onCompiled = function (effect) {
  96801. if (_this.onCompiled) {
  96802. _this.onCompiled(effect);
  96803. }
  96804. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96805. };
  96806. var join = defines.toString();
  96807. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96808. attributes: attribs,
  96809. uniformsNames: uniforms,
  96810. uniformBuffersNames: uniformBuffers,
  96811. samplers: samplers,
  96812. defines: join,
  96813. fallbacks: fallbacks,
  96814. onCompiled: onCompiled,
  96815. onError: this.onError,
  96816. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96817. }, engine), defines);
  96818. this.buildUniformLayout();
  96819. }
  96820. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96821. return false;
  96822. }
  96823. defines._renderId = scene.getRenderId();
  96824. this._wasPreviouslyReady = true;
  96825. return true;
  96826. };
  96827. /**
  96828. * Compute the primary color according to the chosen perceptual color.
  96829. */
  96830. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96831. if (!this.__perceptualColor) {
  96832. return;
  96833. }
  96834. this._primaryColor.copyFrom(this.__perceptualColor);
  96835. // Revert gamma space.
  96836. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96837. // Revert image processing configuration.
  96838. if (this._imageProcessingConfiguration) {
  96839. // Revert Exposure.
  96840. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96841. }
  96842. this._computePrimaryColors();
  96843. };
  96844. /**
  96845. * Compute the highlights and shadow colors according to their chosen levels.
  96846. */
  96847. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96848. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96849. return;
  96850. }
  96851. // Find the highlight color based on the configuration.
  96852. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96853. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96854. // Find the shadow color based on the configuration.
  96855. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96856. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96857. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96858. };
  96859. /**
  96860. * Build the uniform buffer used in the material.
  96861. */
  96862. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96863. // Order is important !
  96864. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96865. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96866. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96867. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96868. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96869. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96870. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96871. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96872. this._uniformBuffer.addUniform("pointSize", 1);
  96873. this._uniformBuffer.addUniform("shadowLevel", 1);
  96874. this._uniformBuffer.addUniform("alpha", 1);
  96875. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96876. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96877. this._uniformBuffer.create();
  96878. };
  96879. /**
  96880. * Unbind the material.
  96881. */
  96882. BackgroundMaterial.prototype.unbind = function () {
  96883. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96884. this._uniformBuffer.setTexture("diffuseSampler", null);
  96885. }
  96886. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96887. this._uniformBuffer.setTexture("reflectionSampler", null);
  96888. }
  96889. _super.prototype.unbind.call(this);
  96890. };
  96891. /**
  96892. * Bind only the world matrix to the material.
  96893. * @param world The world matrix to bind.
  96894. */
  96895. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96896. this._activeEffect.setMatrix("world", world);
  96897. };
  96898. /**
  96899. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96900. * @param world The world matrix to bind.
  96901. * @param subMesh The submesh to bind for.
  96902. */
  96903. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96904. var scene = this.getScene();
  96905. var defines = subMesh._materialDefines;
  96906. if (!defines) {
  96907. return;
  96908. }
  96909. var effect = subMesh.effect;
  96910. if (!effect) {
  96911. return;
  96912. }
  96913. this._activeEffect = effect;
  96914. // Matrices
  96915. this.bindOnlyWorldMatrix(world);
  96916. // Bones
  96917. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96918. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96919. if (mustRebind) {
  96920. this._uniformBuffer.bindToEffect(effect, "Material");
  96921. this.bindViewProjection(effect);
  96922. var reflectionTexture = this._reflectionTexture;
  96923. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96924. // Texture uniforms
  96925. if (scene.texturesEnabled) {
  96926. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96927. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96928. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96929. }
  96930. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96931. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96932. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96933. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96934. }
  96935. }
  96936. if (this.shadowLevel > 0) {
  96937. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96938. }
  96939. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96940. // Point size
  96941. if (this.pointsCloud) {
  96942. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96943. }
  96944. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96945. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96946. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96947. }
  96948. else {
  96949. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96950. }
  96951. }
  96952. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96953. // Textures
  96954. if (scene.texturesEnabled) {
  96955. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96956. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96957. }
  96958. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96959. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96960. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96961. }
  96962. else if (!defines.REFLECTIONBLUR) {
  96963. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96964. }
  96965. else {
  96966. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96967. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96968. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96969. }
  96970. if (defines.REFLECTIONFRESNEL) {
  96971. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96972. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96973. }
  96974. }
  96975. }
  96976. // Clip plane
  96977. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96978. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96979. }
  96980. if (mustRebind || !this.isFrozen) {
  96981. if (scene.lightsEnabled) {
  96982. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96983. }
  96984. // View
  96985. this.bindView(effect);
  96986. // Fog
  96987. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96988. // image processing
  96989. this._imageProcessingConfiguration.bind(this._activeEffect);
  96990. }
  96991. this._uniformBuffer.update();
  96992. this._afterBind(mesh);
  96993. };
  96994. /**
  96995. * Dispose the material.
  96996. * @param forceDisposeEffect Force disposal of the associated effect.
  96997. * @param forceDisposeTextures Force disposal of the associated textures.
  96998. */
  96999. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97000. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97001. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97002. if (forceDisposeTextures) {
  97003. if (this.diffuseTexture) {
  97004. this.diffuseTexture.dispose();
  97005. }
  97006. if (this.reflectionTexture) {
  97007. this.reflectionTexture.dispose();
  97008. }
  97009. }
  97010. this._renderTargets.dispose();
  97011. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97012. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97013. }
  97014. _super.prototype.dispose.call(this, forceDisposeEffect);
  97015. };
  97016. /**
  97017. * Clones the material.
  97018. * @param name The cloned name.
  97019. * @returns The cloned material.
  97020. */
  97021. BackgroundMaterial.prototype.clone = function (name) {
  97022. var _this = this;
  97023. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97024. };
  97025. /**
  97026. * Serializes the current material to its JSON representation.
  97027. * @returns The JSON representation.
  97028. */
  97029. BackgroundMaterial.prototype.serialize = function () {
  97030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97031. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97032. return serializationObject;
  97033. };
  97034. /**
  97035. * Gets the class name of the material
  97036. * @returns "BackgroundMaterial"
  97037. */
  97038. BackgroundMaterial.prototype.getClassName = function () {
  97039. return "BackgroundMaterial";
  97040. };
  97041. /**
  97042. * Parse a JSON input to create back a background material.
  97043. * @param source The JSON data to parse
  97044. * @param scene The scene to create the parsed material in
  97045. * @param rootUrl The root url of the assets the material depends upon
  97046. * @returns the instantiated BackgroundMaterial.
  97047. */
  97048. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97049. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97050. };
  97051. /**
  97052. * Standard reflectance value at parallel view angle.
  97053. */
  97054. BackgroundMaterial.StandardReflectance0 = 0.05;
  97055. /**
  97056. * Standard reflectance value at grazing angle.
  97057. */
  97058. BackgroundMaterial.StandardReflectance90 = 0.5;
  97059. __decorate([
  97060. BABYLON.serializeAsColor3()
  97061. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97062. __decorate([
  97063. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97064. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97065. __decorate([
  97066. BABYLON.serializeAsColor3()
  97067. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97068. __decorate([
  97069. BABYLON.serialize()
  97070. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97071. __decorate([
  97072. BABYLON.serialize()
  97073. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97074. __decorate([
  97075. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97076. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97077. __decorate([
  97078. BABYLON.serializeAsTexture()
  97079. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97080. __decorate([
  97081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97082. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97083. __decorate([
  97084. BABYLON.serialize()
  97085. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97086. __decorate([
  97087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97088. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97089. __decorate([
  97090. BABYLON.serializeAsTexture()
  97091. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97092. __decorate([
  97093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97094. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97095. __decorate([
  97096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97097. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97098. __decorate([
  97099. BABYLON.serialize()
  97100. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97101. __decorate([
  97102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97103. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97104. __decorate([
  97105. BABYLON.serializeAsVector3()
  97106. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97107. __decorate([
  97108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97109. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97110. __decorate([
  97111. BABYLON.serialize()
  97112. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97113. __decorate([
  97114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97115. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97116. __decorate([
  97117. BABYLON.serialize()
  97118. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97119. __decorate([
  97120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97121. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97122. __decorate([
  97123. BABYLON.serialize()
  97124. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97125. __decorate([
  97126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97127. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97128. __decorate([
  97129. BABYLON.serialize()
  97130. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97131. __decorate([
  97132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97133. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97134. __decorate([
  97135. BABYLON.serialize()
  97136. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97137. __decorate([
  97138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97139. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97140. __decorate([
  97141. BABYLON.serialize()
  97142. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97143. __decorate([
  97144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97145. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97146. __decorate([
  97147. BABYLON.serialize()
  97148. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97149. __decorate([
  97150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97151. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97152. __decorate([
  97153. BABYLON.serialize()
  97154. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97155. __decorate([
  97156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97157. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97158. __decorate([
  97159. BABYLON.serialize()
  97160. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97161. __decorate([
  97162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97163. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97164. __decorate([
  97165. BABYLON.serializeAsImageProcessingConfiguration()
  97166. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97167. return BackgroundMaterial;
  97168. }(BABYLON.PushMaterial));
  97169. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97170. })(BABYLON || (BABYLON = {}));
  97171. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97172. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97173. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97174. s = arguments[i];
  97175. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97176. t[p] = s[p];
  97177. }
  97178. return t;
  97179. };
  97180. var BABYLON;
  97181. (function (BABYLON) {
  97182. /**
  97183. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97184. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97185. * It also helps with the default setup of your imageProcessing configuration.
  97186. */
  97187. var EnvironmentHelper = /** @class */ (function () {
  97188. /**
  97189. * constructor
  97190. * @param options
  97191. * @param scene The scene to add the material to
  97192. */
  97193. function EnvironmentHelper(options, scene) {
  97194. var _this = this;
  97195. this._errorHandler = function (message, exception) {
  97196. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97197. };
  97198. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97199. this._scene = scene;
  97200. this.onErrorObservable = new BABYLON.Observable();
  97201. this._setupBackground();
  97202. this._setupImageProcessing();
  97203. }
  97204. /**
  97205. * Creates the default options for the helper.
  97206. */
  97207. EnvironmentHelper._getDefaultOptions = function () {
  97208. return {
  97209. createGround: true,
  97210. groundSize: 15,
  97211. groundTexture: this._groundTextureCDNUrl,
  97212. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97213. groundOpacity: 0.9,
  97214. enableGroundShadow: true,
  97215. groundShadowLevel: 0.5,
  97216. enableGroundMirror: false,
  97217. groundMirrorSizeRatio: 0.3,
  97218. groundMirrorBlurKernel: 64,
  97219. groundMirrorAmount: 1,
  97220. groundMirrorFresnelWeight: 1,
  97221. groundMirrorFallOffDistance: 0,
  97222. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97223. groundYBias: 0.00001,
  97224. createSkybox: true,
  97225. skyboxSize: 20,
  97226. skyboxTexture: this._skyboxTextureCDNUrl,
  97227. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97228. backgroundYRotation: 0,
  97229. sizeAuto: true,
  97230. rootPosition: BABYLON.Vector3.Zero(),
  97231. setupImageProcessing: true,
  97232. environmentTexture: this._environmentTextureCDNUrl,
  97233. cameraExposure: 0.8,
  97234. cameraContrast: 1.2,
  97235. toneMappingEnabled: true,
  97236. };
  97237. };
  97238. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97239. /**
  97240. * Gets the root mesh created by the helper.
  97241. */
  97242. get: function () {
  97243. return this._rootMesh;
  97244. },
  97245. enumerable: true,
  97246. configurable: true
  97247. });
  97248. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97249. /**
  97250. * Gets the skybox created by the helper.
  97251. */
  97252. get: function () {
  97253. return this._skybox;
  97254. },
  97255. enumerable: true,
  97256. configurable: true
  97257. });
  97258. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97259. /**
  97260. * Gets the skybox texture created by the helper.
  97261. */
  97262. get: function () {
  97263. return this._skyboxTexture;
  97264. },
  97265. enumerable: true,
  97266. configurable: true
  97267. });
  97268. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97269. /**
  97270. * Gets the skybox material created by the helper.
  97271. */
  97272. get: function () {
  97273. return this._skyboxMaterial;
  97274. },
  97275. enumerable: true,
  97276. configurable: true
  97277. });
  97278. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97279. /**
  97280. * Gets the ground mesh created by the helper.
  97281. */
  97282. get: function () {
  97283. return this._ground;
  97284. },
  97285. enumerable: true,
  97286. configurable: true
  97287. });
  97288. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97289. /**
  97290. * Gets the ground texture created by the helper.
  97291. */
  97292. get: function () {
  97293. return this._groundTexture;
  97294. },
  97295. enumerable: true,
  97296. configurable: true
  97297. });
  97298. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97299. /**
  97300. * Gets the ground mirror created by the helper.
  97301. */
  97302. get: function () {
  97303. return this._groundMirror;
  97304. },
  97305. enumerable: true,
  97306. configurable: true
  97307. });
  97308. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97309. /**
  97310. * Gets the ground mirror render list to helps pushing the meshes
  97311. * you wish in the ground reflection.
  97312. */
  97313. get: function () {
  97314. if (this._groundMirror) {
  97315. return this._groundMirror.renderList;
  97316. }
  97317. return null;
  97318. },
  97319. enumerable: true,
  97320. configurable: true
  97321. });
  97322. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97323. /**
  97324. * Gets the ground material created by the helper.
  97325. */
  97326. get: function () {
  97327. return this._groundMaterial;
  97328. },
  97329. enumerable: true,
  97330. configurable: true
  97331. });
  97332. /**
  97333. * Updates the background according to the new options
  97334. * @param options
  97335. */
  97336. EnvironmentHelper.prototype.updateOptions = function (options) {
  97337. var newOptions = __assign({}, this._options, options);
  97338. if (this._ground && !newOptions.createGround) {
  97339. this._ground.dispose();
  97340. this._ground = null;
  97341. }
  97342. if (this._groundMaterial && !newOptions.createGround) {
  97343. this._groundMaterial.dispose();
  97344. this._groundMaterial = null;
  97345. }
  97346. if (this._groundTexture) {
  97347. if (this._options.groundTexture != newOptions.groundTexture) {
  97348. this._groundTexture.dispose();
  97349. this._groundTexture = null;
  97350. }
  97351. }
  97352. if (this._skybox && !newOptions.createSkybox) {
  97353. this._skybox.dispose();
  97354. this._skybox = null;
  97355. }
  97356. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97357. this._skyboxMaterial.dispose();
  97358. this._skyboxMaterial = null;
  97359. }
  97360. if (this._skyboxTexture) {
  97361. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97362. this._skyboxTexture.dispose();
  97363. this._skyboxTexture = null;
  97364. }
  97365. }
  97366. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97367. this._groundMirror.dispose();
  97368. this._groundMirror = null;
  97369. }
  97370. if (this._scene.environmentTexture) {
  97371. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97372. this._scene.environmentTexture.dispose();
  97373. }
  97374. }
  97375. this._options = newOptions;
  97376. this._setupBackground();
  97377. this._setupImageProcessing();
  97378. };
  97379. /**
  97380. * Sets the primary color of all the available elements.
  97381. * @param color the main color to affect to the ground and the background
  97382. */
  97383. EnvironmentHelper.prototype.setMainColor = function (color) {
  97384. if (this.groundMaterial) {
  97385. this.groundMaterial.primaryColor = color;
  97386. }
  97387. if (this.skyboxMaterial) {
  97388. this.skyboxMaterial.primaryColor = color;
  97389. }
  97390. if (this.groundMirror) {
  97391. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97392. }
  97393. };
  97394. /**
  97395. * Setup the image processing according to the specified options.
  97396. */
  97397. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97398. if (this._options.setupImageProcessing) {
  97399. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97400. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97401. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97402. this._setupEnvironmentTexture();
  97403. }
  97404. };
  97405. /**
  97406. * Setup the environment texture according to the specified options.
  97407. */
  97408. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97409. if (this._scene.environmentTexture) {
  97410. return;
  97411. }
  97412. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97413. this._scene.environmentTexture = this._options.environmentTexture;
  97414. return;
  97415. }
  97416. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97417. this._scene.environmentTexture = environmentTexture;
  97418. };
  97419. /**
  97420. * Setup the background according to the specified options.
  97421. */
  97422. EnvironmentHelper.prototype._setupBackground = function () {
  97423. if (!this._rootMesh) {
  97424. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97425. }
  97426. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97427. var sceneSize = this._getSceneSize();
  97428. if (this._options.createGround) {
  97429. this._setupGround(sceneSize);
  97430. this._setupGroundMaterial();
  97431. this._setupGroundDiffuseTexture();
  97432. if (this._options.enableGroundMirror) {
  97433. this._setupGroundMirrorTexture(sceneSize);
  97434. }
  97435. this._setupMirrorInGroundMaterial();
  97436. }
  97437. if (this._options.createSkybox) {
  97438. this._setupSkybox(sceneSize);
  97439. this._setupSkyboxMaterial();
  97440. this._setupSkyboxReflectionTexture();
  97441. }
  97442. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97443. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97444. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97445. };
  97446. /**
  97447. * Get the scene sizes according to the setup.
  97448. */
  97449. EnvironmentHelper.prototype._getSceneSize = function () {
  97450. var _this = this;
  97451. var groundSize = this._options.groundSize;
  97452. var skyboxSize = this._options.skyboxSize;
  97453. var rootPosition = this._options.rootPosition;
  97454. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97455. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97456. }
  97457. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97458. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97459. });
  97460. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97461. if (this._options.sizeAuto) {
  97462. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97463. this._scene.activeCamera.upperRadiusLimit) {
  97464. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97465. skyboxSize = groundSize;
  97466. }
  97467. var sceneDiagonalLenght = sceneDiagonal.length();
  97468. if (sceneDiagonalLenght > groundSize) {
  97469. groundSize = sceneDiagonalLenght * 2;
  97470. skyboxSize = groundSize;
  97471. }
  97472. // 10 % bigger.
  97473. groundSize *= 1.1;
  97474. skyboxSize *= 1.5;
  97475. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97476. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97477. }
  97478. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97479. };
  97480. /**
  97481. * Setup the ground according to the specified options.
  97482. */
  97483. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97484. var _this = this;
  97485. if (!this._ground) {
  97486. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97487. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97488. this._ground.parent = this._rootMesh;
  97489. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97490. }
  97491. this._ground.receiveShadows = this._options.enableGroundShadow;
  97492. };
  97493. /**
  97494. * Setup the ground material according to the specified options.
  97495. */
  97496. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97497. if (!this._groundMaterial) {
  97498. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97499. }
  97500. this._groundMaterial.alpha = this._options.groundOpacity;
  97501. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97502. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97503. this._groundMaterial.primaryColor = this._options.groundColor;
  97504. this._groundMaterial.useRGBColor = false;
  97505. this._groundMaterial.enableNoise = true;
  97506. if (this._ground) {
  97507. this._ground.material = this._groundMaterial;
  97508. }
  97509. };
  97510. /**
  97511. * Setup the ground diffuse texture according to the specified options.
  97512. */
  97513. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97514. if (!this._groundMaterial) {
  97515. return;
  97516. }
  97517. if (this._groundTexture) {
  97518. return;
  97519. }
  97520. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97521. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97522. return;
  97523. }
  97524. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97525. diffuseTexture.gammaSpace = false;
  97526. diffuseTexture.hasAlpha = true;
  97527. this._groundMaterial.diffuseTexture = diffuseTexture;
  97528. };
  97529. /**
  97530. * Setup the ground mirror texture according to the specified options.
  97531. */
  97532. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97533. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97534. if (!this._groundMirror) {
  97535. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97536. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97537. this._groundMirror.anisotropicFilteringLevel = 1;
  97538. this._groundMirror.wrapU = wrapping;
  97539. this._groundMirror.wrapV = wrapping;
  97540. this._groundMirror.gammaSpace = false;
  97541. if (this._groundMirror.renderList) {
  97542. for (var i = 0; i < this._scene.meshes.length; i++) {
  97543. var mesh = this._scene.meshes[i];
  97544. if (mesh !== this._ground &&
  97545. mesh !== this._skybox &&
  97546. mesh !== this._rootMesh) {
  97547. this._groundMirror.renderList.push(mesh);
  97548. }
  97549. }
  97550. }
  97551. }
  97552. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97553. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97554. };
  97555. /**
  97556. * Setup the ground to receive the mirror texture.
  97557. */
  97558. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97559. if (this._groundMaterial) {
  97560. this._groundMaterial.reflectionTexture = this._groundMirror;
  97561. this._groundMaterial.reflectionFresnel = true;
  97562. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97563. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97564. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97565. }
  97566. };
  97567. /**
  97568. * Setup the skybox according to the specified options.
  97569. */
  97570. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97571. var _this = this;
  97572. if (!this._skybox) {
  97573. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97574. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97575. }
  97576. this._skybox.parent = this._rootMesh;
  97577. };
  97578. /**
  97579. * Setup the skybox material according to the specified options.
  97580. */
  97581. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97582. if (!this._skybox) {
  97583. return;
  97584. }
  97585. if (!this._skyboxMaterial) {
  97586. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97587. }
  97588. this._skyboxMaterial.useRGBColor = false;
  97589. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97590. this._skyboxMaterial.enableNoise = true;
  97591. this._skybox.material = this._skyboxMaterial;
  97592. };
  97593. /**
  97594. * Setup the skybox reflection texture according to the specified options.
  97595. */
  97596. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97597. if (!this._skyboxMaterial) {
  97598. return;
  97599. }
  97600. if (this._skyboxTexture) {
  97601. return;
  97602. }
  97603. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97604. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97605. return;
  97606. }
  97607. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97608. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97609. this._skyboxTexture.gammaSpace = false;
  97610. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97611. };
  97612. /**
  97613. * Dispose all the elements created by the Helper.
  97614. */
  97615. EnvironmentHelper.prototype.dispose = function () {
  97616. if (this._groundMaterial) {
  97617. this._groundMaterial.dispose(true, true);
  97618. }
  97619. if (this._skyboxMaterial) {
  97620. this._skyboxMaterial.dispose(true, true);
  97621. }
  97622. this._rootMesh.dispose(false);
  97623. };
  97624. /**
  97625. * Default ground texture URL.
  97626. */
  97627. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97628. /**
  97629. * Default skybox texture URL.
  97630. */
  97631. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97632. /**
  97633. * Default environment texture URL.
  97634. */
  97635. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97636. return EnvironmentHelper;
  97637. }());
  97638. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97639. })(BABYLON || (BABYLON = {}));
  97640. //# sourceMappingURL=babylon.environmentHelper.js.map
  97641. var BABYLON;
  97642. (function (BABYLON) {
  97643. /**
  97644. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97645. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97646. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97647. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97648. */
  97649. var VideoDome = /** @class */ (function (_super) {
  97650. __extends(VideoDome, _super);
  97651. /**
  97652. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97653. * @param name Element's name, child elements will append suffixes for their own names.
  97654. * @param urlsOrVideo
  97655. * @param options An object containing optional or exposed sub element properties:
  97656. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97657. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97658. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97659. * @param options **loop=true** Automatically loop video on end.
  97660. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97661. */
  97662. function VideoDome(name, urlsOrVideo, options, scene) {
  97663. var _this = _super.call(this, name, scene) || this;
  97664. // set defaults and manage values
  97665. name = name || "videoDome";
  97666. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97667. options.clickToPlay = Boolean(options.clickToPlay);
  97668. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97669. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97670. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97671. // create
  97672. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97673. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97674. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97675. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97676. flat: false,
  97677. radius: options.size,
  97678. subdivisions: options.resolution,
  97679. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97680. }, scene);
  97681. // configure material
  97682. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97683. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97684. material.reflectionTexture = _this._videoTexture;
  97685. material.useEquirectangularFOV = true;
  97686. material.fovMultiplier = 1.0;
  97687. // configure mesh
  97688. _this._mesh.material = material;
  97689. _this._mesh.parent = _this;
  97690. // optional configuration
  97691. if (options.clickToPlay) {
  97692. scene.onPointerUp = function () {
  97693. _this._videoTexture.video.play();
  97694. };
  97695. }
  97696. return _this;
  97697. }
  97698. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97699. /**
  97700. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97701. * Also see the options.resolution property.
  97702. */
  97703. get: function () {
  97704. return this._material.fovMultiplier;
  97705. },
  97706. set: function (value) {
  97707. this._material.fovMultiplier = value;
  97708. },
  97709. enumerable: true,
  97710. configurable: true
  97711. });
  97712. /**
  97713. * Releases resources associated with this node.
  97714. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97715. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97716. */
  97717. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97718. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97719. this._videoTexture.dispose();
  97720. this._mesh.dispose();
  97721. this._material.dispose();
  97722. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97723. };
  97724. return VideoDome;
  97725. }(BABYLON.Node));
  97726. BABYLON.VideoDome = VideoDome;
  97727. })(BABYLON || (BABYLON = {}));
  97728. //# sourceMappingURL=babylon.videoDome.js.map
  97729. 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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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"};
  97730. 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};"};
  97731. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97732. globalObject["BABYLON"] = BABYLON;
  97733. //backwards compatibility
  97734. if(typeof earcut !== 'undefined') {
  97735. globalObject["Earcut"] = {
  97736. earcut: earcut
  97737. };
  97738. }
  97739. return BABYLON;
  97740. });