babylon.max.js 4.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines The current define statements for the shader.
  79. * @returns The resulting defines with defines of the current rank removed.
  80. */
  81. EffectFallbacks.prototype.reduce = function (currentDefines) {
  82. // First we try to switch to CPU skinning
  83. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  84. this._mesh.computeBonesUsingShaders = false;
  85. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  86. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. }
  93. }
  94. }
  95. else {
  96. var currentFallbacks = this._defines[this._currentRank];
  97. if (currentFallbacks) {
  98. for (var index = 0; index < currentFallbacks.length; index++) {
  99. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  100. }
  101. }
  102. this._currentRank++;
  103. }
  104. return currentDefines;
  105. };
  106. return EffectFallbacks;
  107. }());
  108. BABYLON.EffectFallbacks = EffectFallbacks;
  109. /**
  110. * Options to be used when creating an effect.
  111. */
  112. var EffectCreationOptions = /** @class */ (function () {
  113. function EffectCreationOptions() {
  114. }
  115. return EffectCreationOptions;
  116. }());
  117. BABYLON.EffectCreationOptions = EffectCreationOptions;
  118. /**
  119. * Effect containing vertex and fragment shader that can be executed on an object.
  120. */
  121. var Effect = /** @class */ (function () {
  122. /**
  123. * Instantiates an effect.
  124. * An effect can be used to create/manage/execute vertex and fragment shaders.
  125. * @param baseName Name of the effect.
  126. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  127. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  128. * @param samplers List of sampler variables that will be passed to the shader.
  129. * @param engine Engine to be used to render the effect
  130. * @param defines Define statements to be added to the shader.
  131. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  132. * @param onCompiled Callback that will be called when the shader is compiled.
  133. * @param onError Callback that will be called if an error occurs during shader compilation.
  134. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  135. */
  136. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  137. if (samplers === void 0) { samplers = null; }
  138. if (defines === void 0) { defines = null; }
  139. if (fallbacks === void 0) { fallbacks = null; }
  140. if (onCompiled === void 0) { onCompiled = null; }
  141. if (onError === void 0) { onError = null; }
  142. var _this = this;
  143. /**
  144. * Unique ID of the effect.
  145. */
  146. this.uniqueId = 0;
  147. /**
  148. * Observable that will be called when the shader is compiled.
  149. */
  150. this.onCompileObservable = new BABYLON.Observable();
  151. /**
  152. * Observable that will be called if an error occurs during shader compilation.
  153. */
  154. this.onErrorObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called when effect is bound.
  157. */
  158. this.onBindObservable = new BABYLON.Observable();
  159. this._uniformBuffersNames = {};
  160. this._isReady = false;
  161. this._compilationError = "";
  162. this.name = baseName;
  163. if (attributesNamesOrOptions.attributes) {
  164. var options = attributesNamesOrOptions;
  165. this._engine = uniformsNamesOrEngine;
  166. this._attributesNames = options.attributes;
  167. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  168. this._samplers = options.samplers;
  169. this.defines = options.defines;
  170. this.onError = options.onError;
  171. this.onCompiled = options.onCompiled;
  172. this._fallbacks = options.fallbacks;
  173. this._indexParameters = options.indexParameters;
  174. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  175. if (options.uniformBuffersNames) {
  176. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  177. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  178. }
  179. }
  180. }
  181. else {
  182. this._engine = engine;
  183. this.defines = defines;
  184. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  185. this._samplers = samplers;
  186. this._attributesNames = attributesNamesOrOptions;
  187. this.onError = onError;
  188. this.onCompiled = onCompiled;
  189. this._indexParameters = indexParameters;
  190. this._fallbacks = fallbacks;
  191. }
  192. this.uniqueId = Effect._uniqueIdSeed++;
  193. var vertexSource;
  194. var fragmentSource;
  195. if (baseName.vertexElement) {
  196. vertexSource = document.getElementById(baseName.vertexElement);
  197. if (!vertexSource) {
  198. vertexSource = baseName.vertexElement;
  199. }
  200. }
  201. else {
  202. vertexSource = baseName.vertex || baseName;
  203. }
  204. if (baseName.fragmentElement) {
  205. fragmentSource = document.getElementById(baseName.fragmentElement);
  206. if (!fragmentSource) {
  207. fragmentSource = baseName.fragmentElement;
  208. }
  209. }
  210. else {
  211. fragmentSource = baseName.fragment || baseName;
  212. }
  213. var finalVertexCode;
  214. this._loadVertexShaderAsync(vertexSource)
  215. .then(function (vertexCode) {
  216. return _this._processIncludesAsync(vertexCode);
  217. })
  218. .then(function (vertexCodeWithIncludes) {
  219. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  220. return _this._loadFragmentShaderAsync(fragmentSource);
  221. })
  222. .then(function (fragmentCode) {
  223. return _this._processIncludesAsync(fragmentCode);
  224. })
  225. .then(function (fragmentCodeWithIncludes) {
  226. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  227. if (baseName) {
  228. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  229. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  230. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  231. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  232. }
  233. else {
  234. _this._vertexSourceCode = finalVertexCode;
  235. _this._fragmentSourceCode = migratedFragmentCode;
  236. }
  237. _this._prepareEffect();
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. return Promise.resolve(vertexCode);
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. return Promise.resolve(vertexBinary);
  358. }
  359. // Is in local store ?
  360. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  361. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  362. }
  363. var vertexShaderUrl;
  364. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  365. vertexShaderUrl = vertex;
  366. }
  367. else {
  368. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  369. }
  370. // Vertex shader
  371. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  372. };
  373. /** @ignore */
  374. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  375. if (BABYLON.Tools.IsWindowObjectExist()) {
  376. // DOM element ?
  377. if (fragment instanceof HTMLElement) {
  378. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  379. return Promise.resolve(fragmentCode);
  380. }
  381. }
  382. // Base64 encoded ?
  383. if (fragment.substr(0, 7) === "base64:") {
  384. var fragmentBinary = window.atob(fragment.substr(7));
  385. return Promise.resolve(fragmentBinary);
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  389. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  390. }
  391. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  392. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  393. }
  394. var fragmentShaderUrl;
  395. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  396. fragmentShaderUrl = fragment;
  397. }
  398. else {
  399. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  400. }
  401. // Fragment shader
  402. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  403. };
  404. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  405. // Rebuild shaders source code
  406. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  407. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  408. vertexCode = prefix + vertexCode;
  409. fragmentCode = prefix + fragmentCode;
  410. // Number lines of shaders source code
  411. var i = 2;
  412. var regex = /\n/gm;
  413. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  414. i = 2;
  415. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. // Dump shaders name and formatted source code
  417. if (this.name.vertexElement) {
  418. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  419. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  420. }
  421. else if (this.name.vertex) {
  422. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  423. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  424. }
  425. else {
  426. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  427. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  428. }
  429. };
  430. ;
  431. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  432. var preparedSourceCode = this._processPrecision(sourceCode);
  433. if (this._engine.webGLVersion == 1) {
  434. return preparedSourceCode;
  435. }
  436. // Already converted
  437. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  438. return preparedSourceCode.replace("#version 300 es", "");
  439. }
  440. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  441. // Remove extensions
  442. // #extension GL_OES_standard_derivatives : enable
  443. // #extension GL_EXT_shader_texture_lod : enable
  444. // #extension GL_EXT_frag_depth : enable
  445. // #extension GL_EXT_draw_buffers : require
  446. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  447. var result = preparedSourceCode.replace(regex, "");
  448. // Migrate to GLSL v300
  449. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  450. result = result.replace(/attribute[ \t]/g, "in ");
  451. result = result.replace(/[ \t]attribute/g, " in");
  452. if (isFragment) {
  453. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  454. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  455. result = result.replace(/texture2D\s*\(/g, "texture(");
  456. result = result.replace(/textureCube\s*\(/g, "texture(");
  457. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  458. result = result.replace(/gl_FragColor/g, "glFragColor");
  459. result = result.replace(/gl_FragData/g, "glFragData");
  460. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  461. }
  462. return result;
  463. };
  464. Effect.prototype._processIncludesAsync = function (sourceCode) {
  465. var _this = this;
  466. return new Promise(function (resolve, reject) {
  467. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  468. var match = regex.exec(sourceCode);
  469. var returnValue = sourceCode;
  470. while (match != null) {
  471. var includeFile = match[1];
  472. // Uniform declaration
  473. if (includeFile.indexOf("__decl__") !== -1) {
  474. includeFile = includeFile.replace(/__decl__/, "");
  475. if (_this._engine.supportsUniformBuffers) {
  476. includeFile = includeFile.replace(/Vertex/, "Ubo");
  477. includeFile = includeFile.replace(/Fragment/, "Ubo");
  478. }
  479. includeFile = includeFile + "Declaration";
  480. }
  481. if (Effect.IncludesShadersStore[includeFile]) {
  482. // Substitution
  483. var includeContent = Effect.IncludesShadersStore[includeFile];
  484. if (match[2]) {
  485. var splits = match[3].split(",");
  486. for (var index = 0; index < splits.length; index += 2) {
  487. var source = new RegExp(splits[index], "g");
  488. var dest = splits[index + 1];
  489. includeContent = includeContent.replace(source, dest);
  490. }
  491. }
  492. if (match[4]) {
  493. var indexString = match[5];
  494. if (indexString.indexOf("..") !== -1) {
  495. var indexSplits = indexString.split("..");
  496. var minIndex = parseInt(indexSplits[0]);
  497. var maxIndex = parseInt(indexSplits[1]);
  498. var sourceIncludeContent = includeContent.slice(0);
  499. includeContent = "";
  500. if (isNaN(maxIndex)) {
  501. maxIndex = _this._indexParameters[indexSplits[1]];
  502. }
  503. for (var i = minIndex; i < maxIndex; i++) {
  504. if (!_this._engine.supportsUniformBuffers) {
  505. // Ubo replacement
  506. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  507. return p1 + "{X}";
  508. });
  509. }
  510. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  511. }
  512. }
  513. else {
  514. if (!_this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent = includeContent.replace(/\{X\}/g, indexString);
  521. }
  522. }
  523. // Replace
  524. returnValue = returnValue.replace(match[0], includeContent);
  525. }
  526. else {
  527. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  528. _this._engine._loadFileAsync(includeShaderUrl)
  529. .then(function (fileContent) {
  530. Effect.IncludesShadersStore[includeFile] = fileContent;
  531. return _this._processIncludesAsync(returnValue);
  532. })
  533. .then(function (returnValue) {
  534. resolve(returnValue);
  535. });
  536. return;
  537. }
  538. match = regex.exec(sourceCode);
  539. }
  540. resolve(returnValue);
  541. });
  542. };
  543. Effect.prototype._processPrecision = function (source) {
  544. if (source.indexOf("precision highp float") === -1) {
  545. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  546. source = "precision mediump float;\n" + source;
  547. }
  548. else {
  549. source = "precision highp float;\n" + source;
  550. }
  551. }
  552. else {
  553. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  554. source = source.replace("precision highp float", "precision mediump float");
  555. }
  556. }
  557. return source;
  558. };
  559. /**
  560. * Recompiles the webGL program
  561. * @param vertexSourceCode The source code for the vertex shader.
  562. * @param fragmentSourceCode The source code for the fragment shader.
  563. * @param onCompiled Callback called when completed.
  564. * @param onError Callback called on error.
  565. */
  566. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  567. var _this = this;
  568. this._isReady = false;
  569. this._vertexSourceCodeOverride = vertexSourceCode;
  570. this._fragmentSourceCodeOverride = fragmentSourceCode;
  571. this.onError = function (effect, error) {
  572. if (onError) {
  573. onError(error);
  574. }
  575. };
  576. this.onCompiled = function () {
  577. var scenes = _this.getEngine().scenes;
  578. for (var i = 0; i < scenes.length; i++) {
  579. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  580. }
  581. if (onCompiled) {
  582. onCompiled(_this._program);
  583. }
  584. };
  585. this._fallbacks = null;
  586. this._prepareEffect();
  587. };
  588. /**
  589. * Gets the uniform locations of the the specified variable names
  590. * @param names THe names of the variables to lookup.
  591. * @returns Array of locations in the same order as variable names.
  592. */
  593. Effect.prototype.getSpecificUniformLocations = function (names) {
  594. var engine = this._engine;
  595. return engine.getUniforms(this._program, names);
  596. };
  597. /**
  598. * Prepares the effect
  599. */
  600. Effect.prototype._prepareEffect = function () {
  601. var attributesNames = this._attributesNames;
  602. var defines = this.defines;
  603. var fallbacks = this._fallbacks;
  604. this._valueCache = {};
  605. var previousProgram = this._program;
  606. try {
  607. var engine = this._engine;
  608. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  609. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  610. }
  611. else {
  612. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  613. }
  614. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  615. if (engine.supportsUniformBuffers) {
  616. for (var name in this._uniformBuffersNames) {
  617. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  618. }
  619. }
  620. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  621. this._attributes = engine.getAttributes(this._program, attributesNames);
  622. var index;
  623. for (index = 0; index < this._samplers.length; index++) {
  624. var sampler = this.getUniform(this._samplers[index]);
  625. if (sampler == null) {
  626. this._samplers.splice(index, 1);
  627. index--;
  628. }
  629. }
  630. engine.bindSamplers(this);
  631. this._compilationError = "";
  632. this._isReady = true;
  633. if (this.onCompiled) {
  634. this.onCompiled(this);
  635. }
  636. this.onCompileObservable.notifyObservers(this);
  637. this.onCompileObservable.clear();
  638. // Unbind mesh reference in fallbacks
  639. if (this._fallbacks) {
  640. this._fallbacks.unBindMesh();
  641. }
  642. if (previousProgram) {
  643. this.getEngine()._deleteProgram(previousProgram);
  644. }
  645. }
  646. catch (e) {
  647. this._compilationError = e.message;
  648. // Let's go through fallbacks then
  649. BABYLON.Tools.Error("Unable to compile effect:");
  650. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  651. return " " + uniform;
  652. }));
  653. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  654. return " " + attribute;
  655. }));
  656. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  657. BABYLON.Tools.Error("Error: " + this._compilationError);
  658. if (previousProgram) {
  659. this._program = previousProgram;
  660. this._isReady = true;
  661. if (this.onError) {
  662. this.onError(this, this._compilationError);
  663. }
  664. this.onErrorObservable.notifyObservers(this);
  665. }
  666. if (fallbacks && fallbacks.isMoreFallbacks) {
  667. BABYLON.Tools.Error("Trying next fallback.");
  668. this.defines = fallbacks.reduce(this.defines);
  669. this._prepareEffect();
  670. }
  671. else {
  672. if (this.onError) {
  673. this.onError(this, this._compilationError);
  674. }
  675. this.onErrorObservable.notifyObservers(this);
  676. this.onErrorObservable.clear();
  677. // Unbind mesh reference in fallbacks
  678. if (this._fallbacks) {
  679. this._fallbacks.unBindMesh();
  680. }
  681. }
  682. }
  683. };
  684. Object.defineProperty(Effect.prototype, "isSupported", {
  685. /**
  686. * Checks if the effect is supported. (Must be called after compilation)
  687. */
  688. get: function () {
  689. return this._compilationError === "";
  690. },
  691. enumerable: true,
  692. configurable: true
  693. });
  694. /**
  695. * Binds a texture to the engine to be used as output of the shader.
  696. * @param channel Name of the output variable.
  697. * @param texture Texture to bind.
  698. */
  699. Effect.prototype._bindTexture = function (channel, texture) {
  700. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  701. };
  702. /**
  703. * Sets a texture on the engine to be used in the shader.
  704. * @param channel Name of the sampler variable.
  705. * @param texture Texture to set.
  706. */
  707. Effect.prototype.setTexture = function (channel, texture) {
  708. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  709. };
  710. /**
  711. * Sets an array of textures on the engine to be used in the shader.
  712. * @param channel Name of the variable.
  713. * @param textures Textures to set.
  714. */
  715. Effect.prototype.setTextureArray = function (channel, textures) {
  716. if (this._samplers.indexOf(channel + "Ex") === -1) {
  717. var initialPos = this._samplers.indexOf(channel);
  718. for (var index = 1; index < textures.length; index++) {
  719. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  720. }
  721. }
  722. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  723. };
  724. /**
  725. * 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)
  726. * @param channel Name of the sampler variable.
  727. * @param postProcess Post process to get the input texture from.
  728. */
  729. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  730. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  731. };
  732. /** @ignore */
  733. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  734. var cache = this._valueCache[uniformName];
  735. var flag = matrix.updateFlag;
  736. if (cache !== undefined && cache === flag) {
  737. return false;
  738. }
  739. this._valueCache[uniformName] = flag;
  740. return true;
  741. };
  742. /** @ignore */
  743. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  744. var cache = this._valueCache[uniformName];
  745. if (!cache) {
  746. cache = [x, y];
  747. this._valueCache[uniformName] = cache;
  748. return true;
  749. }
  750. var changed = false;
  751. if (cache[0] !== x) {
  752. cache[0] = x;
  753. changed = true;
  754. }
  755. if (cache[1] !== y) {
  756. cache[1] = y;
  757. changed = true;
  758. }
  759. return changed;
  760. };
  761. /** @ignore */
  762. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y, z];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. if (cache[2] !== z) {
  779. cache[2] = z;
  780. changed = true;
  781. }
  782. return changed;
  783. };
  784. /** @ignore */
  785. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  786. var cache = this._valueCache[uniformName];
  787. if (!cache) {
  788. cache = [x, y, z, w];
  789. this._valueCache[uniformName] = cache;
  790. return true;
  791. }
  792. var changed = false;
  793. if (cache[0] !== x) {
  794. cache[0] = x;
  795. changed = true;
  796. }
  797. if (cache[1] !== y) {
  798. cache[1] = y;
  799. changed = true;
  800. }
  801. if (cache[2] !== z) {
  802. cache[2] = z;
  803. changed = true;
  804. }
  805. if (cache[3] !== w) {
  806. cache[3] = w;
  807. changed = true;
  808. }
  809. return changed;
  810. };
  811. /**
  812. * Binds a buffer to a uniform.
  813. * @param buffer Buffer to bind.
  814. * @param name Name of the uniform variable to bind to.
  815. */
  816. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  817. var bufferName = this._uniformBuffersNames[name];
  818. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  819. return;
  820. }
  821. Effect._baseCache[bufferName] = buffer;
  822. this._engine.bindUniformBufferBase(buffer, bufferName);
  823. };
  824. /**
  825. * Binds block to a uniform.
  826. * @param blockName Name of the block to bind.
  827. * @param index Index to bind.
  828. */
  829. Effect.prototype.bindUniformBlock = function (blockName, index) {
  830. this._engine.bindUniformBlock(this._program, blockName, index);
  831. };
  832. /**
  833. * Sets an interger value on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param value Value to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setInt = function (uniformName, value) {
  839. var cache = this._valueCache[uniformName];
  840. if (cache !== undefined && cache === value)
  841. return this;
  842. this._valueCache[uniformName] = value;
  843. this._engine.setInt(this.getUniform(uniformName), value);
  844. return this;
  845. };
  846. /**
  847. * Sets an int array on a uniform variable.
  848. * @param uniformName Name of the variable.
  849. * @param array array to be set.
  850. * @returns this effect.
  851. */
  852. Effect.prototype.setIntArray = function (uniformName, array) {
  853. this._valueCache[uniformName] = null;
  854. this._engine.setIntArray(this.getUniform(uniformName), array);
  855. return this;
  856. };
  857. /**
  858. * 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)
  859. * @param uniformName Name of the variable.
  860. * @param array array to be set.
  861. * @returns this effect.
  862. */
  863. Effect.prototype.setIntArray2 = function (uniformName, array) {
  864. this._valueCache[uniformName] = null;
  865. this._engine.setIntArray2(this.getUniform(uniformName), array);
  866. return this;
  867. };
  868. /**
  869. * 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)
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray3 = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray3(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray4 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray4(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an float array on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setFloatArray = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setFloatArray(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * 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)
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets matrices on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrices matrices to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrices = function (uniformName, matrices) {
  985. if (!matrices) {
  986. return this;
  987. }
  988. this._valueCache[uniformName] = null;
  989. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  990. return this;
  991. };
  992. /**
  993. * Sets matrix on a uniform variable.
  994. * @param uniformName Name of the variable.
  995. * @param matrix matrix to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setMatrix = function (uniformName, matrix) {
  999. if (this._cacheMatrix(uniformName, matrix)) {
  1000. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1001. }
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param matrix matrix to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1013. return this;
  1014. };
  1015. /**
  1016. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1017. * @param uniformName Name of the variable.
  1018. * @param matrix matrix to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a float on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param value value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setFloat = function (uniformName, value) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === value)
  1035. return this;
  1036. this._valueCache[uniformName] = value;
  1037. this._engine.setFloat(this.getUniform(uniformName), value);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a boolean on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param bool value to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setBool = function (uniformName, bool) {
  1047. var cache = this._valueCache[uniformName];
  1048. if (cache !== undefined && cache === bool)
  1049. return this;
  1050. this._valueCache[uniformName] = bool;
  1051. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets a Vector2 on a uniform variable.
  1056. * @param uniformName Name of the variable.
  1057. * @param vector2 vector2 to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1061. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1062. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1063. }
  1064. return this;
  1065. };
  1066. /**
  1067. * Sets a float2 on a uniform variable.
  1068. * @param uniformName Name of the variable.
  1069. * @param x First float in float2.
  1070. * @param y Second float in float2.
  1071. * @returns this effect.
  1072. */
  1073. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1074. if (this._cacheFloat2(uniformName, x, y)) {
  1075. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1076. }
  1077. return this;
  1078. };
  1079. /**
  1080. * Sets a Vector3 on a uniform variable.
  1081. * @param uniformName Name of the variable.
  1082. * @param vector3 Value to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1086. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a float3 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param x First float in float3.
  1095. * @param y Second float in float3.
  1096. * @param z Third float in float3.
  1097. * @returns this effect.
  1098. */
  1099. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1100. if (this._cacheFloat3(uniformName, x, y, z)) {
  1101. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1102. }
  1103. return this;
  1104. };
  1105. /**
  1106. * Sets a Vector4 on a uniform variable.
  1107. * @param uniformName Name of the variable.
  1108. * @param vector4 Value to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1112. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1113. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1114. }
  1115. return this;
  1116. };
  1117. /**
  1118. * Sets a float4 on a uniform variable.
  1119. * @param uniformName Name of the variable.
  1120. * @param x First float in float4.
  1121. * @param y Second float in float4.
  1122. * @param z Third float in float4.
  1123. * @param w Fourth float in float4.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1127. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1128. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a Color3 on a uniform variable.
  1134. * @param uniformName Name of the variable.
  1135. * @param color3 Value to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setColor3 = function (uniformName, color3) {
  1139. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1140. this._engine.setColor3(this.getUniform(uniformName), color3);
  1141. }
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a Color4 on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param color3 Value to be set.
  1148. * @param alpha Alpha value to be set.
  1149. * @returns this effect.
  1150. */
  1151. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1152. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1153. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1154. }
  1155. return this;
  1156. };
  1157. /**
  1158. * Resets the cache of effects.
  1159. */
  1160. Effect.ResetCache = function () {
  1161. Effect._baseCache = {};
  1162. };
  1163. Effect._uniqueIdSeed = 0;
  1164. Effect._baseCache = {};
  1165. // Statics
  1166. /**
  1167. * Store of each shader (The can be looked up using effect.key)
  1168. */
  1169. Effect.ShadersStore = {};
  1170. /**
  1171. * Store of each included file for a shader (The can be looked up using effect.key)
  1172. */
  1173. Effect.IncludesShadersStore = {};
  1174. return Effect;
  1175. }());
  1176. BABYLON.Effect = Effect;
  1177. })(BABYLON || (BABYLON = {}));
  1178. //# sourceMappingURL=babylon.effect.js.map
  1179. //# sourceMappingURL=babylon.types.js.map
  1180. var BABYLON;
  1181. (function (BABYLON) {
  1182. var KeyboardEventTypes = /** @class */ (function () {
  1183. function KeyboardEventTypes() {
  1184. }
  1185. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1186. get: function () {
  1187. return KeyboardEventTypes._KEYDOWN;
  1188. },
  1189. enumerable: true,
  1190. configurable: true
  1191. });
  1192. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1193. get: function () {
  1194. return KeyboardEventTypes._KEYUP;
  1195. },
  1196. enumerable: true,
  1197. configurable: true
  1198. });
  1199. KeyboardEventTypes._KEYDOWN = 0x01;
  1200. KeyboardEventTypes._KEYUP = 0x02;
  1201. return KeyboardEventTypes;
  1202. }());
  1203. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1204. var KeyboardInfo = /** @class */ (function () {
  1205. function KeyboardInfo(type, event) {
  1206. this.type = type;
  1207. this.event = event;
  1208. }
  1209. return KeyboardInfo;
  1210. }());
  1211. BABYLON.KeyboardInfo = KeyboardInfo;
  1212. /**
  1213. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1214. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1215. */
  1216. var KeyboardInfoPre = /** @class */ (function (_super) {
  1217. __extends(KeyboardInfoPre, _super);
  1218. function KeyboardInfoPre(type, event) {
  1219. var _this = _super.call(this, type, event) || this;
  1220. _this.skipOnPointerObservable = false;
  1221. return _this;
  1222. }
  1223. return KeyboardInfoPre;
  1224. }(KeyboardInfo));
  1225. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1226. })(BABYLON || (BABYLON = {}));
  1227. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1228. var BABYLON;
  1229. (function (BABYLON) {
  1230. var PointerEventTypes = /** @class */ (function () {
  1231. function PointerEventTypes() {
  1232. }
  1233. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERDOWN;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERUP;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERMOVE;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERWHEEL;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERPICK;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERTAP;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERDOUBLETAP;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. PointerEventTypes._POINTERDOWN = 0x01;
  1283. PointerEventTypes._POINTERUP = 0x02;
  1284. PointerEventTypes._POINTERMOVE = 0x04;
  1285. PointerEventTypes._POINTERWHEEL = 0x08;
  1286. PointerEventTypes._POINTERPICK = 0x10;
  1287. PointerEventTypes._POINTERTAP = 0x20;
  1288. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1289. return PointerEventTypes;
  1290. }());
  1291. BABYLON.PointerEventTypes = PointerEventTypes;
  1292. var PointerInfoBase = /** @class */ (function () {
  1293. function PointerInfoBase(type, event) {
  1294. this.type = type;
  1295. this.event = event;
  1296. }
  1297. return PointerInfoBase;
  1298. }());
  1299. BABYLON.PointerInfoBase = PointerInfoBase;
  1300. /**
  1301. * This class is used to store pointer related info for the onPrePointerObservable event.
  1302. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1303. */
  1304. var PointerInfoPre = /** @class */ (function (_super) {
  1305. __extends(PointerInfoPre, _super);
  1306. function PointerInfoPre(type, event, localX, localY) {
  1307. var _this = _super.call(this, type, event) || this;
  1308. _this.skipOnPointerObservable = false;
  1309. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1310. return _this;
  1311. }
  1312. return PointerInfoPre;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfoPre = PointerInfoPre;
  1315. /**
  1316. * This type contains all the data related to a pointer event in Babylon.js.
  1317. * 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.
  1318. */
  1319. var PointerInfo = /** @class */ (function (_super) {
  1320. __extends(PointerInfo, _super);
  1321. function PointerInfo(type, event, pickInfo) {
  1322. var _this = _super.call(this, type, event) || this;
  1323. _this.pickInfo = pickInfo;
  1324. return _this;
  1325. }
  1326. return PointerInfo;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfo = PointerInfo;
  1329. })(BABYLON || (BABYLON = {}));
  1330. //# sourceMappingURL=babylon.pointerEvents.js.map
  1331. var BABYLON;
  1332. (function (BABYLON) {
  1333. BABYLON.ToGammaSpace = 1 / 2.2;
  1334. BABYLON.ToLinearSpace = 2.2;
  1335. BABYLON.Epsilon = 0.001;
  1336. /**
  1337. * Class used to hold a RBG color
  1338. */
  1339. var Color3 = /** @class */ (function () {
  1340. /**
  1341. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1342. * @param r defines the red component (between 0 and 1, default is 0)
  1343. * @param g defines the green component (between 0 and 1, default is 0)
  1344. * @param b defines the blue component (between 0 and 1, default is 0)
  1345. */
  1346. function Color3(
  1347. /**
  1348. * Defines the red component (between 0 and 1, default is 0)
  1349. */
  1350. r,
  1351. /**
  1352. * Defines the green component (between 0 and 1, default is 0)
  1353. */
  1354. g,
  1355. /**
  1356. * Defines the blue component (between 0 and 1, default is 0)
  1357. */
  1358. b) {
  1359. if (r === void 0) { r = 0; }
  1360. if (g === void 0) { g = 0; }
  1361. if (b === void 0) { b = 0; }
  1362. this.r = r;
  1363. this.g = g;
  1364. this.b = b;
  1365. }
  1366. /**
  1367. * Creates a string with the Color3 current values
  1368. * @returns the string representation of the Color3 object
  1369. */
  1370. Color3.prototype.toString = function () {
  1371. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1372. };
  1373. /**
  1374. * Returns the string "Color3"
  1375. * @returns "Color3"
  1376. */
  1377. Color3.prototype.getClassName = function () {
  1378. return "Color3";
  1379. };
  1380. /**
  1381. * Compute the Color3 hash code
  1382. * @returns an unique number that can be used to hash Color3 objects
  1383. */
  1384. Color3.prototype.getHashCode = function () {
  1385. var hash = this.r || 0;
  1386. hash = (hash * 397) ^ (this.g || 0);
  1387. hash = (hash * 397) ^ (this.b || 0);
  1388. return hash;
  1389. };
  1390. // Operators
  1391. /**
  1392. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1393. * @param array defines the array where to store the r,g,b components
  1394. * @param index defines an optional index in the target array to define where to start storing values
  1395. * @returns the current Color3 object
  1396. */
  1397. Color3.prototype.toArray = function (array, index) {
  1398. if (index === undefined) {
  1399. index = 0;
  1400. }
  1401. array[index] = this.r;
  1402. array[index + 1] = this.g;
  1403. array[index + 2] = this.b;
  1404. return this;
  1405. };
  1406. /**
  1407. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1408. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1409. * @returns a new {BABYLON.Color4} object
  1410. */
  1411. Color3.prototype.toColor4 = function (alpha) {
  1412. if (alpha === void 0) { alpha = 1; }
  1413. return new Color4(this.r, this.g, this.b, alpha);
  1414. };
  1415. /**
  1416. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1417. * @returns the new array
  1418. */
  1419. Color3.prototype.asArray = function () {
  1420. var result = new Array();
  1421. this.toArray(result, 0);
  1422. return result;
  1423. };
  1424. /**
  1425. * Returns the luminance value
  1426. * @returns a float value
  1427. */
  1428. Color3.prototype.toLuminance = function () {
  1429. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1430. };
  1431. /**
  1432. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1433. * @param otherColor defines the second operand
  1434. * @returns the new Color3 object
  1435. */
  1436. Color3.prototype.multiply = function (otherColor) {
  1437. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1438. };
  1439. /**
  1440. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1441. * @param otherColor defines the second operand
  1442. * @param result defines the Color3 object where to store the result
  1443. * @returns the current Color3
  1444. */
  1445. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1446. result.r = this.r * otherColor.r;
  1447. result.g = this.g * otherColor.g;
  1448. result.b = this.b * otherColor.b;
  1449. return this;
  1450. };
  1451. /**
  1452. * Determines equality between Color3 objects
  1453. * @param otherColor defines the second operand
  1454. * @returns true if the rgb values are equal to the passed ones
  1455. */
  1456. Color3.prototype.equals = function (otherColor) {
  1457. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1458. };
  1459. /**
  1460. * Determines equality between the current Color3 object and a set of r,b,g values
  1461. * @param r defines the red component to check
  1462. * @param g defines the green component to check
  1463. * @param b defines the blue component to check
  1464. * @returns true if the rgb values are equal to the passed ones
  1465. */
  1466. Color3.prototype.equalsFloats = function (r, g, b) {
  1467. return this.r === r && this.g === g && this.b === b;
  1468. };
  1469. /**
  1470. * Multiplies in place each rgb value by scale
  1471. * @param scale defines the scaling factor
  1472. * @returns the updated Color3.
  1473. */
  1474. Color3.prototype.scale = function (scale) {
  1475. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1476. };
  1477. /**
  1478. * Multiplies the rgb values by scale and stores the result into "result"
  1479. * @param scale defines the scaling factor
  1480. * @param result defines the Color3 object where to store the result
  1481. * @returns the unmodified current Color3.
  1482. */
  1483. Color3.prototype.scaleToRef = function (scale, result) {
  1484. result.r = this.r * scale;
  1485. result.g = this.g * scale;
  1486. result.b = this.b * scale;
  1487. return this;
  1488. };
  1489. /**
  1490. * Clamps the rgb values by the min and max values and stores the result into "result"
  1491. * @param min defines minimum clamping value (default is 0)
  1492. * @param max defines maximum clamping value (default is 1)
  1493. * @param result defines color to store the result into
  1494. * @returns the original Color3
  1495. */
  1496. Color3.prototype.clampToRef = function (min, max, result) {
  1497. if (min === void 0) { min = 0; }
  1498. if (max === void 0) { max = 1; }
  1499. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1500. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1501. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1502. return this;
  1503. };
  1504. /**
  1505. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1506. * @param otherColor defines the second operand
  1507. * @returns the new Color3
  1508. */
  1509. Color3.prototype.add = function (otherColor) {
  1510. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1511. };
  1512. /**
  1513. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1514. * @param otherColor defines the second operand
  1515. * @param result defines Color3 object to store the result into
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.addToRef = function (otherColor, result) {
  1519. result.r = this.r + otherColor.r;
  1520. result.g = this.g + otherColor.g;
  1521. result.b = this.b + otherColor.b;
  1522. return this;
  1523. };
  1524. /**
  1525. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1526. * @param otherColor defines the second operand
  1527. * @returns the new Color3
  1528. */
  1529. Color3.prototype.subtract = function (otherColor) {
  1530. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1531. };
  1532. /**
  1533. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1534. * @param otherColor defines the second operand
  1535. * @param result defines Color3 object to store the result into
  1536. * @returns the unmodified current Color3
  1537. */
  1538. Color3.prototype.subtractToRef = function (otherColor, result) {
  1539. result.r = this.r - otherColor.r;
  1540. result.g = this.g - otherColor.g;
  1541. result.b = this.b - otherColor.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Copy the current object
  1546. * @returns a new Color3 copied the current one
  1547. */
  1548. Color3.prototype.clone = function () {
  1549. return new Color3(this.r, this.g, this.b);
  1550. };
  1551. /**
  1552. * Copies the rgb values from the source in the current Color3
  1553. * @param source defines the source Color3 object
  1554. * @returns the updated Color3 object
  1555. */
  1556. Color3.prototype.copyFrom = function (source) {
  1557. this.r = source.r;
  1558. this.g = source.g;
  1559. this.b = source.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Updates the Color3 rgb values from the passed floats
  1564. * @param r defines the red component to read from
  1565. * @param g defines the green component to read from
  1566. * @param b defines the blue component to read from
  1567. * @returns the current Color3 object
  1568. */
  1569. Color3.prototype.copyFromFloats = function (r, g, b) {
  1570. this.r = r;
  1571. this.g = g;
  1572. this.b = b;
  1573. return this;
  1574. };
  1575. /**
  1576. * Updates the Color3 rgb values from the passed floats
  1577. * @param r defines the red component to read from
  1578. * @param g defines the green component to read from
  1579. * @param b defines the blue component to read from
  1580. * @returns the current Color3 object
  1581. */
  1582. Color3.prototype.set = function (r, g, b) {
  1583. return this.copyFromFloats(r, g, b);
  1584. };
  1585. /**
  1586. * Compute the Color3 hexadecimal code as a string
  1587. * @returns a string containing the hexadecimal representation of the Color3 object
  1588. */
  1589. Color3.prototype.toHexString = function () {
  1590. var intR = (this.r * 255) | 0;
  1591. var intG = (this.g * 255) | 0;
  1592. var intB = (this.b * 255) | 0;
  1593. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1594. };
  1595. /**
  1596. * Computes a new Color3 converted from the current one to linear space
  1597. * @returns a new Color3 object
  1598. */
  1599. Color3.prototype.toLinearSpace = function () {
  1600. var convertedColor = new Color3();
  1601. this.toLinearSpaceToRef(convertedColor);
  1602. return convertedColor;
  1603. };
  1604. /**
  1605. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1606. * @param convertedColor defines the Color3 object where to store the linear space version
  1607. * @returns the unmodified Color3
  1608. */
  1609. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1610. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1611. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1612. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1613. return this;
  1614. };
  1615. /**
  1616. * Computes a new Color3 converted from the current one to gamma space
  1617. * @returns a new Color3 object
  1618. */
  1619. Color3.prototype.toGammaSpace = function () {
  1620. var convertedColor = new Color3();
  1621. this.toGammaSpaceToRef(convertedColor);
  1622. return convertedColor;
  1623. };
  1624. /**
  1625. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1626. * @param convertedColor defines the Color3 object where to store the gamma space version
  1627. * @returns the unmodified Color3
  1628. */
  1629. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1630. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1631. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1632. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1633. return this;
  1634. };
  1635. // Statics
  1636. /**
  1637. * Creates a new Color3 from the string containing valid hexadecimal values
  1638. * @param hex defines a string containing valid hexadecimal values
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.FromHexString = function (hex) {
  1642. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1643. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1644. return new Color3(0, 0, 0);
  1645. }
  1646. var r = parseInt(hex.substring(1, 3), 16);
  1647. var g = parseInt(hex.substring(3, 5), 16);
  1648. var b = parseInt(hex.substring(5, 7), 16);
  1649. return Color3.FromInts(r, g, b);
  1650. };
  1651. /**
  1652. * Creates a new Vector3 from the starting index of the passed array
  1653. * @param array defines the source array
  1654. * @param offset defines an offset in the source array
  1655. * @returns a new Color3 object
  1656. */
  1657. Color3.FromArray = function (array, offset) {
  1658. if (offset === void 0) { offset = 0; }
  1659. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1660. };
  1661. /**
  1662. * Creates a new Color3 from integer values (< 256)
  1663. * @param r defines the red component to read from (value between 0 and 255)
  1664. * @param g defines the green component to read from (value between 0 and 255)
  1665. * @param b defines the blue component to read from (value between 0 and 255)
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.FromInts = function (r, g, b) {
  1669. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1670. };
  1671. /**
  1672. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1673. * @param start defines the start Color3 value
  1674. * @param end defines the end Color3 value
  1675. * @param amount defines the gradient value between start and end
  1676. * @returns a new Color3 object
  1677. */
  1678. Color3.Lerp = function (start, end, amount) {
  1679. var r = start.r + ((end.r - start.r) * amount);
  1680. var g = start.g + ((end.g - start.g) * amount);
  1681. var b = start.b + ((end.b - start.b) * amount);
  1682. return new Color3(r, g, b);
  1683. };
  1684. /**
  1685. * Returns a Color3 value containing a red color
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.Red = function () { return new Color3(1, 0, 0); };
  1689. /**
  1690. * Returns a Color3 value containing a green color
  1691. * @returns a new Color3 object
  1692. */
  1693. Color3.Green = function () { return new Color3(0, 1, 0); };
  1694. /**
  1695. * Returns a Color3 value containing a blue color
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1699. /**
  1700. * Returns a Color3 value containing a black color
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.Black = function () { return new Color3(0, 0, 0); };
  1704. /**
  1705. * Returns a Color3 value containing a white color
  1706. * @returns a new Color3 object
  1707. */
  1708. Color3.White = function () { return new Color3(1, 1, 1); };
  1709. /**
  1710. * Returns a Color3 value containing a purple color
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1714. /**
  1715. * Returns a Color3 value containing a magenta color
  1716. * @returns a new Color3 object
  1717. */
  1718. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1719. /**
  1720. * Returns a Color3 value containing a yellow color
  1721. * @returns a new Color3 object
  1722. */
  1723. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1724. /**
  1725. * Returns a Color3 value containing a gray color
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1729. /**
  1730. * Returns a Color3 value containing a teal color
  1731. * @returns a new Color3 object
  1732. */
  1733. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1734. /**
  1735. * Returns a Color3 value containing a random color
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1739. return Color3;
  1740. }());
  1741. BABYLON.Color3 = Color3;
  1742. /**
  1743. * Class used to hold a RBGA color
  1744. */
  1745. var Color4 = /** @class */ (function () {
  1746. /**
  1747. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1748. * @param r defines the red component (between 0 and 1, default is 0)
  1749. * @param g defines the green component (between 0 and 1, default is 0)
  1750. * @param b defines the blue component (between 0 and 1, default is 0)
  1751. * @param a defines the alpha component (between 0 and 1, default is 1)
  1752. */
  1753. function Color4(
  1754. /**
  1755. * Defines the red component (between 0 and 1, default is 0)
  1756. */
  1757. r,
  1758. /**
  1759. * Defines the green component (between 0 and 1, default is 0)
  1760. */
  1761. g,
  1762. /**
  1763. * Defines the blue component (between 0 and 1, default is 0)
  1764. */
  1765. b,
  1766. /**
  1767. * Defines the alpha component (between 0 and 1, default is 1)
  1768. */
  1769. a) {
  1770. if (r === void 0) { r = 0; }
  1771. if (g === void 0) { g = 0; }
  1772. if (b === void 0) { b = 0; }
  1773. if (a === void 0) { a = 1; }
  1774. this.r = r;
  1775. this.g = g;
  1776. this.b = b;
  1777. this.a = a;
  1778. }
  1779. // Operators
  1780. /**
  1781. * Adds in place the passed Color4 values to the current Color4 object
  1782. * @param right defines the second operand
  1783. * @returns the current updated Color4 object
  1784. */
  1785. Color4.prototype.addInPlace = function (right) {
  1786. this.r += right.r;
  1787. this.g += right.g;
  1788. this.b += right.b;
  1789. this.a += right.a;
  1790. return this;
  1791. };
  1792. /**
  1793. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1794. * @returns the new array
  1795. */
  1796. Color4.prototype.asArray = function () {
  1797. var result = new Array();
  1798. this.toArray(result, 0);
  1799. return result;
  1800. };
  1801. /**
  1802. * Stores from the starting index in the passed array the Color4 successive values
  1803. * @param array defines the array where to store the r,g,b components
  1804. * @param index defines an optional index in the target array to define where to start storing values
  1805. * @returns the current Color4 object
  1806. */
  1807. Color4.prototype.toArray = function (array, index) {
  1808. if (index === undefined) {
  1809. index = 0;
  1810. }
  1811. array[index] = this.r;
  1812. array[index + 1] = this.g;
  1813. array[index + 2] = this.b;
  1814. array[index + 3] = this.a;
  1815. return this;
  1816. };
  1817. /**
  1818. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1819. * @param right defines the second operand
  1820. * @returns a new Color4 object
  1821. */
  1822. Color4.prototype.add = function (right) {
  1823. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1824. };
  1825. /**
  1826. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1827. * @param right defines the second operand
  1828. * @returns a new Color4 object
  1829. */
  1830. Color4.prototype.subtract = function (right) {
  1831. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1832. };
  1833. /**
  1834. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1835. * @param right defines the second operand
  1836. * @param result defines the Color4 object where to store the result
  1837. * @returns the current Color4 object
  1838. */
  1839. Color4.prototype.subtractToRef = function (right, result) {
  1840. result.r = this.r - right.r;
  1841. result.g = this.g - right.g;
  1842. result.b = this.b - right.b;
  1843. result.a = this.a - right.a;
  1844. return this;
  1845. };
  1846. /**
  1847. * Creates a new Color4 with the current Color4 values multiplied by scale
  1848. * @param scale defines the scaling factor to apply
  1849. * @returns a new Color4 object
  1850. */
  1851. Color4.prototype.scale = function (scale) {
  1852. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1853. };
  1854. /**
  1855. * Multiplies the current Color4 values by scale and stores the result in "result"
  1856. * @param scale defines the scaling factor to apply
  1857. * @param result defines the Color4 object where to store the result
  1858. * @returns the current Color4.
  1859. */
  1860. Color4.prototype.scaleToRef = function (scale, result) {
  1861. result.r = this.r * scale;
  1862. result.g = this.g * scale;
  1863. result.b = this.b * scale;
  1864. result.a = this.a * scale;
  1865. return this;
  1866. };
  1867. /**
  1868. * Clamps the rgb values by the min and max values and stores the result into "result"
  1869. * @param min defines minimum clamping value (default is 0)
  1870. * @param max defines maximum clamping value (default is 1)
  1871. * @param result defines color to store the result into.
  1872. * @returns the cuurent Color4
  1873. */
  1874. Color4.prototype.clampToRef = function (min, max, result) {
  1875. if (min === void 0) { min = 0; }
  1876. if (max === void 0) { max = 1; }
  1877. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1878. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1879. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1880. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1881. return this;
  1882. };
  1883. /**
  1884. * Multipy an Color4 value by another and return a new Color4 object
  1885. * @param color defines the Color4 value to multiply by
  1886. * @returns a new Color4 object
  1887. */
  1888. Color4.prototype.multiply = function (color) {
  1889. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1890. };
  1891. /**
  1892. * Multipy a Color4 value by another and push the result in a reference value
  1893. * @param color defines the Color4 value to multiply by
  1894. * @param result defines the Color4 to fill the result in
  1895. * @returns the result Color4
  1896. */
  1897. Color4.prototype.multiplyToRef = function (color, result) {
  1898. result.r = this.r * color.r;
  1899. result.g = this.g * color.g;
  1900. result.b = this.b * color.b;
  1901. result.a = this.a * color.a;
  1902. return result;
  1903. };
  1904. /**
  1905. * Creates a string with the Color4 current values
  1906. * @returns the string representation of the Color4 object
  1907. */
  1908. Color4.prototype.toString = function () {
  1909. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1910. };
  1911. /**
  1912. * Returns the string "Color4"
  1913. * @returns "Color4"
  1914. */
  1915. Color4.prototype.getClassName = function () {
  1916. return "Color4";
  1917. };
  1918. /**
  1919. * Compute the Color4 hash code
  1920. * @returns an unique number that can be used to hash Color4 objects
  1921. */
  1922. Color4.prototype.getHashCode = function () {
  1923. var hash = this.r || 0;
  1924. hash = (hash * 397) ^ (this.g || 0);
  1925. hash = (hash * 397) ^ (this.b || 0);
  1926. hash = (hash * 397) ^ (this.a || 0);
  1927. return hash;
  1928. };
  1929. /**
  1930. * Creates a new Color4 copied from the current one
  1931. * @returns a new Color4 object
  1932. */
  1933. Color4.prototype.clone = function () {
  1934. return new Color4(this.r, this.g, this.b, this.a);
  1935. };
  1936. /**
  1937. * Copies the passed Color4 values into the current one
  1938. * @param source defines the source Color4 object
  1939. * @returns the current updated Color4 object
  1940. */
  1941. Color4.prototype.copyFrom = function (source) {
  1942. this.r = source.r;
  1943. this.g = source.g;
  1944. this.b = source.b;
  1945. this.a = source.a;
  1946. return this;
  1947. };
  1948. /**
  1949. * Copies the passed float values into the current one
  1950. * @param r defines the red component to read from
  1951. * @param g defines the green component to read from
  1952. * @param b defines the blue component to read from
  1953. * @param a defines the alpha component to read from
  1954. * @returns the current updated Color4 object
  1955. */
  1956. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1957. this.r = r;
  1958. this.g = g;
  1959. this.b = b;
  1960. this.a = a;
  1961. return this;
  1962. };
  1963. /**
  1964. * Copies the passed float values into the current one
  1965. * @param r defines the red component to read from
  1966. * @param g defines the green component to read from
  1967. * @param b defines the blue component to read from
  1968. * @param a defines the alpha component to read from
  1969. * @returns the current updated Color4 object
  1970. */
  1971. Color4.prototype.set = function (r, g, b, a) {
  1972. return this.copyFromFloats(r, g, b, a);
  1973. };
  1974. /**
  1975. * Compute the Color4 hexadecimal code as a string
  1976. * @returns a string containing the hexadecimal representation of the Color4 object
  1977. */
  1978. Color4.prototype.toHexString = function () {
  1979. var intR = (this.r * 255) | 0;
  1980. var intG = (this.g * 255) | 0;
  1981. var intB = (this.b * 255) | 0;
  1982. var intA = (this.a * 255) | 0;
  1983. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1984. };
  1985. /**
  1986. * Computes a new Color4 converted from the current one to linear space
  1987. * @returns a new Color4 object
  1988. */
  1989. Color4.prototype.toLinearSpace = function () {
  1990. var convertedColor = new Color4();
  1991. this.toLinearSpaceToRef(convertedColor);
  1992. return convertedColor;
  1993. };
  1994. /**
  1995. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1996. * @param convertedColor defines the Color4 object where to store the linear space version
  1997. * @returns the unmodified Color4
  1998. */
  1999. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2000. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2001. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2002. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2003. convertedColor.a = this.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Computes a new Color4 converted from the current one to gamma space
  2008. * @returns a new Color4 object
  2009. */
  2010. Color4.prototype.toGammaSpace = function () {
  2011. var convertedColor = new Color4();
  2012. this.toGammaSpaceToRef(convertedColor);
  2013. return convertedColor;
  2014. };
  2015. /**
  2016. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2017. * @param convertedColor defines the Color4 object where to store the gamma space version
  2018. * @returns the unmodified Color4
  2019. */
  2020. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2021. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2022. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2023. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2024. convertedColor.a = this.a;
  2025. return this;
  2026. };
  2027. // Statics
  2028. /**
  2029. * Creates a new Color4 from the string containing valid hexadecimal values
  2030. * @param hex defines a string containing valid hexadecimal values
  2031. * @returns a new Color4 object
  2032. */
  2033. Color4.FromHexString = function (hex) {
  2034. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2035. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2036. return new Color4(0.0, 0.0, 0.0, 0.0);
  2037. }
  2038. var r = parseInt(hex.substring(1, 3), 16);
  2039. var g = parseInt(hex.substring(3, 5), 16);
  2040. var b = parseInt(hex.substring(5, 7), 16);
  2041. var a = parseInt(hex.substring(7, 9), 16);
  2042. return Color4.FromInts(r, g, b, a);
  2043. };
  2044. /**
  2045. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2046. * @param left defines the start value
  2047. * @param right defines the end value
  2048. * @param amount defines the gradient factor
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.Lerp = function (left, right, amount) {
  2052. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2053. Color4.LerpToRef(left, right, amount, result);
  2054. return result;
  2055. };
  2056. /**
  2057. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2058. * @param left defines the start value
  2059. * @param right defines the end value
  2060. * @param amount defines the gradient factor
  2061. * @param result defines the Color4 object where to store data
  2062. */
  2063. Color4.LerpToRef = function (left, right, amount, result) {
  2064. result.r = left.r + (right.r - left.r) * amount;
  2065. result.g = left.g + (right.g - left.g) * amount;
  2066. result.b = left.b + (right.b - left.b) * amount;
  2067. result.a = left.a + (right.a - left.a) * amount;
  2068. };
  2069. /**
  2070. * Creates a new Color4 from the starting index element of the passed array
  2071. * @param array defines the source array to read from
  2072. * @param offset defines the offset in the source array
  2073. * @returns a new Color4 object
  2074. */
  2075. Color4.FromArray = function (array, offset) {
  2076. if (offset === void 0) { offset = 0; }
  2077. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2078. };
  2079. /**
  2080. * Creates a new Color3 from integer values (< 256)
  2081. * @param r defines the red component to read from (value between 0 and 255)
  2082. * @param g defines the green component to read from (value between 0 and 255)
  2083. * @param b defines the blue component to read from (value between 0 and 255)
  2084. * @param a defines the alpha component to read from (value between 0 and 255)
  2085. * @returns a new Color3 object
  2086. */
  2087. Color4.FromInts = function (r, g, b, a) {
  2088. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2089. };
  2090. /**
  2091. * Check the content of a given array and convert it to an array containing RGBA data
  2092. * If the original array was already containing count * 4 values then it is returned directly
  2093. * @param colors defines the array to check
  2094. * @param count defines the number of RGBA data to expect
  2095. * @returns an array containing count * 4 values (RGBA)
  2096. */
  2097. Color4.CheckColors4 = function (colors, count) {
  2098. // Check if color3 was used
  2099. if (colors.length === count * 3) {
  2100. var colors4 = [];
  2101. for (var index = 0; index < colors.length; index += 3) {
  2102. var newIndex = (index / 3) * 4;
  2103. colors4[newIndex] = colors[index];
  2104. colors4[newIndex + 1] = colors[index + 1];
  2105. colors4[newIndex + 2] = colors[index + 2];
  2106. colors4[newIndex + 3] = 1.0;
  2107. }
  2108. return colors4;
  2109. }
  2110. return colors;
  2111. };
  2112. return Color4;
  2113. }());
  2114. BABYLON.Color4 = Color4;
  2115. var Vector2 = /** @class */ (function () {
  2116. /**
  2117. * Creates a new Vector2 from the passed x and y coordinates.
  2118. */
  2119. function Vector2(x, y) {
  2120. this.x = x;
  2121. this.y = y;
  2122. }
  2123. /**
  2124. * Returns a string with the Vector2 coordinates.
  2125. */
  2126. Vector2.prototype.toString = function () {
  2127. return "{X: " + this.x + " Y:" + this.y + "}";
  2128. };
  2129. /**
  2130. * Returns the string "Vector2"
  2131. */
  2132. Vector2.prototype.getClassName = function () {
  2133. return "Vector2";
  2134. };
  2135. /**
  2136. * Returns the Vector2 hash code as a number.
  2137. */
  2138. Vector2.prototype.getHashCode = function () {
  2139. var hash = this.x || 0;
  2140. hash = (hash * 397) ^ (this.y || 0);
  2141. return hash;
  2142. };
  2143. // Operators
  2144. /**
  2145. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2146. * Returns the Vector2.
  2147. */
  2148. Vector2.prototype.toArray = function (array, index) {
  2149. if (index === void 0) { index = 0; }
  2150. array[index] = this.x;
  2151. array[index + 1] = this.y;
  2152. return this;
  2153. };
  2154. /**
  2155. * Returns a new array with 2 elements : the Vector2 coordinates.
  2156. */
  2157. Vector2.prototype.asArray = function () {
  2158. var result = new Array();
  2159. this.toArray(result, 0);
  2160. return result;
  2161. };
  2162. /**
  2163. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2164. * Returns the updated Vector2.
  2165. */
  2166. Vector2.prototype.copyFrom = function (source) {
  2167. this.x = source.x;
  2168. this.y = source.y;
  2169. return this;
  2170. };
  2171. /**
  2172. * Sets the Vector2 coordinates with the passed floats.
  2173. * Returns the updated Vector2.
  2174. */
  2175. Vector2.prototype.copyFromFloats = function (x, y) {
  2176. this.x = x;
  2177. this.y = y;
  2178. return this;
  2179. };
  2180. /**
  2181. * Sets the Vector2 coordinates with the passed floats.
  2182. * Returns the updated Vector2.
  2183. */
  2184. Vector2.prototype.set = function (x, y) {
  2185. return this.copyFromFloats(x, y);
  2186. };
  2187. /**
  2188. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2189. */
  2190. Vector2.prototype.add = function (otherVector) {
  2191. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2192. };
  2193. /**
  2194. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2195. * Returns the Vector2.
  2196. */
  2197. Vector2.prototype.addToRef = function (otherVector, result) {
  2198. result.x = this.x + otherVector.x;
  2199. result.y = this.y + otherVector.y;
  2200. return this;
  2201. };
  2202. /**
  2203. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2204. * Returns the updated Vector2.
  2205. */
  2206. Vector2.prototype.addInPlace = function (otherVector) {
  2207. this.x += otherVector.x;
  2208. this.y += otherVector.y;
  2209. return this;
  2210. };
  2211. /**
  2212. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2213. */
  2214. Vector2.prototype.addVector3 = function (otherVector) {
  2215. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2216. };
  2217. /**
  2218. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2219. */
  2220. Vector2.prototype.subtract = function (otherVector) {
  2221. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2222. };
  2223. /**
  2224. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2225. * Returns the Vector2.
  2226. */
  2227. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2228. result.x = this.x - otherVector.x;
  2229. result.y = this.y - otherVector.y;
  2230. return this;
  2231. };
  2232. /**
  2233. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2234. * Returns the updated Vector2.
  2235. */
  2236. Vector2.prototype.subtractInPlace = function (otherVector) {
  2237. this.x -= otherVector.x;
  2238. this.y -= otherVector.y;
  2239. return this;
  2240. };
  2241. /**
  2242. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2243. * Returns the updated Vector2.
  2244. */
  2245. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2246. this.x *= otherVector.x;
  2247. this.y *= otherVector.y;
  2248. return this;
  2249. };
  2250. /**
  2251. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2252. */
  2253. Vector2.prototype.multiply = function (otherVector) {
  2254. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2255. };
  2256. /**
  2257. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2258. * Returns the Vector2.
  2259. */
  2260. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2261. result.x = this.x * otherVector.x;
  2262. result.y = this.y * otherVector.y;
  2263. return this;
  2264. };
  2265. /**
  2266. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2267. */
  2268. Vector2.prototype.multiplyByFloats = function (x, y) {
  2269. return new Vector2(this.x * x, this.y * y);
  2270. };
  2271. /**
  2272. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2273. */
  2274. Vector2.prototype.divide = function (otherVector) {
  2275. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2279. * Returns the Vector2.
  2280. */
  2281. Vector2.prototype.divideToRef = function (otherVector, result) {
  2282. result.x = this.x / otherVector.x;
  2283. result.y = this.y / otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Divides the current Vector3 coordinates by the passed ones.
  2288. * Returns the updated Vector3.
  2289. */
  2290. Vector2.prototype.divideInPlace = function (otherVector) {
  2291. return this.divideToRef(otherVector, this);
  2292. };
  2293. /**
  2294. * Returns a new Vector2 with current Vector2 negated coordinates.
  2295. */
  2296. Vector2.prototype.negate = function () {
  2297. return new Vector2(-this.x, -this.y);
  2298. };
  2299. /**
  2300. * Multiply the Vector2 coordinates by scale.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.scaleInPlace = function (scale) {
  2304. this.x *= scale;
  2305. this.y *= scale;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2310. */
  2311. Vector2.prototype.scale = function (scale) {
  2312. return new Vector2(this.x * scale, this.y * scale);
  2313. };
  2314. /**
  2315. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2316. */
  2317. Vector2.prototype.equals = function (otherVector) {
  2318. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2319. };
  2320. /**
  2321. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2322. */
  2323. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2324. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2325. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2326. };
  2327. // Properties
  2328. /**
  2329. * Returns the vector length (float).
  2330. */
  2331. Vector2.prototype.length = function () {
  2332. return Math.sqrt(this.x * this.x + this.y * this.y);
  2333. };
  2334. /**
  2335. * Returns the vector squared length (float);
  2336. */
  2337. Vector2.prototype.lengthSquared = function () {
  2338. return (this.x * this.x + this.y * this.y);
  2339. };
  2340. // Methods
  2341. /**
  2342. * Normalize the vector.
  2343. * Returns the updated Vector2.
  2344. */
  2345. Vector2.prototype.normalize = function () {
  2346. var len = this.length();
  2347. if (len === 0)
  2348. return this;
  2349. var num = 1.0 / len;
  2350. this.x *= num;
  2351. this.y *= num;
  2352. return this;
  2353. };
  2354. /**
  2355. * Returns a new Vector2 copied from the Vector2.
  2356. */
  2357. Vector2.prototype.clone = function () {
  2358. return new Vector2(this.x, this.y);
  2359. };
  2360. // Statics
  2361. /**
  2362. * Returns a new Vector2(0, 0)
  2363. */
  2364. Vector2.Zero = function () {
  2365. return new Vector2(0, 0);
  2366. };
  2367. /**
  2368. * Returns a new Vector2(1, 1)
  2369. */
  2370. Vector2.One = function () {
  2371. return new Vector2(1, 1);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set from the passed index element of the passed array.
  2375. */
  2376. Vector2.FromArray = function (array, offset) {
  2377. if (offset === void 0) { offset = 0; }
  2378. return new Vector2(array[offset], array[offset + 1]);
  2379. };
  2380. /**
  2381. * Sets "result" from the passed index element of the passed array.
  2382. */
  2383. Vector2.FromArrayToRef = function (array, offset, result) {
  2384. result.x = array[offset];
  2385. result.y = array[offset + 1];
  2386. };
  2387. /**
  2388. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2389. */
  2390. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2391. var squared = amount * amount;
  2392. var cubed = amount * squared;
  2393. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2394. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2395. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2396. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2397. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2398. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * 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".
  2403. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2404. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2405. */
  2406. Vector2.Clamp = function (value, min, max) {
  2407. var x = value.x;
  2408. x = (x > max.x) ? max.x : x;
  2409. x = (x < min.x) ? min.x : x;
  2410. var y = value.y;
  2411. y = (y > max.y) ? max.y : y;
  2412. y = (y < min.y) ? min.y : y;
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2417. */
  2418. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2419. var squared = amount * amount;
  2420. var cubed = amount * squared;
  2421. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2422. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2423. var part3 = (cubed - (2.0 * squared)) + amount;
  2424. var part4 = cubed - squared;
  2425. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2426. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2427. return new Vector2(x, y);
  2428. };
  2429. /**
  2430. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2431. */
  2432. Vector2.Lerp = function (start, end, amount) {
  2433. var x = start.x + ((end.x - start.x) * amount);
  2434. var y = start.y + ((end.y - start.y) * amount);
  2435. return new Vector2(x, y);
  2436. };
  2437. /**
  2438. * Returns the dot product (float) of the vector "left" and the vector "right".
  2439. */
  2440. Vector2.Dot = function (left, right) {
  2441. return left.x * right.x + left.y * right.y;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 equal to the normalized passed vector.
  2445. */
  2446. Vector2.Normalize = function (vector) {
  2447. var newVector = vector.clone();
  2448. newVector.normalize();
  2449. return newVector;
  2450. };
  2451. /**
  2452. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2453. */
  2454. Vector2.Minimize = function (left, right) {
  2455. var x = (left.x < right.x) ? left.x : right.x;
  2456. var y = (left.y < right.y) ? left.y : right.y;
  2457. return new Vector2(x, y);
  2458. };
  2459. /**
  2460. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2461. */
  2462. Vector2.Maximize = function (left, right) {
  2463. var x = (left.x > right.x) ? left.x : right.x;
  2464. var y = (left.y > right.y) ? left.y : right.y;
  2465. return new Vector2(x, y);
  2466. };
  2467. /**
  2468. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2469. */
  2470. Vector2.Transform = function (vector, transformation) {
  2471. var r = Vector2.Zero();
  2472. Vector2.TransformToRef(vector, transformation, r);
  2473. return r;
  2474. };
  2475. /**
  2476. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2477. */
  2478. Vector2.TransformToRef = function (vector, transformation, result) {
  2479. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2480. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2481. result.x = x;
  2482. result.y = y;
  2483. };
  2484. /**
  2485. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2486. */
  2487. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2488. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2489. var sign = a < 0 ? -1 : 1;
  2490. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2491. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2492. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2493. };
  2494. /**
  2495. * Returns the distance (float) between the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Distance = function (value1, value2) {
  2498. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2499. };
  2500. /**
  2501. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2502. */
  2503. Vector2.DistanceSquared = function (value1, value2) {
  2504. var x = value1.x - value2.x;
  2505. var y = value1.y - value2.y;
  2506. return (x * x) + (y * y);
  2507. };
  2508. /**
  2509. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2510. */
  2511. Vector2.Center = function (value1, value2) {
  2512. var center = value1.add(value2);
  2513. center.scaleInPlace(0.5);
  2514. return center;
  2515. };
  2516. /**
  2517. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2518. */
  2519. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2520. var l2 = Vector2.DistanceSquared(segA, segB);
  2521. if (l2 === 0.0) {
  2522. return Vector2.Distance(p, segA);
  2523. }
  2524. var v = segB.subtract(segA);
  2525. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2526. var proj = segA.add(v.multiplyByFloats(t, t));
  2527. return Vector2.Distance(p, proj);
  2528. };
  2529. return Vector2;
  2530. }());
  2531. BABYLON.Vector2 = Vector2;
  2532. /**
  2533. * Classed used to store (x,y,z) vector representation
  2534. * A Vector3 is the main object used in 3D geometry
  2535. * It can represent etiher the coordinates of a point the space, either a direction
  2536. * Reminder: Babylon.js uses a left handed forward facing system
  2537. */
  2538. var Vector3 = /** @class */ (function () {
  2539. /**
  2540. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2541. * @param x defines the first coordinates (on X axis)
  2542. * @param y defines the second coordinates (on Y axis)
  2543. * @param z defines the third coordinates (on Z axis)
  2544. */
  2545. function Vector3(
  2546. /**
  2547. * Defines the first coordinates (on X axis)
  2548. */
  2549. x,
  2550. /**
  2551. * Defines the second coordinates (on Y axis)
  2552. */
  2553. y,
  2554. /**
  2555. * Defines the third coordinates (on Z axis)
  2556. */
  2557. z) {
  2558. this.x = x;
  2559. this.y = y;
  2560. this.z = z;
  2561. }
  2562. /**
  2563. * Creates a string representation of the Vector3
  2564. * @returns a string with the Vector3 coordinates.
  2565. */
  2566. Vector3.prototype.toString = function () {
  2567. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2568. };
  2569. /**
  2570. * Gets the class name
  2571. * @returns the string "Vector3"
  2572. */
  2573. Vector3.prototype.getClassName = function () {
  2574. return "Vector3";
  2575. };
  2576. /**
  2577. * Creates the Vector3 hash code
  2578. * @returns a number which tends to be unique between Vector3 instances
  2579. */
  2580. Vector3.prototype.getHashCode = function () {
  2581. var hash = this.x || 0;
  2582. hash = (hash * 397) ^ (this.y || 0);
  2583. hash = (hash * 397) ^ (this.z || 0);
  2584. return hash;
  2585. };
  2586. // Operators
  2587. /**
  2588. * Creates an array containing three elements : the coordinates of the Vector3
  2589. * @returns a new array of numbers
  2590. */
  2591. Vector3.prototype.asArray = function () {
  2592. var result = [];
  2593. this.toArray(result, 0);
  2594. return result;
  2595. };
  2596. /**
  2597. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2598. * @param array defines the destination array
  2599. * @param index defines the offset in the destination array
  2600. * @returns the current Vector3
  2601. */
  2602. Vector3.prototype.toArray = function (array, index) {
  2603. if (index === void 0) { index = 0; }
  2604. array[index] = this.x;
  2605. array[index + 1] = this.y;
  2606. array[index + 2] = this.z;
  2607. return this;
  2608. };
  2609. /**
  2610. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2611. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2612. */
  2613. Vector3.prototype.toQuaternion = function () {
  2614. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2615. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2616. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2617. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2618. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2619. var cosy = Math.cos(this.y * 0.5);
  2620. var siny = Math.sin(this.y * 0.5);
  2621. result.x = coszMinusx * siny;
  2622. result.y = -sinzMinusx * siny;
  2623. result.z = sinxPlusz * cosy;
  2624. result.w = cosxPlusz * cosy;
  2625. return result;
  2626. };
  2627. /**
  2628. * Adds the passed vector to the current Vector3
  2629. * @param otherVector defines the second operand
  2630. * @returns the current updated Vector3
  2631. */
  2632. Vector3.prototype.addInPlace = function (otherVector) {
  2633. this.x += otherVector.x;
  2634. this.y += otherVector.y;
  2635. this.z += otherVector.z;
  2636. return this;
  2637. };
  2638. /**
  2639. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2640. * @param otherVector defines the second operand
  2641. * @returns the resulting Vector3
  2642. */
  2643. Vector3.prototype.add = function (otherVector) {
  2644. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2645. };
  2646. /**
  2647. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2648. * @param otherVector defines the second operand
  2649. * @param result defines the Vector3 object where to store the result
  2650. * @returns the current Vector3
  2651. */
  2652. Vector3.prototype.addToRef = function (otherVector, result) {
  2653. result.x = this.x + otherVector.x;
  2654. result.y = this.y + otherVector.y;
  2655. result.z = this.z + otherVector.z;
  2656. return this;
  2657. };
  2658. /**
  2659. * Subtract the passed vector from the current Vector3
  2660. * @param otherVector defines the second operand
  2661. * @returns the current updated Vector3
  2662. */
  2663. Vector3.prototype.subtractInPlace = function (otherVector) {
  2664. this.x -= otherVector.x;
  2665. this.y -= otherVector.y;
  2666. this.z -= otherVector.z;
  2667. return this;
  2668. };
  2669. /**
  2670. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2671. * @param otherVector defines the second operand
  2672. * @returns the resulting Vector3
  2673. */
  2674. Vector3.prototype.subtract = function (otherVector) {
  2675. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2676. };
  2677. /**
  2678. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2679. * @param otherVector defines the second operand
  2680. * @param result defines the Vector3 object where to store the result
  2681. * @returns the current Vector3
  2682. */
  2683. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2684. result.x = this.x - otherVector.x;
  2685. result.y = this.y - otherVector.y;
  2686. result.z = this.z - otherVector.z;
  2687. return this;
  2688. };
  2689. /**
  2690. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2691. * @param x defines the x coordinate of the operand
  2692. * @param y defines the y coordinate of the operand
  2693. * @param z defines the z coordinate of the operand
  2694. * @returns the resulting Vector3
  2695. */
  2696. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2697. return new Vector3(this.x - x, this.y - y, this.z - z);
  2698. };
  2699. /**
  2700. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2701. * @param x defines the x coordinate of the operand
  2702. * @param y defines the y coordinate of the operand
  2703. * @param z defines the z coordinate of the operand
  2704. * @param result defines the Vector3 object where to store the result
  2705. * @returns the current Vector3
  2706. */
  2707. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2708. result.x = this.x - x;
  2709. result.y = this.y - y;
  2710. result.z = this.z - z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2715. * @returns a new Vector3
  2716. */
  2717. Vector3.prototype.negate = function () {
  2718. return new Vector3(-this.x, -this.y, -this.z);
  2719. };
  2720. /**
  2721. * Multiplies the Vector3 coordinates by the float "scale"
  2722. * @param scale defines the multiplier factor
  2723. * @returns the current updated Vector3
  2724. */
  2725. Vector3.prototype.scaleInPlace = function (scale) {
  2726. this.x *= scale;
  2727. this.y *= scale;
  2728. this.z *= scale;
  2729. return this;
  2730. };
  2731. /**
  2732. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2733. * @param scale defines the multiplier factor
  2734. * @returns a new Vector3
  2735. */
  2736. Vector3.prototype.scale = function (scale) {
  2737. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2738. };
  2739. /**
  2740. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2741. * @param scale defines the multiplier factor
  2742. * @param result defines the Vector3 object where to store the result
  2743. * @returns the current Vector3
  2744. */
  2745. Vector3.prototype.scaleToRef = function (scale, result) {
  2746. result.x = this.x * scale;
  2747. result.y = this.y * scale;
  2748. result.z = this.z * scale;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2753. * @param otherVector defines the second operand
  2754. * @returns true if both vectors are equals
  2755. */
  2756. Vector3.prototype.equals = function (otherVector) {
  2757. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2758. };
  2759. /**
  2760. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2761. * @param otherVector defines the second operand
  2762. * @param epsilon defines the minimal distance to define values as equals
  2763. * @returns true if both vectors are distant less than epsilon
  2764. */
  2765. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2766. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2767. 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);
  2768. };
  2769. /**
  2770. * Returns true if the current Vector3 coordinates equals the passed floats
  2771. * @param x defines the x coordinate of the operand
  2772. * @param y defines the y coordinate of the operand
  2773. * @param z defines the z coordinate of the operand
  2774. * @returns true if both vectors are equals
  2775. */
  2776. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2777. return this.x === x && this.y === y && this.z === z;
  2778. };
  2779. /**
  2780. * Multiplies the current Vector3 coordinates by the passed ones
  2781. * @param otherVector defines the second operand
  2782. * @returns the current updated Vector3
  2783. */
  2784. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2785. this.x *= otherVector.x;
  2786. this.y *= otherVector.y;
  2787. this.z *= otherVector.z;
  2788. return this;
  2789. };
  2790. /**
  2791. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2792. * @param otherVector defines the second operand
  2793. * @returns the new Vector3
  2794. */
  2795. Vector3.prototype.multiply = function (otherVector) {
  2796. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2797. };
  2798. /**
  2799. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2800. * @param otherVector defines the second operand
  2801. * @param result defines the Vector3 object where to store the result
  2802. * @returns the current Vector3
  2803. */
  2804. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2805. result.x = this.x * otherVector.x;
  2806. result.y = this.y * otherVector.y;
  2807. result.z = this.z * otherVector.z;
  2808. return this;
  2809. };
  2810. /**
  2811. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2812. * @param x defines the x coordinate of the operand
  2813. * @param y defines the y coordinate of the operand
  2814. * @param z defines the z coordinate of the operand
  2815. * @returns the new Vector3
  2816. */
  2817. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2818. return new Vector3(this.x * x, this.y * y, this.z * z);
  2819. };
  2820. /**
  2821. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2822. * @param otherVector defines the second operand
  2823. * @returns the new Vector3
  2824. */
  2825. Vector3.prototype.divide = function (otherVector) {
  2826. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2827. };
  2828. /**
  2829. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2830. * @param otherVector defines the second operand
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the current Vector3
  2833. */
  2834. Vector3.prototype.divideToRef = function (otherVector, result) {
  2835. result.x = this.x / otherVector.x;
  2836. result.y = this.y / otherVector.y;
  2837. result.z = this.z / otherVector.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Divides the current Vector3 coordinates by the passed ones.
  2842. * @param otherVector defines the second operand
  2843. * @returns the current updated Vector3
  2844. */
  2845. Vector3.prototype.divideInPlace = function (otherVector) {
  2846. return this.divideToRef(otherVector, this);
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.minimizeInPlace = function (other) {
  2854. if (other.x < this.x)
  2855. this.x = other.x;
  2856. if (other.y < this.y)
  2857. this.y = other.y;
  2858. if (other.z < this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2864. * @param other defines the second operand
  2865. * @returns the current updated Vector3
  2866. */
  2867. Vector3.prototype.maximizeInPlace = function (other) {
  2868. if (other.x > this.x)
  2869. this.x = other.x;
  2870. if (other.y > this.y)
  2871. this.y = other.y;
  2872. if (other.z > this.z)
  2873. this.z = other.z;
  2874. return this;
  2875. };
  2876. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2877. /**
  2878. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2879. */
  2880. get: function () {
  2881. var absX = Math.abs(this.x);
  2882. var absY = Math.abs(this.y);
  2883. if (absX !== absY) {
  2884. return true;
  2885. }
  2886. var absZ = Math.abs(this.z);
  2887. if (absX !== absZ) {
  2888. return true;
  2889. }
  2890. if (absY !== absZ) {
  2891. return true;
  2892. }
  2893. return false;
  2894. },
  2895. enumerable: true,
  2896. configurable: true
  2897. });
  2898. // Properties
  2899. /**
  2900. * Gets the length of the Vector3
  2901. * @returns the length of the Vecto3
  2902. */
  2903. Vector3.prototype.length = function () {
  2904. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2905. };
  2906. /**
  2907. * Gets the squared length of the Vector3
  2908. * @returns squared length of the Vector3
  2909. */
  2910. Vector3.prototype.lengthSquared = function () {
  2911. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2912. };
  2913. /**
  2914. * Normalize the current Vector3.
  2915. * Please note that this is an in place operation.
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.normalize = function () {
  2919. var len = this.length();
  2920. if (len === 0 || len === 1.0)
  2921. return this;
  2922. var num = 1.0 / len;
  2923. this.x *= num;
  2924. this.y *= num;
  2925. this.z *= num;
  2926. return this;
  2927. };
  2928. /**
  2929. * Normalize the current Vector3 to a new vector
  2930. * @returns the new Vector3
  2931. */
  2932. Vector3.prototype.normalizeToNew = function () {
  2933. var normalized = new Vector3(0, 0, 0);
  2934. this.normalizeToRef(normalized);
  2935. return normalized;
  2936. };
  2937. /**
  2938. * Normalize the current Vector3 to the reference
  2939. * @param reference define the Vector3 to update
  2940. * @returns the updated Vector3
  2941. */
  2942. Vector3.prototype.normalizeToRef = function (reference) {
  2943. var len = this.length();
  2944. if (len === 0 || len === 1.0) {
  2945. reference.set(this.x, this.y, this.z);
  2946. return reference;
  2947. }
  2948. var scale = 1.0 / len;
  2949. this.scaleToRef(scale, reference);
  2950. return reference;
  2951. };
  2952. /**
  2953. * Creates a new Vector3 copied from the current Vector3
  2954. * @returns the new Vector3
  2955. */
  2956. Vector3.prototype.clone = function () {
  2957. return new Vector3(this.x, this.y, this.z);
  2958. };
  2959. /**
  2960. * Copies the passed vector coordinates to the current Vector3 ones
  2961. * @param source defines the source Vector3
  2962. * @returns the current updated Vector3
  2963. */
  2964. Vector3.prototype.copyFrom = function (source) {
  2965. this.x = source.x;
  2966. this.y = source.y;
  2967. this.z = source.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Copies the passed floats to the current Vector3 coordinates
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the current updated Vector3
  2976. */
  2977. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2978. this.x = x;
  2979. this.y = y;
  2980. this.z = z;
  2981. return this;
  2982. };
  2983. /**
  2984. * Copies the passed floats to the current Vector3 coordinates
  2985. * @param x defines the x coordinate of the operand
  2986. * @param y defines the y coordinate of the operand
  2987. * @param z defines the z coordinate of the operand
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.set = function (x, y, z) {
  2991. return this.copyFromFloats(x, y, z);
  2992. };
  2993. // Statics
  2994. /**
  2995. * Get the clip factor between two vectors
  2996. * @param vector0 defines the first operand
  2997. * @param vector1 defines the second operand
  2998. * @param axis defines the axis to use
  2999. * @param size defines the size along the axis
  3000. * @returns the clip factor
  3001. */
  3002. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3003. var d0 = Vector3.Dot(vector0, axis) - size;
  3004. var d1 = Vector3.Dot(vector1, axis) - size;
  3005. var s = d0 / (d0 - d1);
  3006. return s;
  3007. };
  3008. /**
  3009. * Get angle between two vectors
  3010. * @param vector0 angle between vector0 and vector1
  3011. * @param vector1 angle between vector0 and vector1
  3012. * @param normal direction of the normal
  3013. * @return the angle between vector0 and vector1
  3014. */
  3015. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3016. var v0 = vector0.clone().normalize();
  3017. var v1 = vector1.clone().normalize();
  3018. var dot = Vector3.Dot(v0, v1);
  3019. var n = Vector3.Cross(v0, v1);
  3020. if (Vector3.Dot(n, normal) > 0) {
  3021. return Math.acos(dot);
  3022. }
  3023. return -Math.acos(dot);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set from the index "offset" of the passed array
  3027. * @param array defines the source array
  3028. * @param offset defines the offset in the source array
  3029. * @returns the new Vector3
  3030. */
  3031. Vector3.FromArray = function (array, offset) {
  3032. if (!offset) {
  3033. offset = 0;
  3034. }
  3035. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3039. * This function is deprecated. Use FromArray instead
  3040. * @param array defines the source array
  3041. * @param offset defines the offset in the source array
  3042. * @returns the new Vector3
  3043. */
  3044. Vector3.FromFloatArray = function (array, offset) {
  3045. return Vector3.FromArray(array, offset);
  3046. };
  3047. /**
  3048. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3049. * @param array defines the source array
  3050. * @param offset defines the offset in the source array
  3051. * @param result defines the Vector3 where to store the result
  3052. */
  3053. Vector3.FromArrayToRef = function (array, offset, result) {
  3054. result.x = array[offset];
  3055. result.y = array[offset + 1];
  3056. result.z = array[offset + 2];
  3057. };
  3058. /**
  3059. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3060. * This function is deprecated. Use FromArrayToRef instead.
  3061. * @param array defines the source array
  3062. * @param offset defines the offset in the source array
  3063. * @param result defines the Vector3 where to store the result
  3064. */
  3065. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3066. return Vector3.FromArrayToRef(array, offset, result);
  3067. };
  3068. /**
  3069. * Sets the passed vector "result" with the passed floats.
  3070. * @param x defines the x coordinate of the source
  3071. * @param y defines the y coordinate of the source
  3072. * @param z defines the z coordinate of the source
  3073. * @param result defines the Vector3 where to store the result
  3074. */
  3075. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3076. result.x = x;
  3077. result.y = y;
  3078. result.z = z;
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3082. * @returns a new empty Vector3
  3083. */
  3084. Vector3.Zero = function () {
  3085. return new Vector3(0.0, 0.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3089. * @returns a new unit Vector3
  3090. */
  3091. Vector3.One = function () {
  3092. return new Vector3(1.0, 1.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3096. * @returns a new up Vector3
  3097. */
  3098. Vector3.Up = function () {
  3099. return new Vector3(0.0, 1.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3103. * @returns a new forward Vector3
  3104. */
  3105. Vector3.Forward = function () {
  3106. return new Vector3(0.0, 0.0, 1.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3110. * @returns a new right Vector3
  3111. */
  3112. Vector3.Right = function () {
  3113. return new Vector3(1.0, 0.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3117. * @returns a new left Vector3
  3118. */
  3119. Vector3.Left = function () {
  3120. return new Vector3(-1.0, 0.0, 0.0);
  3121. };
  3122. /**
  3123. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3124. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3125. * @param vector defines the Vector3 to transform
  3126. * @param transformation defines the transformation matrix
  3127. * @returns the transformed Vector3
  3128. */
  3129. Vector3.TransformCoordinates = function (vector, transformation) {
  3130. var result = Vector3.Zero();
  3131. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3132. return result;
  3133. };
  3134. /**
  3135. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3136. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3137. * @param vector defines the Vector3 to transform
  3138. * @param transformation defines the transformation matrix
  3139. * @param result defines the Vector3 where to store the result
  3140. */
  3141. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3142. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3143. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3144. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3145. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3146. result.x = x / w;
  3147. result.y = y / w;
  3148. result.z = z / w;
  3149. };
  3150. /**
  3151. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3152. * This method computes tranformed coordinates only, not transformed direction vectors
  3153. * @param x define the x coordinate of the source vector
  3154. * @param y define the y coordinate of the source vector
  3155. * @param z define the z coordinate of the source vector
  3156. * @param transformation defines the transformation matrix
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3160. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3161. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3162. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3163. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3164. result.x = rx / rw;
  3165. result.y = ry / rw;
  3166. result.z = rz / rw;
  3167. };
  3168. /**
  3169. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3170. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3171. * @param vector defines the Vector3 to transform
  3172. * @param transformation defines the transformation matrix
  3173. * @returns the new Vector3
  3174. */
  3175. Vector3.TransformNormal = function (vector, transformation) {
  3176. var result = Vector3.Zero();
  3177. Vector3.TransformNormalToRef(vector, transformation, result);
  3178. return result;
  3179. };
  3180. /**
  3181. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3182. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3183. * @param vector defines the Vector3 to transform
  3184. * @param transformation defines the transformation matrix
  3185. * @param result defines the Vector3 where to store the result
  3186. */
  3187. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3188. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3189. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3190. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3191. result.x = x;
  3192. result.y = y;
  3193. result.z = z;
  3194. };
  3195. /**
  3196. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3197. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3198. * @param x define the x coordinate of the source vector
  3199. * @param y define the y coordinate of the source vector
  3200. * @param z define the z coordinate of the source vector
  3201. * @param transformation defines the transformation matrix
  3202. * @param result defines the Vector3 where to store the result
  3203. */
  3204. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3205. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3206. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3207. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3211. * @param value1 defines the first control point
  3212. * @param value2 defines the second control point
  3213. * @param value3 defines the third control point
  3214. * @param value4 defines the fourth control point
  3215. * @param amount defines the amount on the spline to use
  3216. * @returns the new Vector3
  3217. */
  3218. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3219. var squared = amount * amount;
  3220. var cubed = amount * squared;
  3221. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3222. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3223. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3224. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3225. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3226. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3227. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3228. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3229. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3230. return new Vector3(x, y, z);
  3231. };
  3232. /**
  3233. * 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"
  3234. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3235. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3236. * @param value defines the current value
  3237. * @param min defines the lower range value
  3238. * @param max defines the upper range value
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.Clamp = function (value, min, max) {
  3242. var x = value.x;
  3243. x = (x > max.x) ? max.x : x;
  3244. x = (x < min.x) ? min.x : x;
  3245. var y = value.y;
  3246. y = (y > max.y) ? max.y : y;
  3247. y = (y < min.y) ? min.y : y;
  3248. var z = value.z;
  3249. z = (z > max.z) ? max.z : z;
  3250. z = (z < min.z) ? min.z : z;
  3251. return new Vector3(x, y, z);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3255. * @param value1 defines the first control point
  3256. * @param tangent1 defines the first tangent vector
  3257. * @param value2 defines the second control point
  3258. * @param tangent2 defines the second tangent vector
  3259. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3260. * @returns the new Vector3
  3261. */
  3262. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3263. var squared = amount * amount;
  3264. var cubed = amount * squared;
  3265. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3266. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3267. var part3 = (cubed - (2.0 * squared)) + amount;
  3268. var part4 = cubed - squared;
  3269. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3270. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3271. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3272. return new Vector3(x, y, z);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3276. * @param start defines the start value
  3277. * @param end defines the end value
  3278. * @param amount max defines amount between both (between 0 and 1)
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.Lerp = function (start, end, amount) {
  3282. var result = new Vector3(0, 0, 0);
  3283. Vector3.LerpToRef(start, end, amount, result);
  3284. return result;
  3285. };
  3286. /**
  3287. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3288. * @param start defines the start value
  3289. * @param end defines the end value
  3290. * @param amount max defines amount between both (between 0 and 1)
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.LerpToRef = function (start, end, amount, result) {
  3294. result.x = start.x + ((end.x - start.x) * amount);
  3295. result.y = start.y + ((end.y - start.y) * amount);
  3296. result.z = start.z + ((end.z - start.z) * amount);
  3297. };
  3298. /**
  3299. * Returns the dot product (float) between the vectors "left" and "right"
  3300. * @param left defines the left operand
  3301. * @param right defines the right operand
  3302. * @returns the dot product
  3303. */
  3304. Vector3.Dot = function (left, right) {
  3305. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3306. };
  3307. /**
  3308. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3309. * The cross product is then orthogonal to both "left" and "right"
  3310. * @param left defines the left operand
  3311. * @param right defines the right operand
  3312. * @returns the cross product
  3313. */
  3314. Vector3.Cross = function (left, right) {
  3315. var result = Vector3.Zero();
  3316. Vector3.CrossToRef(left, right, result);
  3317. return result;
  3318. };
  3319. /**
  3320. * Sets the passed vector "result" with the cross product of "left" and "right"
  3321. * The cross product is then orthogonal to both "left" and "right"
  3322. * @param left defines the left operand
  3323. * @param right defines the right operand
  3324. * @param result defines the Vector3 where to store the result
  3325. */
  3326. Vector3.CrossToRef = function (left, right, result) {
  3327. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3328. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3329. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3330. result.copyFrom(MathTmp.Vector3[0]);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 as the normalization of the passed vector
  3334. * @param vector defines the Vector3 to normalize
  3335. * @returns the new Vector3
  3336. */
  3337. Vector3.Normalize = function (vector) {
  3338. var result = Vector3.Zero();
  3339. Vector3.NormalizeToRef(vector, result);
  3340. return result;
  3341. };
  3342. /**
  3343. * Sets the passed vector "result" with the normalization of the passed first vector
  3344. * @param vector defines the Vector3 to normalize
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.NormalizeToRef = function (vector, result) {
  3348. result.copyFrom(vector);
  3349. result.normalize();
  3350. };
  3351. /**
  3352. * Project a Vector3 onto screen space
  3353. * @param vector defines the Vector3 to project
  3354. * @param world defines the world matrix to use
  3355. * @param transform defines the transform (view x projection) matrix to use
  3356. * @param viewport defines the screen viewport to use
  3357. * @returns the new Vector3
  3358. */
  3359. Vector3.Project = function (vector, world, transform, viewport) {
  3360. var cw = viewport.width;
  3361. var ch = viewport.height;
  3362. var cx = viewport.x;
  3363. var cy = viewport.y;
  3364. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3365. 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);
  3366. var matrix = MathTmp.Matrix[0];
  3367. world.multiplyToRef(transform, matrix);
  3368. matrix.multiplyToRef(viewportMatrix, matrix);
  3369. return Vector3.TransformCoordinates(vector, matrix);
  3370. };
  3371. /**
  3372. * Unproject from screen space to object space
  3373. * @param source defines the screen space Vector3 to use
  3374. * @param viewportWidth defines the current width of the viewport
  3375. * @param viewportHeight defines the current height of the viewport
  3376. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3377. * @param transform defines the transform (view x projection) matrix to use
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3381. var matrix = MathTmp.Matrix[0];
  3382. world.multiplyToRef(transform, matrix);
  3383. matrix.invert();
  3384. source.x = source.x / viewportWidth * 2 - 1;
  3385. source.y = -(source.y / viewportHeight * 2 - 1);
  3386. var vector = Vector3.TransformCoordinates(source, matrix);
  3387. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3388. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3389. vector = vector.scale(1.0 / num);
  3390. }
  3391. return vector;
  3392. };
  3393. /**
  3394. * Unproject from screen space to object space
  3395. * @param source defines the screen space Vector3 to use
  3396. * @param viewportWidth defines the current width of the viewport
  3397. * @param viewportHeight defines the current height of the viewport
  3398. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3399. * @param view defines the view matrix to use
  3400. * @param projection defines the projection matrix to use
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3404. var result = Vector3.Zero();
  3405. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Unproject from screen space to object space
  3410. * @param source defines the screen space Vector3 to use
  3411. * @param viewportWidth defines the current width of the viewport
  3412. * @param viewportHeight defines the current height of the viewport
  3413. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3414. * @param view defines the view matrix to use
  3415. * @param projection defines the projection matrix to use
  3416. * @param result defines the Vector3 where to store the result
  3417. */
  3418. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3419. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3420. };
  3421. /**
  3422. * Unproject from screen space to object space
  3423. * @param sourceX defines the screen space x coordinate to use
  3424. * @param sourceY defines the screen space y coordinate to use
  3425. * @param sourceZ defines the screen space z coordinate to use
  3426. * @param viewportWidth defines the current width of the viewport
  3427. * @param viewportHeight defines the current height of the viewport
  3428. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3429. * @param view defines the view matrix to use
  3430. * @param projection defines the projection matrix to use
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3434. var matrix = MathTmp.Matrix[0];
  3435. world.multiplyToRef(view, matrix);
  3436. matrix.multiplyToRef(projection, matrix);
  3437. matrix.invert();
  3438. var screenSource = MathTmp.Vector3[0];
  3439. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3440. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3441. screenSource.z = 2 * sourceZ - 1.0;
  3442. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3443. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3444. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3445. result.scaleInPlace(1.0 / num);
  3446. }
  3447. };
  3448. /**
  3449. * Gets the minimal coordinate values between two Vector3
  3450. * @param left defines the first operand
  3451. * @param right defines the second operand
  3452. * @returns the new Vector3
  3453. */
  3454. Vector3.Minimize = function (left, right) {
  3455. var min = left.clone();
  3456. min.minimizeInPlace(right);
  3457. return min;
  3458. };
  3459. /**
  3460. * Gets the maximal coordinate values between two Vector3
  3461. * @param left defines the first operand
  3462. * @param right defines the second operand
  3463. * @returns the new Vector3
  3464. */
  3465. Vector3.Maximize = function (left, right) {
  3466. var max = left.clone();
  3467. max.maximizeInPlace(right);
  3468. return max;
  3469. };
  3470. /**
  3471. * Returns the distance between the vectors "value1" and "value2"
  3472. * @param value1 defines the first operand
  3473. * @param value2 defines the second operand
  3474. * @returns the distance
  3475. */
  3476. Vector3.Distance = function (value1, value2) {
  3477. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3478. };
  3479. /**
  3480. * Returns the squared distance between the vectors "value1" and "value2"
  3481. * @param value1 defines the first operand
  3482. * @param value2 defines the second operand
  3483. * @returns the squared distance
  3484. */
  3485. Vector3.DistanceSquared = function (value1, value2) {
  3486. var x = value1.x - value2.x;
  3487. var y = value1.y - value2.y;
  3488. var z = value1.z - value2.z;
  3489. return (x * x) + (y * y) + (z * z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located at the center between "value1" and "value2"
  3493. * @param value1 defines the first operand
  3494. * @param value2 defines the second operand
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Center = function (value1, value2) {
  3498. var center = value1.add(value2);
  3499. center.scaleInPlace(0.5);
  3500. return center;
  3501. };
  3502. /**
  3503. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3504. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3505. * to something in order to rotate it from its local system to the given target system
  3506. * Note: axis1, axis2 and axis3 are normalized during this operation
  3507. * @param axis1 defines the first axis
  3508. * @param axis2 defines the second axis
  3509. * @param axis3 defines the third axis
  3510. * @returns a new Vector3
  3511. */
  3512. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3513. var rotation = Vector3.Zero();
  3514. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3515. return rotation;
  3516. };
  3517. /**
  3518. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3519. * @param axis1 defines the first axis
  3520. * @param axis2 defines the second axis
  3521. * @param axis3 defines the third axis
  3522. * @param ref defines the Vector3 where to store the result
  3523. */
  3524. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3525. var quat = MathTmp.Quaternion[0];
  3526. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3527. quat.toEulerAnglesToRef(ref);
  3528. };
  3529. return Vector3;
  3530. }());
  3531. BABYLON.Vector3 = Vector3;
  3532. //Vector4 class created for EulerAngle class conversion to Quaternion
  3533. var Vector4 = /** @class */ (function () {
  3534. /**
  3535. * Creates a Vector4 object from the passed floats.
  3536. */
  3537. function Vector4(x, y, z, w) {
  3538. this.x = x;
  3539. this.y = y;
  3540. this.z = z;
  3541. this.w = w;
  3542. }
  3543. /**
  3544. * Returns the string with the Vector4 coordinates.
  3545. */
  3546. Vector4.prototype.toString = function () {
  3547. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3548. };
  3549. /**
  3550. * Returns the string "Vector4".
  3551. */
  3552. Vector4.prototype.getClassName = function () {
  3553. return "Vector4";
  3554. };
  3555. /**
  3556. * Returns the Vector4 hash code.
  3557. */
  3558. Vector4.prototype.getHashCode = function () {
  3559. var hash = this.x || 0;
  3560. hash = (hash * 397) ^ (this.y || 0);
  3561. hash = (hash * 397) ^ (this.z || 0);
  3562. hash = (hash * 397) ^ (this.w || 0);
  3563. return hash;
  3564. };
  3565. // Operators
  3566. /**
  3567. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3568. */
  3569. Vector4.prototype.asArray = function () {
  3570. var result = new Array();
  3571. this.toArray(result, 0);
  3572. return result;
  3573. };
  3574. /**
  3575. * Populates the passed array from the passed index with the Vector4 coordinates.
  3576. * Returns the Vector4.
  3577. */
  3578. Vector4.prototype.toArray = function (array, index) {
  3579. if (index === undefined) {
  3580. index = 0;
  3581. }
  3582. array[index] = this.x;
  3583. array[index + 1] = this.y;
  3584. array[index + 2] = this.z;
  3585. array[index + 3] = this.w;
  3586. return this;
  3587. };
  3588. /**
  3589. * Adds the passed vector to the current Vector4.
  3590. * Returns the updated Vector4.
  3591. */
  3592. Vector4.prototype.addInPlace = function (otherVector) {
  3593. this.x += otherVector.x;
  3594. this.y += otherVector.y;
  3595. this.z += otherVector.z;
  3596. this.w += otherVector.w;
  3597. return this;
  3598. };
  3599. /**
  3600. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3601. */
  3602. Vector4.prototype.add = function (otherVector) {
  3603. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3604. };
  3605. /**
  3606. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3607. * Returns the current Vector4.
  3608. */
  3609. Vector4.prototype.addToRef = function (otherVector, result) {
  3610. result.x = this.x + otherVector.x;
  3611. result.y = this.y + otherVector.y;
  3612. result.z = this.z + otherVector.z;
  3613. result.w = this.w + otherVector.w;
  3614. return this;
  3615. };
  3616. /**
  3617. * Subtract in place the passed vector from the current Vector4.
  3618. * Returns the updated Vector4.
  3619. */
  3620. Vector4.prototype.subtractInPlace = function (otherVector) {
  3621. this.x -= otherVector.x;
  3622. this.y -= otherVector.y;
  3623. this.z -= otherVector.z;
  3624. this.w -= otherVector.w;
  3625. return this;
  3626. };
  3627. /**
  3628. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3629. */
  3630. Vector4.prototype.subtract = function (otherVector) {
  3631. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3632. };
  3633. /**
  3634. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3635. * Returns the current Vector4.
  3636. */
  3637. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3638. result.x = this.x - otherVector.x;
  3639. result.y = this.y - otherVector.y;
  3640. result.z = this.z - otherVector.z;
  3641. result.w = this.w - otherVector.w;
  3642. return this;
  3643. };
  3644. /**
  3645. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3646. */
  3647. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3648. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3649. };
  3650. /**
  3651. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3652. * Returns the current Vector4.
  3653. */
  3654. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3655. result.x = this.x - x;
  3656. result.y = this.y - y;
  3657. result.z = this.z - z;
  3658. result.w = this.w - w;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3663. */
  3664. Vector4.prototype.negate = function () {
  3665. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3666. };
  3667. /**
  3668. * Multiplies the current Vector4 coordinates by scale (float).
  3669. * Returns the updated Vector4.
  3670. */
  3671. Vector4.prototype.scaleInPlace = function (scale) {
  3672. this.x *= scale;
  3673. this.y *= scale;
  3674. this.z *= scale;
  3675. this.w *= scale;
  3676. return this;
  3677. };
  3678. /**
  3679. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3680. */
  3681. Vector4.prototype.scale = function (scale) {
  3682. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3683. };
  3684. /**
  3685. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3686. * Returns the current Vector4.
  3687. */
  3688. Vector4.prototype.scaleToRef = function (scale, result) {
  3689. result.x = this.x * scale;
  3690. result.y = this.y * scale;
  3691. result.z = this.z * scale;
  3692. result.w = this.w * scale;
  3693. return this;
  3694. };
  3695. /**
  3696. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3697. */
  3698. Vector4.prototype.equals = function (otherVector) {
  3699. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3700. };
  3701. /**
  3702. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3703. */
  3704. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3705. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3706. return otherVector
  3707. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3708. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3709. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3710. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3711. };
  3712. /**
  3713. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3714. */
  3715. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3716. return this.x === x && this.y === y && this.z === z && this.w === w;
  3717. };
  3718. /**
  3719. * Multiplies in place the current Vector4 by the passed one.
  3720. * Returns the updated Vector4.
  3721. */
  3722. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3723. this.x *= otherVector.x;
  3724. this.y *= otherVector.y;
  3725. this.z *= otherVector.z;
  3726. this.w *= otherVector.w;
  3727. return this;
  3728. };
  3729. /**
  3730. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3731. */
  3732. Vector4.prototype.multiply = function (otherVector) {
  3733. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3734. };
  3735. /**
  3736. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3737. * Returns the current Vector4.
  3738. */
  3739. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3740. result.x = this.x * otherVector.x;
  3741. result.y = this.y * otherVector.y;
  3742. result.z = this.z * otherVector.z;
  3743. result.w = this.w * otherVector.w;
  3744. return this;
  3745. };
  3746. /**
  3747. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3748. */
  3749. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3750. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3751. };
  3752. /**
  3753. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3754. */
  3755. Vector4.prototype.divide = function (otherVector) {
  3756. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3757. };
  3758. /**
  3759. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3760. * Returns the current Vector4.
  3761. */
  3762. Vector4.prototype.divideToRef = function (otherVector, result) {
  3763. result.x = this.x / otherVector.x;
  3764. result.y = this.y / otherVector.y;
  3765. result.z = this.z / otherVector.z;
  3766. result.w = this.w / otherVector.w;
  3767. return this;
  3768. };
  3769. /**
  3770. * Divides the current Vector3 coordinates by the passed ones.
  3771. * @returns the updated Vector3.
  3772. */
  3773. Vector4.prototype.divideInPlace = function (otherVector) {
  3774. return this.divideToRef(otherVector, this);
  3775. };
  3776. /**
  3777. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3778. * @param other defines the second operand
  3779. * @returns the current updated Vector4
  3780. */
  3781. Vector4.prototype.minimizeInPlace = function (other) {
  3782. if (other.x < this.x)
  3783. this.x = other.x;
  3784. if (other.y < this.y)
  3785. this.y = other.y;
  3786. if (other.z < this.z)
  3787. this.z = other.z;
  3788. if (other.w < this.w)
  3789. this.w = other.w;
  3790. return this;
  3791. };
  3792. /**
  3793. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3794. * @param other defines the second operand
  3795. * @returns the current updated Vector4
  3796. */
  3797. Vector4.prototype.maximizeInPlace = function (other) {
  3798. if (other.x > this.x)
  3799. this.x = other.x;
  3800. if (other.y > this.y)
  3801. this.y = other.y;
  3802. if (other.z > this.z)
  3803. this.z = other.z;
  3804. if (other.w > this.w)
  3805. this.w = other.w;
  3806. return this;
  3807. };
  3808. // Properties
  3809. /**
  3810. * Returns the Vector4 length (float).
  3811. */
  3812. Vector4.prototype.length = function () {
  3813. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3814. };
  3815. /**
  3816. * Returns the Vector4 squared length (float).
  3817. */
  3818. Vector4.prototype.lengthSquared = function () {
  3819. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3820. };
  3821. // Methods
  3822. /**
  3823. * Normalizes in place the Vector4.
  3824. * Returns the updated Vector4.
  3825. */
  3826. Vector4.prototype.normalize = function () {
  3827. var len = this.length();
  3828. if (len === 0)
  3829. return this;
  3830. var num = 1.0 / len;
  3831. this.x *= num;
  3832. this.y *= num;
  3833. this.z *= num;
  3834. this.w *= num;
  3835. return this;
  3836. };
  3837. /**
  3838. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3839. */
  3840. Vector4.prototype.toVector3 = function () {
  3841. return new Vector3(this.x, this.y, this.z);
  3842. };
  3843. /**
  3844. * Returns a new Vector4 copied from the current one.
  3845. */
  3846. Vector4.prototype.clone = function () {
  3847. return new Vector4(this.x, this.y, this.z, this.w);
  3848. };
  3849. /**
  3850. * Updates the current Vector4 with the passed one coordinates.
  3851. * Returns the updated Vector4.
  3852. */
  3853. Vector4.prototype.copyFrom = function (source) {
  3854. this.x = source.x;
  3855. this.y = source.y;
  3856. this.z = source.z;
  3857. this.w = source.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Updates the current Vector4 coordinates with the passed floats.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3865. this.x = x;
  3866. this.y = y;
  3867. this.z = z;
  3868. this.w = w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Updates the current Vector4 coordinates with the passed floats.
  3873. * Returns the updated Vector4.
  3874. */
  3875. Vector4.prototype.set = function (x, y, z, w) {
  3876. return this.copyFromFloats(x, y, z, w);
  3877. };
  3878. // Statics
  3879. /**
  3880. * Returns a new Vector4 set from the starting index of the passed array.
  3881. */
  3882. Vector4.FromArray = function (array, offset) {
  3883. if (!offset) {
  3884. offset = 0;
  3885. }
  3886. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3887. };
  3888. /**
  3889. * Updates the passed vector "result" from the starting index of the passed array.
  3890. */
  3891. Vector4.FromArrayToRef = function (array, offset, result) {
  3892. result.x = array[offset];
  3893. result.y = array[offset + 1];
  3894. result.z = array[offset + 2];
  3895. result.w = array[offset + 3];
  3896. };
  3897. /**
  3898. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3899. */
  3900. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3901. Vector4.FromArrayToRef(array, offset, result);
  3902. };
  3903. /**
  3904. * Updates the passed vector "result" coordinates from the passed floats.
  3905. */
  3906. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3907. result.x = x;
  3908. result.y = y;
  3909. result.z = z;
  3910. result.w = w;
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3914. */
  3915. Vector4.Zero = function () {
  3916. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3917. };
  3918. /**
  3919. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3920. */
  3921. Vector4.One = function () {
  3922. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3923. };
  3924. /**
  3925. * Returns a new normalized Vector4 from the passed one.
  3926. */
  3927. Vector4.Normalize = function (vector) {
  3928. var result = Vector4.Zero();
  3929. Vector4.NormalizeToRef(vector, result);
  3930. return result;
  3931. };
  3932. /**
  3933. * Updates the passed vector "result" from the normalization of the passed one.
  3934. */
  3935. Vector4.NormalizeToRef = function (vector, result) {
  3936. result.copyFrom(vector);
  3937. result.normalize();
  3938. };
  3939. Vector4.Minimize = function (left, right) {
  3940. var min = left.clone();
  3941. min.minimizeInPlace(right);
  3942. return min;
  3943. };
  3944. Vector4.Maximize = function (left, right) {
  3945. var max = left.clone();
  3946. max.maximizeInPlace(right);
  3947. return max;
  3948. };
  3949. /**
  3950. * Returns the distance (float) between the vectors "value1" and "value2".
  3951. */
  3952. Vector4.Distance = function (value1, value2) {
  3953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3954. };
  3955. /**
  3956. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3957. */
  3958. Vector4.DistanceSquared = function (value1, value2) {
  3959. var x = value1.x - value2.x;
  3960. var y = value1.y - value2.y;
  3961. var z = value1.z - value2.z;
  3962. var w = value1.w - value2.w;
  3963. return (x * x) + (y * y) + (z * z) + (w * w);
  3964. };
  3965. /**
  3966. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3967. */
  3968. Vector4.Center = function (value1, value2) {
  3969. var center = value1.add(value2);
  3970. center.scaleInPlace(0.5);
  3971. return center;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3975. * This methods computes transformed normalized direction vectors only.
  3976. */
  3977. Vector4.TransformNormal = function (vector, transformation) {
  3978. var result = Vector4.Zero();
  3979. Vector4.TransformNormalToRef(vector, transformation, result);
  3980. return result;
  3981. };
  3982. /**
  3983. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3984. * This methods computes transformed normalized direction vectors only.
  3985. */
  3986. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3987. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3988. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3989. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3990. result.x = x;
  3991. result.y = y;
  3992. result.z = z;
  3993. result.w = vector.w;
  3994. };
  3995. /**
  3996. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3997. * This methods computes transformed normalized direction vectors only.
  3998. */
  3999. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4000. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4001. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4002. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4003. result.w = w;
  4004. };
  4005. return Vector4;
  4006. }());
  4007. BABYLON.Vector4 = Vector4;
  4008. var Size = /** @class */ (function () {
  4009. /**
  4010. * Creates a Size object from the passed width and height (floats).
  4011. */
  4012. function Size(width, height) {
  4013. this.width = width;
  4014. this.height = height;
  4015. }
  4016. // Returns a string with the Size width and height.
  4017. Size.prototype.toString = function () {
  4018. return "{W: " + this.width + ", H: " + this.height + "}";
  4019. };
  4020. /**
  4021. * Returns the string "Size"
  4022. */
  4023. Size.prototype.getClassName = function () {
  4024. return "Size";
  4025. };
  4026. /**
  4027. * Returns the Size hash code.
  4028. */
  4029. Size.prototype.getHashCode = function () {
  4030. var hash = this.width || 0;
  4031. hash = (hash * 397) ^ (this.height || 0);
  4032. return hash;
  4033. };
  4034. /**
  4035. * Updates the current size from the passed one.
  4036. * Returns the updated Size.
  4037. */
  4038. Size.prototype.copyFrom = function (src) {
  4039. this.width = src.width;
  4040. this.height = src.height;
  4041. };
  4042. /**
  4043. * Updates in place the current Size from the passed floats.
  4044. * Returns the updated Size.
  4045. */
  4046. Size.prototype.copyFromFloats = function (width, height) {
  4047. this.width = width;
  4048. this.height = height;
  4049. return this;
  4050. };
  4051. /**
  4052. * Updates in place the current Size from the passed floats.
  4053. * Returns the updated Size.
  4054. */
  4055. Size.prototype.set = function (width, height) {
  4056. return this.copyFromFloats(width, height);
  4057. };
  4058. /**
  4059. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4060. */
  4061. Size.prototype.multiplyByFloats = function (w, h) {
  4062. return new Size(this.width * w, this.height * h);
  4063. };
  4064. /**
  4065. * Returns a new Size copied from the passed one.
  4066. */
  4067. Size.prototype.clone = function () {
  4068. return new Size(this.width, this.height);
  4069. };
  4070. /**
  4071. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4072. */
  4073. Size.prototype.equals = function (other) {
  4074. if (!other) {
  4075. return false;
  4076. }
  4077. return (this.width === other.width) && (this.height === other.height);
  4078. };
  4079. Object.defineProperty(Size.prototype, "surface", {
  4080. /**
  4081. * Returns the surface of the Size : width * height (float).
  4082. */
  4083. get: function () {
  4084. return this.width * this.height;
  4085. },
  4086. enumerable: true,
  4087. configurable: true
  4088. });
  4089. /**
  4090. * Returns a new Size set to (0.0, 0.0)
  4091. */
  4092. Size.Zero = function () {
  4093. return new Size(0.0, 0.0);
  4094. };
  4095. /**
  4096. * Returns a new Size set as the addition result of the current Size and the passed one.
  4097. */
  4098. Size.prototype.add = function (otherSize) {
  4099. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4100. return r;
  4101. };
  4102. /**
  4103. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4104. */
  4105. Size.prototype.subtract = function (otherSize) {
  4106. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4107. return r;
  4108. };
  4109. /**
  4110. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4111. */
  4112. Size.Lerp = function (start, end, amount) {
  4113. var w = start.width + ((end.width - start.width) * amount);
  4114. var h = start.height + ((end.height - start.height) * amount);
  4115. return new Size(w, h);
  4116. };
  4117. return Size;
  4118. }());
  4119. BABYLON.Size = Size;
  4120. var Quaternion = /** @class */ (function () {
  4121. /**
  4122. * Creates a new Quaternion from the passed floats.
  4123. */
  4124. function Quaternion(x, y, z, w) {
  4125. if (x === void 0) { x = 0.0; }
  4126. if (y === void 0) { y = 0.0; }
  4127. if (z === void 0) { z = 0.0; }
  4128. if (w === void 0) { w = 1.0; }
  4129. this.x = x;
  4130. this.y = y;
  4131. this.z = z;
  4132. this.w = w;
  4133. }
  4134. /**
  4135. * Returns a string with the Quaternion coordinates.
  4136. */
  4137. Quaternion.prototype.toString = function () {
  4138. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4139. };
  4140. /**
  4141. * Returns the string "Quaternion".
  4142. */
  4143. Quaternion.prototype.getClassName = function () {
  4144. return "Quaternion";
  4145. };
  4146. /**
  4147. * Returns the Quaternion hash code.
  4148. */
  4149. Quaternion.prototype.getHashCode = function () {
  4150. var hash = this.x || 0;
  4151. hash = (hash * 397) ^ (this.y || 0);
  4152. hash = (hash * 397) ^ (this.z || 0);
  4153. hash = (hash * 397) ^ (this.w || 0);
  4154. return hash;
  4155. };
  4156. /**
  4157. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4158. */
  4159. Quaternion.prototype.asArray = function () {
  4160. return [this.x, this.y, this.z, this.w];
  4161. };
  4162. /**
  4163. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4164. */
  4165. Quaternion.prototype.equals = function (otherQuaternion) {
  4166. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4167. };
  4168. /**
  4169. * Returns a new Quaternion copied from the current one.
  4170. */
  4171. Quaternion.prototype.clone = function () {
  4172. return new Quaternion(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Quaternion from the passed one coordinates.
  4176. * Returns the updated Quaterion.
  4177. */
  4178. Quaternion.prototype.copyFrom = function (other) {
  4179. this.x = other.x;
  4180. this.y = other.y;
  4181. this.z = other.z;
  4182. this.w = other.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Quaternion from the passed float coordinates.
  4187. * Returns the updated Quaterion.
  4188. */
  4189. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Quaternion from the passed float coordinates.
  4198. * Returns the updated Quaterion.
  4199. */
  4200. Quaternion.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. /**
  4204. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4205. */
  4206. Quaternion.prototype.add = function (other) {
  4207. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4208. };
  4209. /**
  4210. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4211. */
  4212. Quaternion.prototype.subtract = function (other) {
  4213. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4214. };
  4215. /**
  4216. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4217. */
  4218. Quaternion.prototype.scale = function (value) {
  4219. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4220. };
  4221. /**
  4222. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4223. */
  4224. Quaternion.prototype.multiply = function (q1) {
  4225. var result = new Quaternion(0, 0, 0, 1.0);
  4226. this.multiplyToRef(q1, result);
  4227. return result;
  4228. };
  4229. /**
  4230. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4231. * Returns the current Quaternion.
  4232. */
  4233. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4234. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4235. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4236. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4237. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4238. result.copyFromFloats(x, y, z, w);
  4239. return this;
  4240. };
  4241. /**
  4242. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4243. * Returns the updated Quaternion.
  4244. */
  4245. Quaternion.prototype.multiplyInPlace = function (q1) {
  4246. this.multiplyToRef(q1, this);
  4247. return this;
  4248. };
  4249. /**
  4250. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4251. * Returns the current Quaternion.
  4252. */
  4253. Quaternion.prototype.conjugateToRef = function (ref) {
  4254. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4255. return this;
  4256. };
  4257. /**
  4258. * Conjugates in place the current Quaternion.
  4259. * Returns the updated Quaternion.
  4260. */
  4261. Quaternion.prototype.conjugateInPlace = function () {
  4262. this.x *= -1;
  4263. this.y *= -1;
  4264. this.z *= -1;
  4265. return this;
  4266. };
  4267. /**
  4268. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4269. */
  4270. Quaternion.prototype.conjugate = function () {
  4271. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4272. return result;
  4273. };
  4274. /**
  4275. * Returns the Quaternion length (float).
  4276. */
  4277. Quaternion.prototype.length = function () {
  4278. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4279. };
  4280. /**
  4281. * Normalize in place the current Quaternion.
  4282. * Returns the updated Quaternion.
  4283. */
  4284. Quaternion.prototype.normalize = function () {
  4285. var length = 1.0 / this.length();
  4286. this.x *= length;
  4287. this.y *= length;
  4288. this.z *= length;
  4289. this.w *= length;
  4290. return this;
  4291. };
  4292. /**
  4293. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4294. */
  4295. Quaternion.prototype.toEulerAngles = function (order) {
  4296. if (order === void 0) { order = "YZX"; }
  4297. var result = Vector3.Zero();
  4298. this.toEulerAnglesToRef(result, order);
  4299. return result;
  4300. };
  4301. /**
  4302. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4303. * Returns the current Quaternion.
  4304. */
  4305. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4306. if (order === void 0) { order = "YZX"; }
  4307. var qz = this.z;
  4308. var qx = this.x;
  4309. var qy = this.y;
  4310. var qw = this.w;
  4311. var sqw = qw * qw;
  4312. var sqz = qz * qz;
  4313. var sqx = qx * qx;
  4314. var sqy = qy * qy;
  4315. var zAxisY = qy * qz - qx * qw;
  4316. var limit = .4999999;
  4317. if (zAxisY < -limit) {
  4318. result.y = 2 * Math.atan2(qy, qw);
  4319. result.x = Math.PI / 2;
  4320. result.z = 0;
  4321. }
  4322. else if (zAxisY > limit) {
  4323. result.y = 2 * Math.atan2(qy, qw);
  4324. result.x = -Math.PI / 2;
  4325. result.z = 0;
  4326. }
  4327. else {
  4328. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4329. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4330. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4331. }
  4332. return this;
  4333. };
  4334. /**
  4335. * Updates the passed rotation matrix with the current Quaternion values.
  4336. * Returns the current Quaternion.
  4337. */
  4338. Quaternion.prototype.toRotationMatrix = function (result) {
  4339. var xx = this.x * this.x;
  4340. var yy = this.y * this.y;
  4341. var zz = this.z * this.z;
  4342. var xy = this.x * this.y;
  4343. var zw = this.z * this.w;
  4344. var zx = this.z * this.x;
  4345. var yw = this.y * this.w;
  4346. var yz = this.y * this.z;
  4347. var xw = this.x * this.w;
  4348. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4349. result.m[1] = 2.0 * (xy + zw);
  4350. result.m[2] = 2.0 * (zx - yw);
  4351. result.m[3] = 0;
  4352. result.m[4] = 2.0 * (xy - zw);
  4353. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4354. result.m[6] = 2.0 * (yz + xw);
  4355. result.m[7] = 0;
  4356. result.m[8] = 2.0 * (zx + yw);
  4357. result.m[9] = 2.0 * (yz - xw);
  4358. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4359. result.m[11] = 0;
  4360. result.m[12] = 0;
  4361. result.m[13] = 0;
  4362. result.m[14] = 0;
  4363. result.m[15] = 1.0;
  4364. result._markAsUpdated();
  4365. return this;
  4366. };
  4367. /**
  4368. * Updates the current Quaternion from the passed rotation matrix values.
  4369. * Returns the updated Quaternion.
  4370. */
  4371. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4372. Quaternion.FromRotationMatrixToRef(matrix, this);
  4373. return this;
  4374. };
  4375. // Statics
  4376. /**
  4377. * Returns a new Quaternion set from the passed rotation matrix values.
  4378. */
  4379. Quaternion.FromRotationMatrix = function (matrix) {
  4380. var result = new Quaternion();
  4381. Quaternion.FromRotationMatrixToRef(matrix, result);
  4382. return result;
  4383. };
  4384. /**
  4385. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4386. */
  4387. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4388. var data = matrix.m;
  4389. var m11 = data[0], m12 = data[4], m13 = data[8];
  4390. var m21 = data[1], m22 = data[5], m23 = data[9];
  4391. var m31 = data[2], m32 = data[6], m33 = data[10];
  4392. var trace = m11 + m22 + m33;
  4393. var s;
  4394. if (trace > 0) {
  4395. s = 0.5 / Math.sqrt(trace + 1.0);
  4396. result.w = 0.25 / s;
  4397. result.x = (m32 - m23) * s;
  4398. result.y = (m13 - m31) * s;
  4399. result.z = (m21 - m12) * s;
  4400. }
  4401. else if (m11 > m22 && m11 > m33) {
  4402. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4403. result.w = (m32 - m23) / s;
  4404. result.x = 0.25 * s;
  4405. result.y = (m12 + m21) / s;
  4406. result.z = (m13 + m31) / s;
  4407. }
  4408. else if (m22 > m33) {
  4409. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4410. result.w = (m13 - m31) / s;
  4411. result.x = (m12 + m21) / s;
  4412. result.y = 0.25 * s;
  4413. result.z = (m23 + m32) / s;
  4414. }
  4415. else {
  4416. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4417. result.w = (m21 - m12) / s;
  4418. result.x = (m13 + m31) / s;
  4419. result.y = (m23 + m32) / s;
  4420. result.z = 0.25 * s;
  4421. }
  4422. };
  4423. /**
  4424. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4425. */
  4426. Quaternion.Zero = function () {
  4427. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4428. };
  4429. /**
  4430. * Returns a new Quaternion as the inverted current Quaternion.
  4431. */
  4432. Quaternion.Inverse = function (q) {
  4433. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4434. };
  4435. /**
  4436. * Returns the identity Quaternion.
  4437. */
  4438. Quaternion.Identity = function () {
  4439. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4440. };
  4441. Quaternion.IsIdentity = function (quaternion) {
  4442. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4443. };
  4444. /**
  4445. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4446. */
  4447. Quaternion.RotationAxis = function (axis, angle) {
  4448. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4449. };
  4450. /**
  4451. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4452. */
  4453. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4454. var sin = Math.sin(angle / 2);
  4455. axis.normalize();
  4456. result.w = Math.cos(angle / 2);
  4457. result.x = axis.x * sin;
  4458. result.y = axis.y * sin;
  4459. result.z = axis.z * sin;
  4460. return result;
  4461. };
  4462. /**
  4463. * Retuns a new Quaternion set from the starting index of the passed array.
  4464. */
  4465. Quaternion.FromArray = function (array, offset) {
  4466. if (!offset) {
  4467. offset = 0;
  4468. }
  4469. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4470. };
  4471. /**
  4472. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4473. */
  4474. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4475. var q = new Quaternion();
  4476. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4477. return q;
  4478. };
  4479. /**
  4480. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4481. */
  4482. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4483. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4484. var halfRoll = roll * 0.5;
  4485. var halfPitch = pitch * 0.5;
  4486. var halfYaw = yaw * 0.5;
  4487. var sinRoll = Math.sin(halfRoll);
  4488. var cosRoll = Math.cos(halfRoll);
  4489. var sinPitch = Math.sin(halfPitch);
  4490. var cosPitch = Math.cos(halfPitch);
  4491. var sinYaw = Math.sin(halfYaw);
  4492. var cosYaw = Math.cos(halfYaw);
  4493. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4494. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4495. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4496. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4497. };
  4498. /**
  4499. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4500. */
  4501. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4502. var result = new Quaternion();
  4503. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4504. return result;
  4505. };
  4506. /**
  4507. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4508. */
  4509. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4510. // Produces a quaternion from Euler angles in the z-x-z orientation
  4511. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4512. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4513. var halfBeta = beta * 0.5;
  4514. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4515. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4516. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4517. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4518. };
  4519. /**
  4520. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4521. * cf to Vector3.RotationFromAxis() documentation.
  4522. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4523. */
  4524. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4525. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4526. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4527. return quat;
  4528. };
  4529. /**
  4530. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4531. * cf to Vector3.RotationFromAxis() documentation.
  4532. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4533. */
  4534. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4535. var rotMat = MathTmp.Matrix[0];
  4536. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4537. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4538. };
  4539. Quaternion.Slerp = function (left, right, amount) {
  4540. var result = Quaternion.Identity();
  4541. Quaternion.SlerpToRef(left, right, amount, result);
  4542. return result;
  4543. };
  4544. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4545. var num2;
  4546. var num3;
  4547. var num = amount;
  4548. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4549. var flag = false;
  4550. if (num4 < 0) {
  4551. flag = true;
  4552. num4 = -num4;
  4553. }
  4554. if (num4 > 0.999999) {
  4555. num3 = 1 - num;
  4556. num2 = flag ? -num : num;
  4557. }
  4558. else {
  4559. var num5 = Math.acos(num4);
  4560. var num6 = (1.0 / Math.sin(num5));
  4561. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4562. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4563. }
  4564. result.x = (num3 * left.x) + (num2 * right.x);
  4565. result.y = (num3 * left.y) + (num2 * right.y);
  4566. result.z = (num3 * left.z) + (num2 * right.z);
  4567. result.w = (num3 * left.w) + (num2 * right.w);
  4568. };
  4569. /**
  4570. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4571. */
  4572. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4573. var squared = amount * amount;
  4574. var cubed = amount * squared;
  4575. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4576. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4577. var part3 = (cubed - (2.0 * squared)) + amount;
  4578. var part4 = cubed - squared;
  4579. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4580. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4581. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4582. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4583. return new Quaternion(x, y, z, w);
  4584. };
  4585. return Quaternion;
  4586. }());
  4587. BABYLON.Quaternion = Quaternion;
  4588. var Matrix = /** @class */ (function () {
  4589. function Matrix() {
  4590. this._isIdentity = false;
  4591. this._isIdentityDirty = true;
  4592. this.m = new Float32Array(16);
  4593. this._markAsUpdated();
  4594. }
  4595. Matrix.prototype._markAsUpdated = function () {
  4596. this.updateFlag = Matrix._updateFlagSeed++;
  4597. this._isIdentityDirty = true;
  4598. };
  4599. // Properties
  4600. /**
  4601. * Boolean : True is the matrix is the identity matrix
  4602. */
  4603. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4604. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4605. if (this._isIdentityDirty) {
  4606. this._isIdentityDirty = false;
  4607. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4608. this._isIdentity = false;
  4609. }
  4610. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4611. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4612. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4613. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4614. this._isIdentity = false;
  4615. }
  4616. else {
  4617. this._isIdentity = true;
  4618. }
  4619. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4620. this._isIdentity = false;
  4621. }
  4622. }
  4623. return this._isIdentity;
  4624. };
  4625. /**
  4626. * Returns the matrix determinant (float).
  4627. */
  4628. Matrix.prototype.determinant = function () {
  4629. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4630. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4631. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4632. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4633. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4634. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4635. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4636. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4637. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4638. };
  4639. // Methods
  4640. /**
  4641. * Returns the matrix underlying array.
  4642. */
  4643. Matrix.prototype.toArray = function () {
  4644. return this.m;
  4645. };
  4646. /**
  4647. * Returns the matrix underlying array.
  4648. */
  4649. Matrix.prototype.asArray = function () {
  4650. return this.toArray();
  4651. };
  4652. /**
  4653. * Inverts in place the Matrix.
  4654. * Returns the Matrix inverted.
  4655. */
  4656. Matrix.prototype.invert = function () {
  4657. this.invertToRef(this);
  4658. return this;
  4659. };
  4660. /**
  4661. * Sets all the matrix elements to zero.
  4662. * Returns the Matrix.
  4663. */
  4664. Matrix.prototype.reset = function () {
  4665. for (var index = 0; index < 16; index++) {
  4666. this.m[index] = 0.0;
  4667. }
  4668. this._markAsUpdated();
  4669. return this;
  4670. };
  4671. /**
  4672. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4673. */
  4674. Matrix.prototype.add = function (other) {
  4675. var result = new Matrix();
  4676. this.addToRef(other, result);
  4677. return result;
  4678. };
  4679. /**
  4680. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4681. * Returns the Matrix.
  4682. */
  4683. Matrix.prototype.addToRef = function (other, result) {
  4684. for (var index = 0; index < 16; index++) {
  4685. result.m[index] = this.m[index] + other.m[index];
  4686. }
  4687. result._markAsUpdated();
  4688. return this;
  4689. };
  4690. /**
  4691. * Adds in place the passed matrix to the current Matrix.
  4692. * Returns the updated Matrix.
  4693. */
  4694. Matrix.prototype.addToSelf = function (other) {
  4695. for (var index = 0; index < 16; index++) {
  4696. this.m[index] += other.m[index];
  4697. }
  4698. this._markAsUpdated();
  4699. return this;
  4700. };
  4701. /**
  4702. * Sets the passed matrix with the current inverted Matrix.
  4703. * Returns the unmodified current Matrix.
  4704. */
  4705. Matrix.prototype.invertToRef = function (other) {
  4706. var l1 = this.m[0];
  4707. var l2 = this.m[1];
  4708. var l3 = this.m[2];
  4709. var l4 = this.m[3];
  4710. var l5 = this.m[4];
  4711. var l6 = this.m[5];
  4712. var l7 = this.m[6];
  4713. var l8 = this.m[7];
  4714. var l9 = this.m[8];
  4715. var l10 = this.m[9];
  4716. var l11 = this.m[10];
  4717. var l12 = this.m[11];
  4718. var l13 = this.m[12];
  4719. var l14 = this.m[13];
  4720. var l15 = this.m[14];
  4721. var l16 = this.m[15];
  4722. var l17 = (l11 * l16) - (l12 * l15);
  4723. var l18 = (l10 * l16) - (l12 * l14);
  4724. var l19 = (l10 * l15) - (l11 * l14);
  4725. var l20 = (l9 * l16) - (l12 * l13);
  4726. var l21 = (l9 * l15) - (l11 * l13);
  4727. var l22 = (l9 * l14) - (l10 * l13);
  4728. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4729. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4730. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4731. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4732. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4733. var l28 = (l7 * l16) - (l8 * l15);
  4734. var l29 = (l6 * l16) - (l8 * l14);
  4735. var l30 = (l6 * l15) - (l7 * l14);
  4736. var l31 = (l5 * l16) - (l8 * l13);
  4737. var l32 = (l5 * l15) - (l7 * l13);
  4738. var l33 = (l5 * l14) - (l6 * l13);
  4739. var l34 = (l7 * l12) - (l8 * l11);
  4740. var l35 = (l6 * l12) - (l8 * l10);
  4741. var l36 = (l6 * l11) - (l7 * l10);
  4742. var l37 = (l5 * l12) - (l8 * l9);
  4743. var l38 = (l5 * l11) - (l7 * l9);
  4744. var l39 = (l5 * l10) - (l6 * l9);
  4745. other.m[0] = l23 * l27;
  4746. other.m[4] = l24 * l27;
  4747. other.m[8] = l25 * l27;
  4748. other.m[12] = l26 * l27;
  4749. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4750. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4751. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4752. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4753. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4754. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4755. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4756. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4757. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4758. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4759. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4760. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4761. other._markAsUpdated();
  4762. return this;
  4763. };
  4764. /**
  4765. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4766. * Returns the updated Matrix.
  4767. */
  4768. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4769. this.m[12] = x;
  4770. this.m[13] = y;
  4771. this.m[14] = z;
  4772. this._markAsUpdated();
  4773. return this;
  4774. };
  4775. /**
  4776. * Inserts the translation vector in the current Matrix.
  4777. * Returns the updated Matrix.
  4778. */
  4779. Matrix.prototype.setTranslation = function (vector3) {
  4780. this.m[12] = vector3.x;
  4781. this.m[13] = vector3.y;
  4782. this.m[14] = vector3.z;
  4783. this._markAsUpdated();
  4784. return this;
  4785. };
  4786. /**
  4787. * Returns a new Vector3 as the extracted translation from the Matrix.
  4788. */
  4789. Matrix.prototype.getTranslation = function () {
  4790. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4791. };
  4792. /**
  4793. * Fill a Vector3 with the extracted translation from the Matrix.
  4794. */
  4795. Matrix.prototype.getTranslationToRef = function (result) {
  4796. result.x = this.m[12];
  4797. result.y = this.m[13];
  4798. result.z = this.m[14];
  4799. return this;
  4800. };
  4801. /**
  4802. * Remove rotation and scaling part from the Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.removeRotationAndScaling = function () {
  4806. this.setRowFromFloats(0, 1, 0, 0, 0);
  4807. this.setRowFromFloats(1, 0, 1, 0, 0);
  4808. this.setRowFromFloats(2, 0, 0, 1, 0);
  4809. return this;
  4810. };
  4811. /**
  4812. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4813. */
  4814. Matrix.prototype.multiply = function (other) {
  4815. var result = new Matrix();
  4816. this.multiplyToRef(other, result);
  4817. return result;
  4818. };
  4819. /**
  4820. * Updates the current Matrix from the passed one values.
  4821. * Returns the updated Matrix.
  4822. */
  4823. Matrix.prototype.copyFrom = function (other) {
  4824. for (var index = 0; index < 16; index++) {
  4825. this.m[index] = other.m[index];
  4826. }
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Populates the passed array from the starting index with the Matrix values.
  4832. * Returns the Matrix.
  4833. */
  4834. Matrix.prototype.copyToArray = function (array, offset) {
  4835. if (offset === void 0) { offset = 0; }
  4836. for (var index = 0; index < 16; index++) {
  4837. array[offset + index] = this.m[index];
  4838. }
  4839. return this;
  4840. };
  4841. /**
  4842. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4843. */
  4844. Matrix.prototype.multiplyToRef = function (other, result) {
  4845. this.multiplyToArray(other, result.m, 0);
  4846. result._markAsUpdated();
  4847. return this;
  4848. };
  4849. /**
  4850. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4851. */
  4852. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4853. var tm0 = this.m[0];
  4854. var tm1 = this.m[1];
  4855. var tm2 = this.m[2];
  4856. var tm3 = this.m[3];
  4857. var tm4 = this.m[4];
  4858. var tm5 = this.m[5];
  4859. var tm6 = this.m[6];
  4860. var tm7 = this.m[7];
  4861. var tm8 = this.m[8];
  4862. var tm9 = this.m[9];
  4863. var tm10 = this.m[10];
  4864. var tm11 = this.m[11];
  4865. var tm12 = this.m[12];
  4866. var tm13 = this.m[13];
  4867. var tm14 = this.m[14];
  4868. var tm15 = this.m[15];
  4869. var om0 = other.m[0];
  4870. var om1 = other.m[1];
  4871. var om2 = other.m[2];
  4872. var om3 = other.m[3];
  4873. var om4 = other.m[4];
  4874. var om5 = other.m[5];
  4875. var om6 = other.m[6];
  4876. var om7 = other.m[7];
  4877. var om8 = other.m[8];
  4878. var om9 = other.m[9];
  4879. var om10 = other.m[10];
  4880. var om11 = other.m[11];
  4881. var om12 = other.m[12];
  4882. var om13 = other.m[13];
  4883. var om14 = other.m[14];
  4884. var om15 = other.m[15];
  4885. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4886. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4887. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4888. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4889. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4890. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4891. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4892. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4893. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4894. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4895. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4896. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4897. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4898. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4899. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4900. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4901. return this;
  4902. };
  4903. /**
  4904. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4905. */
  4906. Matrix.prototype.equals = function (value) {
  4907. return value &&
  4908. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4909. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4910. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4911. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4912. };
  4913. /**
  4914. * Returns a new Matrix from the current Matrix.
  4915. */
  4916. Matrix.prototype.clone = function () {
  4917. 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]);
  4918. };
  4919. /**
  4920. * Returns the string "Matrix"
  4921. */
  4922. Matrix.prototype.getClassName = function () {
  4923. return "Matrix";
  4924. };
  4925. /**
  4926. * Returns the Matrix hash code.
  4927. */
  4928. Matrix.prototype.getHashCode = function () {
  4929. var hash = this.m[0] || 0;
  4930. for (var i = 1; i < 16; i++) {
  4931. hash = (hash * 397) ^ (this.m[i] || 0);
  4932. }
  4933. return hash;
  4934. };
  4935. /**
  4936. * Decomposes the current Matrix into :
  4937. * - a scale vector3 passed as a reference to update,
  4938. * - a rotation quaternion passed as a reference to update,
  4939. * - a translation vector3 passed as a reference to update.
  4940. * Returns the true if operation was successful.
  4941. */
  4942. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4943. translation.x = this.m[12];
  4944. translation.y = this.m[13];
  4945. translation.z = this.m[14];
  4946. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4947. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4948. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4949. if (this.determinant() <= 0) {
  4950. scale.y *= -1;
  4951. }
  4952. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4953. rotation.x = 0;
  4954. rotation.y = 0;
  4955. rotation.z = 0;
  4956. rotation.w = 1;
  4957. return false;
  4958. }
  4959. 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]);
  4960. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4961. return true;
  4962. };
  4963. /**
  4964. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4965. */
  4966. Matrix.prototype.getRotationMatrix = function () {
  4967. var result = Matrix.Identity();
  4968. this.getRotationMatrixToRef(result);
  4969. return result;
  4970. };
  4971. /**
  4972. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4973. * Returns the current Matrix.
  4974. */
  4975. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4976. var m = this.m;
  4977. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4978. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4979. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4980. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4981. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4982. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4983. 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);
  4984. return this;
  4985. };
  4986. // Statics
  4987. /**
  4988. * Returns a new Matrix set from the starting index of the passed array.
  4989. */
  4990. Matrix.FromArray = function (array, offset) {
  4991. var result = new Matrix();
  4992. if (!offset) {
  4993. offset = 0;
  4994. }
  4995. Matrix.FromArrayToRef(array, offset, result);
  4996. return result;
  4997. };
  4998. /**
  4999. * Sets the passed "result" matrix from the starting index of the passed array.
  5000. */
  5001. Matrix.FromArrayToRef = function (array, offset, result) {
  5002. for (var index = 0; index < 16; index++) {
  5003. result.m[index] = array[index + offset];
  5004. }
  5005. result._markAsUpdated();
  5006. };
  5007. /**
  5008. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5009. */
  5010. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5011. for (var index = 0; index < 16; index++) {
  5012. result.m[index] = array[index + offset] * scale;
  5013. }
  5014. result._markAsUpdated();
  5015. };
  5016. /**
  5017. * Sets the passed matrix "result" with the 16 passed floats.
  5018. */
  5019. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5020. result.m[0] = initialM11;
  5021. result.m[1] = initialM12;
  5022. result.m[2] = initialM13;
  5023. result.m[3] = initialM14;
  5024. result.m[4] = initialM21;
  5025. result.m[5] = initialM22;
  5026. result.m[6] = initialM23;
  5027. result.m[7] = initialM24;
  5028. result.m[8] = initialM31;
  5029. result.m[9] = initialM32;
  5030. result.m[10] = initialM33;
  5031. result.m[11] = initialM34;
  5032. result.m[12] = initialM41;
  5033. result.m[13] = initialM42;
  5034. result.m[14] = initialM43;
  5035. result.m[15] = initialM44;
  5036. result._markAsUpdated();
  5037. };
  5038. /**
  5039. * Returns the index-th row of the current matrix as a new Vector4.
  5040. */
  5041. Matrix.prototype.getRow = function (index) {
  5042. if (index < 0 || index > 3) {
  5043. return null;
  5044. }
  5045. var i = index * 4;
  5046. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5047. };
  5048. /**
  5049. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5050. * Returns the updated Matrix.
  5051. */
  5052. Matrix.prototype.setRow = function (index, row) {
  5053. if (index < 0 || index > 3) {
  5054. return this;
  5055. }
  5056. var i = index * 4;
  5057. this.m[i + 0] = row.x;
  5058. this.m[i + 1] = row.y;
  5059. this.m[i + 2] = row.z;
  5060. this.m[i + 3] = row.w;
  5061. this._markAsUpdated();
  5062. return this;
  5063. };
  5064. /**
  5065. * Compute the transpose of the matrix.
  5066. * Returns a new Matrix.
  5067. */
  5068. Matrix.prototype.transpose = function () {
  5069. return Matrix.Transpose(this);
  5070. };
  5071. /**
  5072. * Compute the transpose of the matrix.
  5073. * Returns the current matrix.
  5074. */
  5075. Matrix.prototype.transposeToRef = function (result) {
  5076. Matrix.TransposeToRef(this, result);
  5077. return this;
  5078. };
  5079. /**
  5080. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5081. * Returns the updated Matrix.
  5082. */
  5083. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5084. if (index < 0 || index > 3) {
  5085. return this;
  5086. }
  5087. var i = index * 4;
  5088. this.m[i + 0] = x;
  5089. this.m[i + 1] = y;
  5090. this.m[i + 2] = z;
  5091. this.m[i + 3] = w;
  5092. this._markAsUpdated();
  5093. return this;
  5094. };
  5095. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5096. /**
  5097. * Static identity matrix to be used as readonly matrix
  5098. * Must not be updated.
  5099. */
  5100. get: function () {
  5101. return Matrix._identityReadOnly;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. /**
  5107. * Returns a new Matrix set from the 16 passed floats.
  5108. */
  5109. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5110. var result = new Matrix();
  5111. result.m[0] = initialM11;
  5112. result.m[1] = initialM12;
  5113. result.m[2] = initialM13;
  5114. result.m[3] = initialM14;
  5115. result.m[4] = initialM21;
  5116. result.m[5] = initialM22;
  5117. result.m[6] = initialM23;
  5118. result.m[7] = initialM24;
  5119. result.m[8] = initialM31;
  5120. result.m[9] = initialM32;
  5121. result.m[10] = initialM33;
  5122. result.m[11] = initialM34;
  5123. result.m[12] = initialM41;
  5124. result.m[13] = initialM42;
  5125. result.m[14] = initialM43;
  5126. result.m[15] = initialM44;
  5127. return result;
  5128. };
  5129. /**
  5130. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5131. */
  5132. Matrix.Compose = function (scale, rotation, translation) {
  5133. var result = Matrix.Identity();
  5134. Matrix.ComposeToRef(scale, rotation, translation, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5139. */
  5140. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5141. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5142. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5143. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5144. result.setTranslation(translation);
  5145. };
  5146. /**
  5147. * Returns a new indentity Matrix.
  5148. */
  5149. Matrix.Identity = function () {
  5150. 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);
  5151. };
  5152. /**
  5153. * Sets the passed "result" as an identity matrix.
  5154. */
  5155. Matrix.IdentityToRef = function (result) {
  5156. 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);
  5157. };
  5158. /**
  5159. * Returns a new zero Matrix.
  5160. */
  5161. Matrix.Zero = function () {
  5162. 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);
  5163. };
  5164. /**
  5165. * Returns a new rotation matrix for "angle" radians around the X axis.
  5166. */
  5167. Matrix.RotationX = function (angle) {
  5168. var result = new Matrix();
  5169. Matrix.RotationXToRef(angle, result);
  5170. return result;
  5171. };
  5172. /**
  5173. * Returns a new Matrix as the passed inverted one.
  5174. */
  5175. Matrix.Invert = function (source) {
  5176. var result = new Matrix();
  5177. source.invertToRef(result);
  5178. return result;
  5179. };
  5180. /**
  5181. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5182. */
  5183. Matrix.RotationXToRef = function (angle, result) {
  5184. var s = Math.sin(angle);
  5185. var c = Math.cos(angle);
  5186. result.m[0] = 1.0;
  5187. result.m[15] = 1.0;
  5188. result.m[5] = c;
  5189. result.m[10] = c;
  5190. result.m[9] = -s;
  5191. result.m[6] = s;
  5192. result.m[1] = 0.0;
  5193. result.m[2] = 0.0;
  5194. result.m[3] = 0.0;
  5195. result.m[4] = 0.0;
  5196. result.m[7] = 0.0;
  5197. result.m[8] = 0.0;
  5198. result.m[11] = 0.0;
  5199. result.m[12] = 0.0;
  5200. result.m[13] = 0.0;
  5201. result.m[14] = 0.0;
  5202. result._markAsUpdated();
  5203. };
  5204. /**
  5205. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5206. */
  5207. Matrix.RotationY = function (angle) {
  5208. var result = new Matrix();
  5209. Matrix.RotationYToRef(angle, result);
  5210. return result;
  5211. };
  5212. /**
  5213. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5214. */
  5215. Matrix.RotationYToRef = function (angle, result) {
  5216. var s = Math.sin(angle);
  5217. var c = Math.cos(angle);
  5218. result.m[5] = 1.0;
  5219. result.m[15] = 1.0;
  5220. result.m[0] = c;
  5221. result.m[2] = -s;
  5222. result.m[8] = s;
  5223. result.m[10] = c;
  5224. result.m[1] = 0.0;
  5225. result.m[3] = 0.0;
  5226. result.m[4] = 0.0;
  5227. result.m[6] = 0.0;
  5228. result.m[7] = 0.0;
  5229. result.m[9] = 0.0;
  5230. result.m[11] = 0.0;
  5231. result.m[12] = 0.0;
  5232. result.m[13] = 0.0;
  5233. result.m[14] = 0.0;
  5234. result._markAsUpdated();
  5235. };
  5236. /**
  5237. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5238. */
  5239. Matrix.RotationZ = function (angle) {
  5240. var result = new Matrix();
  5241. Matrix.RotationZToRef(angle, result);
  5242. return result;
  5243. };
  5244. /**
  5245. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5246. */
  5247. Matrix.RotationZToRef = function (angle, result) {
  5248. var s = Math.sin(angle);
  5249. var c = Math.cos(angle);
  5250. result.m[10] = 1.0;
  5251. result.m[15] = 1.0;
  5252. result.m[0] = c;
  5253. result.m[1] = s;
  5254. result.m[4] = -s;
  5255. result.m[5] = c;
  5256. result.m[2] = 0.0;
  5257. result.m[3] = 0.0;
  5258. result.m[6] = 0.0;
  5259. result.m[7] = 0.0;
  5260. result.m[8] = 0.0;
  5261. result.m[9] = 0.0;
  5262. result.m[11] = 0.0;
  5263. result.m[12] = 0.0;
  5264. result.m[13] = 0.0;
  5265. result.m[14] = 0.0;
  5266. result._markAsUpdated();
  5267. };
  5268. /**
  5269. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5270. */
  5271. Matrix.RotationAxis = function (axis, angle) {
  5272. var result = Matrix.Zero();
  5273. Matrix.RotationAxisToRef(axis, angle, result);
  5274. return result;
  5275. };
  5276. /**
  5277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5278. */
  5279. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5280. var s = Math.sin(-angle);
  5281. var c = Math.cos(-angle);
  5282. var c1 = 1 - c;
  5283. axis.normalize();
  5284. result.m[0] = (axis.x * axis.x) * c1 + c;
  5285. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5286. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5287. result.m[3] = 0.0;
  5288. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5289. result.m[5] = (axis.y * axis.y) * c1 + c;
  5290. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5291. result.m[7] = 0.0;
  5292. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5293. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5294. result.m[10] = (axis.z * axis.z) * c1 + c;
  5295. result.m[11] = 0.0;
  5296. result.m[15] = 1.0;
  5297. result._markAsUpdated();
  5298. };
  5299. /**
  5300. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5301. */
  5302. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5303. var result = new Matrix();
  5304. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5309. */
  5310. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5311. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5312. this._tempQuaternion.toRotationMatrix(result);
  5313. };
  5314. /**
  5315. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5316. */
  5317. Matrix.Scaling = function (x, y, z) {
  5318. var result = Matrix.Zero();
  5319. Matrix.ScalingToRef(x, y, z, result);
  5320. return result;
  5321. };
  5322. /**
  5323. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5324. */
  5325. Matrix.ScalingToRef = function (x, y, z, result) {
  5326. result.m[0] = x;
  5327. result.m[1] = 0.0;
  5328. result.m[2] = 0.0;
  5329. result.m[3] = 0.0;
  5330. result.m[4] = 0.0;
  5331. result.m[5] = y;
  5332. result.m[6] = 0.0;
  5333. result.m[7] = 0.0;
  5334. result.m[8] = 0.0;
  5335. result.m[9] = 0.0;
  5336. result.m[10] = z;
  5337. result.m[11] = 0.0;
  5338. result.m[12] = 0.0;
  5339. result.m[13] = 0.0;
  5340. result.m[14] = 0.0;
  5341. result.m[15] = 1.0;
  5342. result._markAsUpdated();
  5343. };
  5344. /**
  5345. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5346. */
  5347. Matrix.Translation = function (x, y, z) {
  5348. var result = Matrix.Identity();
  5349. Matrix.TranslationToRef(x, y, z, result);
  5350. return result;
  5351. };
  5352. /**
  5353. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5354. */
  5355. Matrix.TranslationToRef = function (x, y, z, result) {
  5356. 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);
  5357. };
  5358. /**
  5359. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5360. */
  5361. Matrix.Lerp = function (startValue, endValue, gradient) {
  5362. var result = Matrix.Zero();
  5363. for (var index = 0; index < 16; index++) {
  5364. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5365. }
  5366. result._markAsUpdated();
  5367. return result;
  5368. };
  5369. /**
  5370. * Returns a new Matrix whose values are computed by :
  5371. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5372. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5373. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5374. */
  5375. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5376. var startScale = new Vector3(0, 0, 0);
  5377. var startRotation = new Quaternion();
  5378. var startTranslation = new Vector3(0, 0, 0);
  5379. startValue.decompose(startScale, startRotation, startTranslation);
  5380. var endScale = new Vector3(0, 0, 0);
  5381. var endRotation = new Quaternion();
  5382. var endTranslation = new Vector3(0, 0, 0);
  5383. endValue.decompose(endScale, endRotation, endTranslation);
  5384. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5385. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5386. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5387. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5388. };
  5389. /**
  5390. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5391. * This methods works for a Left-Handed system.
  5392. */
  5393. Matrix.LookAtLH = function (eye, target, up) {
  5394. var result = Matrix.Zero();
  5395. Matrix.LookAtLHToRef(eye, target, up, result);
  5396. return result;
  5397. };
  5398. /**
  5399. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5400. * This methods works for a Left-Handed system.
  5401. */
  5402. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5403. // Z axis
  5404. target.subtractToRef(eye, this._zAxis);
  5405. this._zAxis.normalize();
  5406. // X axis
  5407. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5408. if (this._xAxis.lengthSquared() === 0) {
  5409. this._xAxis.x = 1.0;
  5410. }
  5411. else {
  5412. this._xAxis.normalize();
  5413. }
  5414. // Y axis
  5415. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5416. this._yAxis.normalize();
  5417. // Eye angles
  5418. var ex = -Vector3.Dot(this._xAxis, eye);
  5419. var ey = -Vector3.Dot(this._yAxis, eye);
  5420. var ez = -Vector3.Dot(this._zAxis, eye);
  5421. 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);
  5422. };
  5423. /**
  5424. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5425. * This methods works for a Right-Handed system.
  5426. */
  5427. Matrix.LookAtRH = function (eye, target, up) {
  5428. var result = Matrix.Zero();
  5429. Matrix.LookAtRHToRef(eye, target, up, result);
  5430. return result;
  5431. };
  5432. /**
  5433. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5434. * This methods works for a Left-Handed system.
  5435. */
  5436. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5437. // Z axis
  5438. eye.subtractToRef(target, this._zAxis);
  5439. this._zAxis.normalize();
  5440. // X axis
  5441. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5442. if (this._xAxis.lengthSquared() === 0) {
  5443. this._xAxis.x = 1.0;
  5444. }
  5445. else {
  5446. this._xAxis.normalize();
  5447. }
  5448. // Y axis
  5449. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5450. this._yAxis.normalize();
  5451. // Eye angles
  5452. var ex = -Vector3.Dot(this._xAxis, eye);
  5453. var ey = -Vector3.Dot(this._yAxis, eye);
  5454. var ez = -Vector3.Dot(this._zAxis, eye);
  5455. 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);
  5456. };
  5457. /**
  5458. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5459. */
  5460. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5461. var matrix = Matrix.Zero();
  5462. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5463. return matrix;
  5464. };
  5465. /**
  5466. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5467. */
  5468. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5469. var n = znear;
  5470. var f = zfar;
  5471. var a = 2.0 / width;
  5472. var b = 2.0 / height;
  5473. var c = 2.0 / (f - n);
  5474. var d = -(f + n) / (f - n);
  5475. 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);
  5476. };
  5477. /**
  5478. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5479. */
  5480. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5481. var matrix = Matrix.Zero();
  5482. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5483. return matrix;
  5484. };
  5485. /**
  5486. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5489. var n = znear;
  5490. var f = zfar;
  5491. var a = 2.0 / (right - left);
  5492. var b = 2.0 / (top - bottom);
  5493. var c = 2.0 / (f - n);
  5494. var d = -(f + n) / (f - n);
  5495. var i0 = (left + right) / (left - right);
  5496. var i1 = (top + bottom) / (bottom - top);
  5497. 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);
  5498. };
  5499. /**
  5500. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5501. */
  5502. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5503. var matrix = Matrix.Zero();
  5504. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5505. return matrix;
  5506. };
  5507. /**
  5508. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5509. */
  5510. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5511. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5512. result.m[10] *= -1.0;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5516. */
  5517. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. var n = znear;
  5520. var f = zfar;
  5521. var a = 2.0 * n / width;
  5522. var b = 2.0 * n / height;
  5523. var c = (f + n) / (f - n);
  5524. var d = -2.0 * f * n / (f - n);
  5525. 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);
  5526. return matrix;
  5527. };
  5528. /**
  5529. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5530. */
  5531. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5532. var matrix = Matrix.Zero();
  5533. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5534. return matrix;
  5535. };
  5536. /**
  5537. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5540. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5541. var n = znear;
  5542. var f = zfar;
  5543. var t = 1.0 / (Math.tan(fov * 0.5));
  5544. var a = isVerticalFovFixed ? (t / aspect) : t;
  5545. var b = isVerticalFovFixed ? t : (t * aspect);
  5546. var c = (f + n) / (f - n);
  5547. var d = -2.0 * f * n / (f - n);
  5548. 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);
  5549. };
  5550. /**
  5551. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5552. */
  5553. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5556. return matrix;
  5557. };
  5558. /**
  5559. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5560. */
  5561. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5562. //alternatively this could be expressed as:
  5563. // m = PerspectiveFovLHToRef
  5564. // m[10] *= -1.0;
  5565. // m[11] *= -1.0;
  5566. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5567. var n = znear;
  5568. var f = zfar;
  5569. var t = 1.0 / (Math.tan(fov * 0.5));
  5570. var a = isVerticalFovFixed ? (t / aspect) : t;
  5571. var b = isVerticalFovFixed ? t : (t * aspect);
  5572. var c = -(f + n) / (f - n);
  5573. var d = -2 * f * n / (f - n);
  5574. 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);
  5575. };
  5576. /**
  5577. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5578. */
  5579. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5580. if (rightHanded === void 0) { rightHanded = false; }
  5581. var rightHandedFactor = rightHanded ? -1 : 1;
  5582. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5583. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5584. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5585. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5586. var xScale = 2.0 / (leftTan + rightTan);
  5587. var yScale = 2.0 / (upTan + downTan);
  5588. result.m[0] = xScale;
  5589. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5590. result.m[5] = yScale;
  5591. result.m[6] = result.m[7] = 0.0;
  5592. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5593. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5594. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5595. result.m[10] = -zfar / (znear - zfar);
  5596. result.m[11] = 1.0 * rightHandedFactor;
  5597. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5598. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5599. // result.m[14] = (znear * zfar) / (znear - zfar);
  5600. result._markAsUpdated();
  5601. };
  5602. /**
  5603. * Returns the final transformation matrix : world * view * projection * viewport
  5604. */
  5605. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5606. var cw = viewport.width;
  5607. var ch = viewport.height;
  5608. var cx = viewport.x;
  5609. var cy = viewport.y;
  5610. 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);
  5611. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5612. };
  5613. /**
  5614. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5615. */
  5616. Matrix.GetAsMatrix2x2 = function (matrix) {
  5617. return new Float32Array([
  5618. matrix.m[0], matrix.m[1],
  5619. matrix.m[4], matrix.m[5]
  5620. ]);
  5621. };
  5622. /**
  5623. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5624. */
  5625. Matrix.GetAsMatrix3x3 = function (matrix) {
  5626. return new Float32Array([
  5627. matrix.m[0], matrix.m[1], matrix.m[2],
  5628. matrix.m[4], matrix.m[5], matrix.m[6],
  5629. matrix.m[8], matrix.m[9], matrix.m[10]
  5630. ]);
  5631. };
  5632. /**
  5633. * Compute the transpose of the passed Matrix.
  5634. * Returns a new Matrix.
  5635. */
  5636. Matrix.Transpose = function (matrix) {
  5637. var result = new Matrix();
  5638. Matrix.TransposeToRef(matrix, result);
  5639. return result;
  5640. };
  5641. /**
  5642. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5643. */
  5644. Matrix.TransposeToRef = function (matrix, result) {
  5645. result.m[0] = matrix.m[0];
  5646. result.m[1] = matrix.m[4];
  5647. result.m[2] = matrix.m[8];
  5648. result.m[3] = matrix.m[12];
  5649. result.m[4] = matrix.m[1];
  5650. result.m[5] = matrix.m[5];
  5651. result.m[6] = matrix.m[9];
  5652. result.m[7] = matrix.m[13];
  5653. result.m[8] = matrix.m[2];
  5654. result.m[9] = matrix.m[6];
  5655. result.m[10] = matrix.m[10];
  5656. result.m[11] = matrix.m[14];
  5657. result.m[12] = matrix.m[3];
  5658. result.m[13] = matrix.m[7];
  5659. result.m[14] = matrix.m[11];
  5660. result.m[15] = matrix.m[15];
  5661. };
  5662. /**
  5663. * Returns a new Matrix as the reflection matrix across the passed plane.
  5664. */
  5665. Matrix.Reflection = function (plane) {
  5666. var matrix = new Matrix();
  5667. Matrix.ReflectionToRef(plane, matrix);
  5668. return matrix;
  5669. };
  5670. /**
  5671. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5672. */
  5673. Matrix.ReflectionToRef = function (plane, result) {
  5674. plane.normalize();
  5675. var x = plane.normal.x;
  5676. var y = plane.normal.y;
  5677. var z = plane.normal.z;
  5678. var temp = -2 * x;
  5679. var temp2 = -2 * y;
  5680. var temp3 = -2 * z;
  5681. result.m[0] = (temp * x) + 1;
  5682. result.m[1] = temp2 * x;
  5683. result.m[2] = temp3 * x;
  5684. result.m[3] = 0.0;
  5685. result.m[4] = temp * y;
  5686. result.m[5] = (temp2 * y) + 1;
  5687. result.m[6] = temp3 * y;
  5688. result.m[7] = 0.0;
  5689. result.m[8] = temp * z;
  5690. result.m[9] = temp2 * z;
  5691. result.m[10] = (temp3 * z) + 1;
  5692. result.m[11] = 0.0;
  5693. result.m[12] = temp * plane.d;
  5694. result.m[13] = temp2 * plane.d;
  5695. result.m[14] = temp3 * plane.d;
  5696. result.m[15] = 1.0;
  5697. result._markAsUpdated();
  5698. };
  5699. /**
  5700. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5701. */
  5702. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5703. result.m[0] = xaxis.x;
  5704. result.m[1] = xaxis.y;
  5705. result.m[2] = xaxis.z;
  5706. result.m[3] = 0.0;
  5707. result.m[4] = yaxis.x;
  5708. result.m[5] = yaxis.y;
  5709. result.m[6] = yaxis.z;
  5710. result.m[7] = 0.0;
  5711. result.m[8] = zaxis.x;
  5712. result.m[9] = zaxis.y;
  5713. result.m[10] = zaxis.z;
  5714. result.m[11] = 0.0;
  5715. result.m[12] = 0.0;
  5716. result.m[13] = 0.0;
  5717. result.m[14] = 0.0;
  5718. result.m[15] = 1.0;
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5723. */
  5724. Matrix.FromQuaternionToRef = function (quat, result) {
  5725. var xx = quat.x * quat.x;
  5726. var yy = quat.y * quat.y;
  5727. var zz = quat.z * quat.z;
  5728. var xy = quat.x * quat.y;
  5729. var zw = quat.z * quat.w;
  5730. var zx = quat.z * quat.x;
  5731. var yw = quat.y * quat.w;
  5732. var yz = quat.y * quat.z;
  5733. var xw = quat.x * quat.w;
  5734. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5735. result.m[1] = 2.0 * (xy + zw);
  5736. result.m[2] = 2.0 * (zx - yw);
  5737. result.m[3] = 0.0;
  5738. result.m[4] = 2.0 * (xy - zw);
  5739. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5740. result.m[6] = 2.0 * (yz + xw);
  5741. result.m[7] = 0.0;
  5742. result.m[8] = 2.0 * (zx + yw);
  5743. result.m[9] = 2.0 * (yz - xw);
  5744. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5745. result.m[11] = 0.0;
  5746. result.m[12] = 0.0;
  5747. result.m[13] = 0.0;
  5748. result.m[14] = 0.0;
  5749. result.m[15] = 1.0;
  5750. result._markAsUpdated();
  5751. };
  5752. Matrix._tempQuaternion = new Quaternion();
  5753. Matrix._xAxis = Vector3.Zero();
  5754. Matrix._yAxis = Vector3.Zero();
  5755. Matrix._zAxis = Vector3.Zero();
  5756. Matrix._updateFlagSeed = 0;
  5757. Matrix._identityReadOnly = Matrix.Identity();
  5758. return Matrix;
  5759. }());
  5760. BABYLON.Matrix = Matrix;
  5761. var Plane = /** @class */ (function () {
  5762. /**
  5763. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5764. */
  5765. function Plane(a, b, c, d) {
  5766. this.normal = new Vector3(a, b, c);
  5767. this.d = d;
  5768. }
  5769. /**
  5770. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5771. */
  5772. Plane.prototype.asArray = function () {
  5773. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5774. };
  5775. // Methods
  5776. /**
  5777. * Returns a new plane copied from the current Plane.
  5778. */
  5779. Plane.prototype.clone = function () {
  5780. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5781. };
  5782. /**
  5783. * Returns the string "Plane".
  5784. */
  5785. Plane.prototype.getClassName = function () {
  5786. return "Plane";
  5787. };
  5788. /**
  5789. * Returns the Plane hash code.
  5790. */
  5791. Plane.prototype.getHashCode = function () {
  5792. var hash = this.normal.getHashCode();
  5793. hash = (hash * 397) ^ (this.d || 0);
  5794. return hash;
  5795. };
  5796. /**
  5797. * Normalize the current Plane in place.
  5798. * Returns the updated Plane.
  5799. */
  5800. Plane.prototype.normalize = function () {
  5801. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5802. var magnitude = 0.0;
  5803. if (norm !== 0) {
  5804. magnitude = 1.0 / norm;
  5805. }
  5806. this.normal.x *= magnitude;
  5807. this.normal.y *= magnitude;
  5808. this.normal.z *= magnitude;
  5809. this.d *= magnitude;
  5810. return this;
  5811. };
  5812. /**
  5813. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5814. */
  5815. Plane.prototype.transform = function (transformation) {
  5816. var transposedMatrix = Matrix.Transpose(transformation);
  5817. var x = this.normal.x;
  5818. var y = this.normal.y;
  5819. var z = this.normal.z;
  5820. var d = this.d;
  5821. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5822. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5823. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5824. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5825. return new Plane(normalX, normalY, normalZ, finalD);
  5826. };
  5827. /**
  5828. * Returns the dot product (float) of the point coordinates and the plane normal.
  5829. */
  5830. Plane.prototype.dotCoordinate = function (point) {
  5831. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5832. };
  5833. /**
  5834. * Updates the current Plane from the plane defined by the three passed points.
  5835. * Returns the updated Plane.
  5836. */
  5837. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5838. var x1 = point2.x - point1.x;
  5839. var y1 = point2.y - point1.y;
  5840. var z1 = point2.z - point1.z;
  5841. var x2 = point3.x - point1.x;
  5842. var y2 = point3.y - point1.y;
  5843. var z2 = point3.z - point1.z;
  5844. var yz = (y1 * z2) - (z1 * y2);
  5845. var xz = (z1 * x2) - (x1 * z2);
  5846. var xy = (x1 * y2) - (y1 * x2);
  5847. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5848. var invPyth;
  5849. if (pyth !== 0) {
  5850. invPyth = 1.0 / pyth;
  5851. }
  5852. else {
  5853. invPyth = 0.0;
  5854. }
  5855. this.normal.x = yz * invPyth;
  5856. this.normal.y = xz * invPyth;
  5857. this.normal.z = xy * invPyth;
  5858. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5859. return this;
  5860. };
  5861. /**
  5862. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5863. */
  5864. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5865. var dot = Vector3.Dot(this.normal, direction);
  5866. return (dot <= epsilon);
  5867. };
  5868. /**
  5869. * Returns the signed distance (float) from the passed point to the Plane.
  5870. */
  5871. Plane.prototype.signedDistanceTo = function (point) {
  5872. return Vector3.Dot(point, this.normal) + this.d;
  5873. };
  5874. // Statics
  5875. /**
  5876. * Returns a new Plane from the passed array.
  5877. */
  5878. Plane.FromArray = function (array) {
  5879. return new Plane(array[0], array[1], array[2], array[3]);
  5880. };
  5881. /**
  5882. * Returns a new Plane defined by the three passed points.
  5883. */
  5884. Plane.FromPoints = function (point1, point2, point3) {
  5885. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5886. result.copyFromPoints(point1, point2, point3);
  5887. return result;
  5888. };
  5889. /**
  5890. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5891. * Note : the vector "normal" is updated because normalized.
  5892. */
  5893. Plane.FromPositionAndNormal = function (origin, normal) {
  5894. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5895. normal.normalize();
  5896. result.normal = normal;
  5897. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5898. return result;
  5899. };
  5900. /**
  5901. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5902. */
  5903. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5904. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5905. return Vector3.Dot(point, normal) + d;
  5906. };
  5907. return Plane;
  5908. }());
  5909. BABYLON.Plane = Plane;
  5910. var Viewport = /** @class */ (function () {
  5911. /**
  5912. * Creates a Viewport object located at (x, y) and sized (width, height).
  5913. */
  5914. function Viewport(x, y, width, height) {
  5915. this.x = x;
  5916. this.y = y;
  5917. this.width = width;
  5918. this.height = height;
  5919. }
  5920. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5921. if (renderWidthOrEngine.getRenderWidth) {
  5922. var engine = renderWidthOrEngine;
  5923. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5924. }
  5925. var renderWidth = renderWidthOrEngine;
  5926. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5927. };
  5928. /**
  5929. * Returns a new Viewport copied from the current one.
  5930. */
  5931. Viewport.prototype.clone = function () {
  5932. return new Viewport(this.x, this.y, this.width, this.height);
  5933. };
  5934. return Viewport;
  5935. }());
  5936. BABYLON.Viewport = Viewport;
  5937. var Frustum = /** @class */ (function () {
  5938. function Frustum() {
  5939. }
  5940. /**
  5941. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5942. */
  5943. Frustum.GetPlanes = function (transform) {
  5944. var frustumPlanes = [];
  5945. for (var index = 0; index < 6; index++) {
  5946. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5947. }
  5948. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5949. return frustumPlanes;
  5950. };
  5951. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5955. frustumPlane.d = transform.m[15] + transform.m[14];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5962. frustumPlane.d = transform.m[15] - transform.m[14];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5967. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5968. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5969. frustumPlane.d = transform.m[15] + transform.m[12];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5974. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5975. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5976. frustumPlane.d = transform.m[15] - transform.m[12];
  5977. frustumPlane.normalize();
  5978. };
  5979. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5980. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5981. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5982. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5983. frustumPlane.d = transform.m[15] - transform.m[13];
  5984. frustumPlane.normalize();
  5985. };
  5986. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5987. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5988. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5989. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5990. frustumPlane.d = transform.m[15] + transform.m[13];
  5991. frustumPlane.normalize();
  5992. };
  5993. /**
  5994. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5995. */
  5996. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5997. // Near
  5998. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5999. // Far
  6000. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6001. // Left
  6002. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6003. // Right
  6004. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6005. // Top
  6006. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6007. // Bottom
  6008. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6009. };
  6010. return Frustum;
  6011. }());
  6012. BABYLON.Frustum = Frustum;
  6013. var Space;
  6014. (function (Space) {
  6015. Space[Space["LOCAL"] = 0] = "LOCAL";
  6016. Space[Space["WORLD"] = 1] = "WORLD";
  6017. Space[Space["BONE"] = 2] = "BONE";
  6018. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6019. var Axis = /** @class */ (function () {
  6020. function Axis() {
  6021. }
  6022. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6023. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6024. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6025. return Axis;
  6026. }());
  6027. BABYLON.Axis = Axis;
  6028. ;
  6029. var BezierCurve = /** @class */ (function () {
  6030. function BezierCurve() {
  6031. }
  6032. /**
  6033. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6034. */
  6035. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6036. // Extract X (which is equal to time here)
  6037. var f0 = 1 - 3 * x2 + 3 * x1;
  6038. var f1 = 3 * x2 - 6 * x1;
  6039. var f2 = 3 * x1;
  6040. var refinedT = t;
  6041. for (var i = 0; i < 5; i++) {
  6042. var refinedT2 = refinedT * refinedT;
  6043. var refinedT3 = refinedT2 * refinedT;
  6044. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6045. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6046. refinedT -= (x - t) * slope;
  6047. refinedT = Math.min(1, Math.max(0, refinedT));
  6048. }
  6049. // Resolve cubic bezier for the given x
  6050. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6051. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6052. Math.pow(refinedT, 3);
  6053. };
  6054. return BezierCurve;
  6055. }());
  6056. BABYLON.BezierCurve = BezierCurve;
  6057. var Orientation;
  6058. (function (Orientation) {
  6059. Orientation[Orientation["CW"] = 0] = "CW";
  6060. Orientation[Orientation["CCW"] = 1] = "CCW";
  6061. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6062. var Angle = /** @class */ (function () {
  6063. /**
  6064. * Creates an Angle object of "radians" radians (float).
  6065. */
  6066. function Angle(radians) {
  6067. var _this = this;
  6068. /**
  6069. * Returns the Angle value in degrees (float).
  6070. */
  6071. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6072. /**
  6073. * Returns the Angle value in radians (float).
  6074. */
  6075. this.radians = function () { return _this._radians; };
  6076. this._radians = radians;
  6077. if (this._radians < 0.0)
  6078. this._radians += (2.0 * Math.PI);
  6079. }
  6080. /**
  6081. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6082. */
  6083. Angle.BetweenTwoPoints = function (a, b) {
  6084. var delta = b.subtract(a);
  6085. var theta = Math.atan2(delta.y, delta.x);
  6086. return new Angle(theta);
  6087. };
  6088. /**
  6089. * Returns a new Angle object from the passed float in radians.
  6090. */
  6091. Angle.FromRadians = function (radians) {
  6092. return new Angle(radians);
  6093. };
  6094. /**
  6095. * Returns a new Angle object from the passed float in degrees.
  6096. */
  6097. Angle.FromDegrees = function (degrees) {
  6098. return new Angle(degrees * Math.PI / 180.0);
  6099. };
  6100. return Angle;
  6101. }());
  6102. BABYLON.Angle = Angle;
  6103. var Arc2 = /** @class */ (function () {
  6104. /**
  6105. * Creates an Arc object from the three passed points : start, middle and end.
  6106. */
  6107. function Arc2(startPoint, midPoint, endPoint) {
  6108. this.startPoint = startPoint;
  6109. this.midPoint = midPoint;
  6110. this.endPoint = endPoint;
  6111. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6112. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6113. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6114. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6115. 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);
  6116. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6117. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6118. var a1 = this.startAngle.degrees();
  6119. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6120. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6121. // angles correction
  6122. if (a2 - a1 > +180.0)
  6123. a2 -= 360.0;
  6124. if (a2 - a1 < -180.0)
  6125. a2 += 360.0;
  6126. if (a3 - a2 > +180.0)
  6127. a3 -= 360.0;
  6128. if (a3 - a2 < -180.0)
  6129. a3 += 360.0;
  6130. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6131. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6132. }
  6133. return Arc2;
  6134. }());
  6135. BABYLON.Arc2 = Arc2;
  6136. var Path2 = /** @class */ (function () {
  6137. /**
  6138. * Creates a Path2 object from the starting 2D coordinates x and y.
  6139. */
  6140. function Path2(x, y) {
  6141. this._points = new Array();
  6142. this._length = 0.0;
  6143. this.closed = false;
  6144. this._points.push(new Vector2(x, y));
  6145. }
  6146. /**
  6147. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6148. * Returns the updated Path2.
  6149. */
  6150. Path2.prototype.addLineTo = function (x, y) {
  6151. if (this.closed) {
  6152. //Tools.Error("cannot add lines to closed paths");
  6153. return this;
  6154. }
  6155. var newPoint = new Vector2(x, y);
  6156. var previousPoint = this._points[this._points.length - 1];
  6157. this._points.push(newPoint);
  6158. this._length += newPoint.subtract(previousPoint).length();
  6159. return this;
  6160. };
  6161. /**
  6162. * 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.
  6163. * Returns the updated Path2.
  6164. */
  6165. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6166. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6167. if (this.closed) {
  6168. //Tools.Error("cannot add arcs to closed paths");
  6169. return this;
  6170. }
  6171. var startPoint = this._points[this._points.length - 1];
  6172. var midPoint = new Vector2(midX, midY);
  6173. var endPoint = new Vector2(endX, endY);
  6174. var arc = new Arc2(startPoint, midPoint, endPoint);
  6175. var increment = arc.angle.radians() / numberOfSegments;
  6176. if (arc.orientation === Orientation.CW)
  6177. increment *= -1;
  6178. var currentAngle = arc.startAngle.radians() + increment;
  6179. for (var i = 0; i < numberOfSegments; i++) {
  6180. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6181. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6182. this.addLineTo(x, y);
  6183. currentAngle += increment;
  6184. }
  6185. return this;
  6186. };
  6187. /**
  6188. * Closes the Path2.
  6189. * Returns the Path2.
  6190. */
  6191. Path2.prototype.close = function () {
  6192. this.closed = true;
  6193. return this;
  6194. };
  6195. /**
  6196. * Returns the Path2 total length (float).
  6197. */
  6198. Path2.prototype.length = function () {
  6199. var result = this._length;
  6200. if (!this.closed) {
  6201. var lastPoint = this._points[this._points.length - 1];
  6202. var firstPoint = this._points[0];
  6203. result += (firstPoint.subtract(lastPoint).length());
  6204. }
  6205. return result;
  6206. };
  6207. /**
  6208. * Returns the Path2 internal array of points.
  6209. */
  6210. Path2.prototype.getPoints = function () {
  6211. return this._points;
  6212. };
  6213. /**
  6214. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6215. */
  6216. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6217. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6218. //Tools.Error("normalized length position should be between 0 and 1.");
  6219. return Vector2.Zero();
  6220. }
  6221. var lengthPosition = normalizedLengthPosition * this.length();
  6222. var previousOffset = 0;
  6223. for (var i = 0; i < this._points.length; i++) {
  6224. var j = (i + 1) % this._points.length;
  6225. var a = this._points[i];
  6226. var b = this._points[j];
  6227. var bToA = b.subtract(a);
  6228. var nextOffset = (bToA.length() + previousOffset);
  6229. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6230. var dir = bToA.normalize();
  6231. var localOffset = lengthPosition - previousOffset;
  6232. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6233. }
  6234. previousOffset = nextOffset;
  6235. }
  6236. //Tools.Error("internal error");
  6237. return Vector2.Zero();
  6238. };
  6239. /**
  6240. * Returns a new Path2 starting at the coordinates (x, y).
  6241. */
  6242. Path2.StartingAt = function (x, y) {
  6243. return new Path2(x, y);
  6244. };
  6245. return Path2;
  6246. }());
  6247. BABYLON.Path2 = Path2;
  6248. var Path3D = /** @class */ (function () {
  6249. /**
  6250. * new Path3D(path, normal, raw)
  6251. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6252. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6253. * path : an array of Vector3, the curve axis of the Path3D
  6254. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6255. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6256. */
  6257. function Path3D(path, firstNormal, raw) {
  6258. if (firstNormal === void 0) { firstNormal = null; }
  6259. this.path = path;
  6260. this._curve = new Array();
  6261. this._distances = new Array();
  6262. this._tangents = new Array();
  6263. this._normals = new Array();
  6264. this._binormals = new Array();
  6265. for (var p = 0; p < path.length; p++) {
  6266. this._curve[p] = path[p].clone(); // hard copy
  6267. }
  6268. this._raw = raw || false;
  6269. this._compute(firstNormal);
  6270. }
  6271. /**
  6272. * Returns the Path3D array of successive Vector3 designing its curve.
  6273. */
  6274. Path3D.prototype.getCurve = function () {
  6275. return this._curve;
  6276. };
  6277. /**
  6278. * Returns an array populated with tangent vectors on each Path3D curve point.
  6279. */
  6280. Path3D.prototype.getTangents = function () {
  6281. return this._tangents;
  6282. };
  6283. /**
  6284. * Returns an array populated with normal vectors on each Path3D curve point.
  6285. */
  6286. Path3D.prototype.getNormals = function () {
  6287. return this._normals;
  6288. };
  6289. /**
  6290. * Returns an array populated with binormal vectors on each Path3D curve point.
  6291. */
  6292. Path3D.prototype.getBinormals = function () {
  6293. return this._binormals;
  6294. };
  6295. /**
  6296. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6297. */
  6298. Path3D.prototype.getDistances = function () {
  6299. return this._distances;
  6300. };
  6301. /**
  6302. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6303. * Returns the same object updated.
  6304. */
  6305. Path3D.prototype.update = function (path, firstNormal) {
  6306. if (firstNormal === void 0) { firstNormal = null; }
  6307. for (var p = 0; p < path.length; p++) {
  6308. this._curve[p].x = path[p].x;
  6309. this._curve[p].y = path[p].y;
  6310. this._curve[p].z = path[p].z;
  6311. }
  6312. this._compute(firstNormal);
  6313. return this;
  6314. };
  6315. // private function compute() : computes tangents, normals and binormals
  6316. Path3D.prototype._compute = function (firstNormal) {
  6317. var l = this._curve.length;
  6318. // first and last tangents
  6319. this._tangents[0] = this._getFirstNonNullVector(0);
  6320. if (!this._raw) {
  6321. this._tangents[0].normalize();
  6322. }
  6323. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6324. if (!this._raw) {
  6325. this._tangents[l - 1].normalize();
  6326. }
  6327. // normals and binormals at first point : arbitrary vector with _normalVector()
  6328. var tg0 = this._tangents[0];
  6329. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6330. this._normals[0] = pp0;
  6331. if (!this._raw) {
  6332. this._normals[0].normalize();
  6333. }
  6334. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6335. if (!this._raw) {
  6336. this._binormals[0].normalize();
  6337. }
  6338. this._distances[0] = 0.0;
  6339. // normals and binormals : next points
  6340. var prev; // previous vector (segment)
  6341. var cur; // current vector (segment)
  6342. var curTang; // current tangent
  6343. // previous normal
  6344. var prevBinor; // previous binormal
  6345. for (var i = 1; i < l; i++) {
  6346. // tangents
  6347. prev = this._getLastNonNullVector(i);
  6348. if (i < l - 1) {
  6349. cur = this._getFirstNonNullVector(i);
  6350. this._tangents[i] = prev.add(cur);
  6351. this._tangents[i].normalize();
  6352. }
  6353. this._distances[i] = this._distances[i - 1] + prev.length();
  6354. // normals and binormals
  6355. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6356. curTang = this._tangents[i];
  6357. prevBinor = this._binormals[i - 1];
  6358. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6359. if (!this._raw) {
  6360. this._normals[i].normalize();
  6361. }
  6362. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6363. if (!this._raw) {
  6364. this._binormals[i].normalize();
  6365. }
  6366. }
  6367. };
  6368. // private function getFirstNonNullVector(index)
  6369. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6370. Path3D.prototype._getFirstNonNullVector = function (index) {
  6371. var i = 1;
  6372. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6373. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6374. i++;
  6375. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6376. }
  6377. return nNVector;
  6378. };
  6379. // private function getLastNonNullVector(index)
  6380. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6381. Path3D.prototype._getLastNonNullVector = function (index) {
  6382. var i = 1;
  6383. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6384. while (nLVector.length() === 0 && index > i + 1) {
  6385. i++;
  6386. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6387. }
  6388. return nLVector;
  6389. };
  6390. // private function normalVector(v0, vt, va) :
  6391. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6392. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6393. Path3D.prototype._normalVector = function (v0, vt, va) {
  6394. var normal0;
  6395. var tgl = vt.length();
  6396. if (tgl === 0.0) {
  6397. tgl = 1.0;
  6398. }
  6399. if (va === undefined || va === null) {
  6400. var point;
  6401. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6402. point = new Vector3(0.0, -1.0, 0.0);
  6403. }
  6404. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6405. point = new Vector3(1.0, 0.0, 0.0);
  6406. }
  6407. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6408. point = new Vector3(0.0, 0.0, 1.0);
  6409. }
  6410. else {
  6411. point = Vector3.Zero();
  6412. }
  6413. normal0 = Vector3.Cross(vt, point);
  6414. }
  6415. else {
  6416. normal0 = Vector3.Cross(vt, va);
  6417. Vector3.CrossToRef(normal0, vt, normal0);
  6418. }
  6419. normal0.normalize();
  6420. return normal0;
  6421. };
  6422. return Path3D;
  6423. }());
  6424. BABYLON.Path3D = Path3D;
  6425. var Curve3 = /** @class */ (function () {
  6426. /**
  6427. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6428. * A Curve3 is designed from a series of successive Vector3.
  6429. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6430. */
  6431. function Curve3(points) {
  6432. this._length = 0.0;
  6433. this._points = points;
  6434. this._length = this._computeLength(points);
  6435. }
  6436. /**
  6437. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6438. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6439. * @param v1 (Vector3) the control point
  6440. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6441. * @param nbPoints (integer) the wanted number of points in the curve
  6442. */
  6443. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6444. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6445. var bez = new Array();
  6446. var equation = function (t, val0, val1, val2) {
  6447. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6448. return res;
  6449. };
  6450. for (var i = 0; i <= nbPoints; i++) {
  6451. 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)));
  6452. }
  6453. return new Curve3(bez);
  6454. };
  6455. /**
  6456. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6457. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6458. * @param v1 (Vector3) the first control point
  6459. * @param v2 (Vector3) the second control point
  6460. * @param v3 (Vector3) the end point of the Cubic Bezier
  6461. * @param nbPoints (integer) the wanted number of points in the curve
  6462. */
  6463. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6464. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6465. var bez = new Array();
  6466. var equation = function (t, val0, val1, val2, val3) {
  6467. 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;
  6468. return res;
  6469. };
  6470. for (var i = 0; i <= nbPoints; i++) {
  6471. 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)));
  6472. }
  6473. return new Curve3(bez);
  6474. };
  6475. /**
  6476. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6477. * @param p1 (Vector3) the origin point of the Hermite Spline
  6478. * @param t1 (Vector3) the tangent vector at the origin point
  6479. * @param p2 (Vector3) the end point of the Hermite Spline
  6480. * @param t2 (Vector3) the tangent vector at the end point
  6481. * @param nbPoints (integer) the wanted number of points in the curve
  6482. */
  6483. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6484. var hermite = new Array();
  6485. var step = 1.0 / nbPoints;
  6486. for (var i = 0; i <= nbPoints; i++) {
  6487. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6488. }
  6489. return new Curve3(hermite);
  6490. };
  6491. /**
  6492. * Returns a Curve3 object along a CatmullRom Spline curve :
  6493. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6494. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6495. */
  6496. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6497. var totalPoints = new Array();
  6498. totalPoints.push(points[0].clone());
  6499. Array.prototype.push.apply(totalPoints, points);
  6500. totalPoints.push(points[points.length - 1].clone());
  6501. var catmullRom = new Array();
  6502. var step = 1.0 / nbPoints;
  6503. var amount = 0.0;
  6504. for (var i = 0; i < totalPoints.length - 3; i++) {
  6505. amount = 0;
  6506. for (var c = 0; c < nbPoints; c++) {
  6507. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6508. amount += step;
  6509. }
  6510. }
  6511. i--;
  6512. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6513. return new Curve3(catmullRom);
  6514. };
  6515. /**
  6516. * Returns the Curve3 stored array of successive Vector3
  6517. */
  6518. Curve3.prototype.getPoints = function () {
  6519. return this._points;
  6520. };
  6521. /**
  6522. * Returns the computed length (float) of the curve.
  6523. */
  6524. Curve3.prototype.length = function () {
  6525. return this._length;
  6526. };
  6527. /**
  6528. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6529. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6530. * curveA and curveB keep unchanged.
  6531. */
  6532. Curve3.prototype.continue = function (curve) {
  6533. var lastPoint = this._points[this._points.length - 1];
  6534. var continuedPoints = this._points.slice();
  6535. var curvePoints = curve.getPoints();
  6536. for (var i = 1; i < curvePoints.length; i++) {
  6537. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6538. }
  6539. var continuedCurve = new Curve3(continuedPoints);
  6540. return continuedCurve;
  6541. };
  6542. Curve3.prototype._computeLength = function (path) {
  6543. var l = 0;
  6544. for (var i = 1; i < path.length; i++) {
  6545. l += (path[i].subtract(path[i - 1])).length();
  6546. }
  6547. return l;
  6548. };
  6549. return Curve3;
  6550. }());
  6551. BABYLON.Curve3 = Curve3;
  6552. // Vertex formats
  6553. var PositionNormalVertex = /** @class */ (function () {
  6554. function PositionNormalVertex(position, normal) {
  6555. if (position === void 0) { position = Vector3.Zero(); }
  6556. if (normal === void 0) { normal = Vector3.Up(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. }
  6560. PositionNormalVertex.prototype.clone = function () {
  6561. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6562. };
  6563. return PositionNormalVertex;
  6564. }());
  6565. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6566. var PositionNormalTextureVertex = /** @class */ (function () {
  6567. function PositionNormalTextureVertex(position, normal, uv) {
  6568. if (position === void 0) { position = Vector3.Zero(); }
  6569. if (normal === void 0) { normal = Vector3.Up(); }
  6570. if (uv === void 0) { uv = Vector2.Zero(); }
  6571. this.position = position;
  6572. this.normal = normal;
  6573. this.uv = uv;
  6574. }
  6575. PositionNormalTextureVertex.prototype.clone = function () {
  6576. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6577. };
  6578. return PositionNormalTextureVertex;
  6579. }());
  6580. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6581. // Temporary pre-allocated objects for engine internal use
  6582. // usage in any internal function :
  6583. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6584. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6585. var Tmp = /** @class */ (function () {
  6586. function Tmp() {
  6587. }
  6588. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6589. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6590. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6591. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6592. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6593. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6594. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6595. Matrix.Zero(), Matrix.Zero(),
  6596. Matrix.Zero(), Matrix.Zero(),
  6597. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6598. return Tmp;
  6599. }());
  6600. BABYLON.Tmp = Tmp;
  6601. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6602. var MathTmp = /** @class */ (function () {
  6603. function MathTmp() {
  6604. }
  6605. MathTmp.Vector3 = [Vector3.Zero()];
  6606. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6607. MathTmp.Quaternion = [Quaternion.Zero()];
  6608. return MathTmp;
  6609. }());
  6610. })(BABYLON || (BABYLON = {}));
  6611. //# sourceMappingURL=babylon.math.js.map
  6612. var BABYLON;
  6613. (function (BABYLON) {
  6614. var Scalar = /** @class */ (function () {
  6615. function Scalar() {
  6616. }
  6617. /**
  6618. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6619. */
  6620. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6621. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6622. var num = a - b;
  6623. return -epsilon <= num && num <= epsilon;
  6624. };
  6625. /**
  6626. * Returns a string : the upper case translation of the number i to hexadecimal.
  6627. */
  6628. Scalar.ToHex = function (i) {
  6629. var str = i.toString(16);
  6630. if (i <= 15) {
  6631. return ("0" + str).toUpperCase();
  6632. }
  6633. return str.toUpperCase();
  6634. };
  6635. /**
  6636. * Returns -1 if value is negative and +1 is value is positive.
  6637. * Returns the value itself if it's equal to zero.
  6638. */
  6639. Scalar.Sign = function (value) {
  6640. value = +value; // convert to a number
  6641. if (value === 0 || isNaN(value))
  6642. return value;
  6643. return value > 0 ? 1 : -1;
  6644. };
  6645. /**
  6646. * Returns the value itself if it's between min and max.
  6647. * Returns min if the value is lower than min.
  6648. * Returns max if the value is greater than max.
  6649. */
  6650. Scalar.Clamp = function (value, min, max) {
  6651. if (min === void 0) { min = 0; }
  6652. if (max === void 0) { max = 1; }
  6653. return Math.min(max, Math.max(min, value));
  6654. };
  6655. /**
  6656. * Returns the log2 of value.
  6657. */
  6658. Scalar.Log2 = function (value) {
  6659. return Math.log(value) * Math.LOG2E;
  6660. };
  6661. /**
  6662. * Loops the value, so that it is never larger than length and never smaller than 0.
  6663. *
  6664. * This is similar to the modulo operator but it works with floating point numbers.
  6665. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6666. * With t = 5 and length = 2.5, the result would be 0.0.
  6667. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6668. */
  6669. Scalar.Repeat = function (value, length) {
  6670. return value - Math.floor(value / length) * length;
  6671. };
  6672. /**
  6673. * Normalize the value between 0.0 and 1.0 using min and max values
  6674. */
  6675. Scalar.Normalize = function (value, min, max) {
  6676. return (value - min) / (max - min);
  6677. };
  6678. /**
  6679. * Denormalize the value from 0.0 and 1.0 using min and max values
  6680. */
  6681. Scalar.Denormalize = function (normalized, min, max) {
  6682. return (normalized * (max - min) + min);
  6683. };
  6684. /**
  6685. * Calculates the shortest difference between two given angles given in degrees.
  6686. */
  6687. Scalar.DeltaAngle = function (current, target) {
  6688. var num = Scalar.Repeat(target - current, 360.0);
  6689. if (num > 180.0) {
  6690. num -= 360.0;
  6691. }
  6692. return num;
  6693. };
  6694. /**
  6695. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6696. *
  6697. * The returned value will move back and forth between 0 and length
  6698. */
  6699. Scalar.PingPong = function (tx, length) {
  6700. var t = Scalar.Repeat(tx, length * 2.0);
  6701. return length - Math.abs(t - length);
  6702. };
  6703. /**
  6704. * Interpolates between min and max with smoothing at the limits.
  6705. *
  6706. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6707. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6708. */
  6709. Scalar.SmoothStep = function (from, to, tx) {
  6710. var t = Scalar.Clamp(tx);
  6711. t = -2.0 * t * t * t + 3.0 * t * t;
  6712. return to * t + from * (1.0 - t);
  6713. };
  6714. /**
  6715. * Moves a value current towards target.
  6716. *
  6717. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6718. * Negative values of maxDelta pushes the value away from target.
  6719. */
  6720. Scalar.MoveTowards = function (current, target, maxDelta) {
  6721. var result = 0;
  6722. if (Math.abs(target - current) <= maxDelta) {
  6723. result = target;
  6724. }
  6725. else {
  6726. result = current + Scalar.Sign(target - current) * maxDelta;
  6727. }
  6728. return result;
  6729. };
  6730. /**
  6731. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6732. *
  6733. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6734. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6735. */
  6736. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6737. var num = Scalar.DeltaAngle(current, target);
  6738. var result = 0;
  6739. if (-maxDelta < num && num < maxDelta) {
  6740. result = target;
  6741. }
  6742. else {
  6743. target = current + num;
  6744. result = Scalar.MoveTowards(current, target, maxDelta);
  6745. }
  6746. return result;
  6747. };
  6748. /**
  6749. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6750. */
  6751. Scalar.Lerp = function (start, end, amount) {
  6752. return start + ((end - start) * amount);
  6753. };
  6754. /**
  6755. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6756. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6757. */
  6758. Scalar.LerpAngle = function (start, end, amount) {
  6759. var num = Scalar.Repeat(end - start, 360.0);
  6760. if (num > 180.0) {
  6761. num -= 360.0;
  6762. }
  6763. return start + num * Scalar.Clamp(amount);
  6764. };
  6765. /**
  6766. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6767. */
  6768. Scalar.InverseLerp = function (a, b, value) {
  6769. var result = 0;
  6770. if (a != b) {
  6771. result = Scalar.Clamp((value - a) / (b - a));
  6772. }
  6773. else {
  6774. result = 0.0;
  6775. }
  6776. return result;
  6777. };
  6778. /**
  6779. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6780. */
  6781. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6782. var squared = amount * amount;
  6783. var cubed = amount * squared;
  6784. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6785. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6786. var part3 = (cubed - (2.0 * squared)) + amount;
  6787. var part4 = cubed - squared;
  6788. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6789. };
  6790. /**
  6791. * Returns a random float number between and min and max values
  6792. */
  6793. Scalar.RandomRange = function (min, max) {
  6794. if (min === max)
  6795. return min;
  6796. return ((Math.random() * (max - min)) + min);
  6797. };
  6798. /**
  6799. * This function returns percentage of a number in a given range.
  6800. *
  6801. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6802. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6803. */
  6804. Scalar.RangeToPercent = function (number, min, max) {
  6805. return ((number - min) / (max - min));
  6806. };
  6807. /**
  6808. * This function returns number that corresponds to the percentage in a given range.
  6809. *
  6810. * PercentToRange(0.34,0,100) will return 34.
  6811. */
  6812. Scalar.PercentToRange = function (percent, min, max) {
  6813. return ((max - min) * percent + min);
  6814. };
  6815. /**
  6816. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6817. * @param angle The angle to normalize in radian.
  6818. * @return The converted angle.
  6819. */
  6820. Scalar.NormalizeRadians = function (angle) {
  6821. // More precise but slower version kept for reference.
  6822. // angle = angle % Tools.TwoPi;
  6823. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6824. //if (angle > Math.PI) {
  6825. // angle -= Tools.TwoPi;
  6826. //}
  6827. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6828. return angle;
  6829. };
  6830. /**
  6831. * Two pi constants convenient for computation.
  6832. */
  6833. Scalar.TwoPi = Math.PI * 2;
  6834. return Scalar;
  6835. }());
  6836. BABYLON.Scalar = Scalar;
  6837. })(BABYLON || (BABYLON = {}));
  6838. //# sourceMappingURL=babylon.math.scalar.js.map
  6839. //# sourceMappingURL=babylon.mixins.js.map
  6840. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6841. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6842. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6843. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6844. //# sourceMappingURL=babylon.webgl2.js.map
  6845. var BABYLON;
  6846. (function (BABYLON) {
  6847. var __decoratorInitialStore = {};
  6848. var __mergedStore = {};
  6849. var _copySource = function (creationFunction, source, instanciate) {
  6850. var destination = creationFunction();
  6851. // Tags
  6852. if (BABYLON.Tags) {
  6853. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6854. }
  6855. var classStore = getMergedStore(destination);
  6856. // Properties
  6857. for (var property in classStore) {
  6858. var propertyDescriptor = classStore[property];
  6859. var sourceProperty = source[property];
  6860. var propertyType = propertyDescriptor.type;
  6861. if (sourceProperty !== undefined && sourceProperty !== null) {
  6862. switch (propertyType) {
  6863. case 0: // Value
  6864. case 6:// Mesh reference
  6865. destination[property] = sourceProperty;
  6866. break;
  6867. case 1:// Texture
  6868. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6869. break;
  6870. case 2: // Color3
  6871. case 3: // FresnelParameters
  6872. case 4: // Vector2
  6873. case 5: // Vector3
  6874. case 7: // Color Curves
  6875. case 10:// Quaternion
  6876. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6877. break;
  6878. }
  6879. }
  6880. }
  6881. return destination;
  6882. };
  6883. function getDirectStore(target) {
  6884. var classKey = target.getClassName();
  6885. if (!__decoratorInitialStore[classKey]) {
  6886. __decoratorInitialStore[classKey] = {};
  6887. }
  6888. return __decoratorInitialStore[classKey];
  6889. }
  6890. /**
  6891. * Return the list of properties flagged as serializable
  6892. * @param target: host object
  6893. */
  6894. function getMergedStore(target) {
  6895. var classKey = target.getClassName();
  6896. if (__mergedStore[classKey]) {
  6897. return __mergedStore[classKey];
  6898. }
  6899. __mergedStore[classKey] = {};
  6900. var store = __mergedStore[classKey];
  6901. var currentTarget = target;
  6902. var currentKey = classKey;
  6903. while (currentKey) {
  6904. var initialStore = __decoratorInitialStore[currentKey];
  6905. for (var property in initialStore) {
  6906. store[property] = initialStore[property];
  6907. }
  6908. var parent_1 = void 0;
  6909. var done = false;
  6910. do {
  6911. parent_1 = Object.getPrototypeOf(currentTarget);
  6912. if (!parent_1.getClassName) {
  6913. done = true;
  6914. break;
  6915. }
  6916. if (parent_1.getClassName() !== currentKey) {
  6917. break;
  6918. }
  6919. currentTarget = parent_1;
  6920. } while (parent_1);
  6921. if (done) {
  6922. break;
  6923. }
  6924. currentKey = parent_1.getClassName();
  6925. currentTarget = parent_1;
  6926. }
  6927. return store;
  6928. }
  6929. function generateSerializableMember(type, sourceName) {
  6930. return function (target, propertyKey) {
  6931. var classStore = getDirectStore(target);
  6932. if (!classStore[propertyKey]) {
  6933. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6934. }
  6935. };
  6936. }
  6937. function generateExpandMember(setCallback, targetKey) {
  6938. if (targetKey === void 0) { targetKey = null; }
  6939. return function (target, propertyKey) {
  6940. var key = targetKey || ("_" + propertyKey);
  6941. Object.defineProperty(target, propertyKey, {
  6942. get: function () {
  6943. return this[key];
  6944. },
  6945. set: function (value) {
  6946. if (this[key] === value) {
  6947. return;
  6948. }
  6949. this[key] = value;
  6950. target[setCallback].apply(this);
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. };
  6956. }
  6957. function expandToProperty(callback, targetKey) {
  6958. if (targetKey === void 0) { targetKey = null; }
  6959. return generateExpandMember(callback, targetKey);
  6960. }
  6961. BABYLON.expandToProperty = expandToProperty;
  6962. function serialize(sourceName) {
  6963. return generateSerializableMember(0, sourceName); // value member
  6964. }
  6965. BABYLON.serialize = serialize;
  6966. function serializeAsTexture(sourceName) {
  6967. return generateSerializableMember(1, sourceName); // texture member
  6968. }
  6969. BABYLON.serializeAsTexture = serializeAsTexture;
  6970. function serializeAsColor3(sourceName) {
  6971. return generateSerializableMember(2, sourceName); // color3 member
  6972. }
  6973. BABYLON.serializeAsColor3 = serializeAsColor3;
  6974. function serializeAsFresnelParameters(sourceName) {
  6975. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6976. }
  6977. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6978. function serializeAsVector2(sourceName) {
  6979. return generateSerializableMember(4, sourceName); // vector2 member
  6980. }
  6981. BABYLON.serializeAsVector2 = serializeAsVector2;
  6982. function serializeAsVector3(sourceName) {
  6983. return generateSerializableMember(5, sourceName); // vector3 member
  6984. }
  6985. BABYLON.serializeAsVector3 = serializeAsVector3;
  6986. function serializeAsMeshReference(sourceName) {
  6987. return generateSerializableMember(6, sourceName); // mesh reference member
  6988. }
  6989. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6990. function serializeAsColorCurves(sourceName) {
  6991. return generateSerializableMember(7, sourceName); // color curves
  6992. }
  6993. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6994. function serializeAsColor4(sourceName) {
  6995. return generateSerializableMember(8, sourceName); // color 4
  6996. }
  6997. BABYLON.serializeAsColor4 = serializeAsColor4;
  6998. function serializeAsImageProcessingConfiguration(sourceName) {
  6999. return generateSerializableMember(9, sourceName); // image processing
  7000. }
  7001. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7002. function serializeAsQuaternion(sourceName) {
  7003. return generateSerializableMember(10, sourceName); // quaternion member
  7004. }
  7005. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7006. var SerializationHelper = /** @class */ (function () {
  7007. function SerializationHelper() {
  7008. }
  7009. SerializationHelper.Serialize = function (entity, serializationObject) {
  7010. if (!serializationObject) {
  7011. serializationObject = {};
  7012. }
  7013. // Tags
  7014. if (BABYLON.Tags) {
  7015. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7016. }
  7017. var serializedProperties = getMergedStore(entity);
  7018. // Properties
  7019. for (var property in serializedProperties) {
  7020. var propertyDescriptor = serializedProperties[property];
  7021. var targetPropertyName = propertyDescriptor.sourceName || property;
  7022. var propertyType = propertyDescriptor.type;
  7023. var sourceProperty = entity[property];
  7024. if (sourceProperty !== undefined && sourceProperty !== null) {
  7025. switch (propertyType) {
  7026. case 0:// Value
  7027. serializationObject[targetPropertyName] = sourceProperty;
  7028. break;
  7029. case 1:// Texture
  7030. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7031. break;
  7032. case 2:// Color3
  7033. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7034. break;
  7035. case 3:// FresnelParameters
  7036. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7037. break;
  7038. case 4:// Vector2
  7039. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7040. break;
  7041. case 5:// Vector3
  7042. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7043. break;
  7044. case 6:// Mesh reference
  7045. serializationObject[targetPropertyName] = sourceProperty.id;
  7046. break;
  7047. case 7:// Color Curves
  7048. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7049. break;
  7050. case 8:// Color 4
  7051. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7052. break;
  7053. case 9:// Image Processing
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. }
  7057. }
  7058. }
  7059. return serializationObject;
  7060. };
  7061. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7062. if (rootUrl === void 0) { rootUrl = null; }
  7063. var destination = creationFunction();
  7064. if (!rootUrl) {
  7065. rootUrl = "";
  7066. }
  7067. // Tags
  7068. if (BABYLON.Tags) {
  7069. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7070. }
  7071. var classStore = getMergedStore(destination);
  7072. // Properties
  7073. for (var property in classStore) {
  7074. var propertyDescriptor = classStore[property];
  7075. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7076. var propertyType = propertyDescriptor.type;
  7077. if (sourceProperty !== undefined && sourceProperty !== null) {
  7078. var dest = destination;
  7079. switch (propertyType) {
  7080. case 0:// Value
  7081. dest[property] = sourceProperty;
  7082. break;
  7083. case 1:// Texture
  7084. if (scene) {
  7085. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7086. }
  7087. break;
  7088. case 2:// Color3
  7089. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7090. break;
  7091. case 3:// FresnelParameters
  7092. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7093. break;
  7094. case 4:// Vector2
  7095. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7096. break;
  7097. case 5:// Vector3
  7098. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7099. break;
  7100. case 6:// Mesh reference
  7101. if (scene) {
  7102. dest[property] = scene.getLastMeshByID(sourceProperty);
  7103. }
  7104. break;
  7105. case 7:// Color Curves
  7106. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7107. break;
  7108. case 8:// Color 4
  7109. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7110. break;
  7111. case 9:// Image Processing
  7112. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7113. break;
  7114. }
  7115. }
  7116. }
  7117. return destination;
  7118. };
  7119. SerializationHelper.Clone = function (creationFunction, source) {
  7120. return _copySource(creationFunction, source, false);
  7121. };
  7122. SerializationHelper.Instanciate = function (creationFunction, source) {
  7123. return _copySource(creationFunction, source, true);
  7124. };
  7125. return SerializationHelper;
  7126. }());
  7127. BABYLON.SerializationHelper = SerializationHelper;
  7128. })(BABYLON || (BABYLON = {}));
  7129. //# sourceMappingURL=babylon.decorators.js.map
  7130. var BABYLON;
  7131. (function (BABYLON) {
  7132. /**
  7133. * Wrapper class for promise with external resolve and reject.
  7134. */
  7135. var Deferred = /** @class */ (function () {
  7136. /**
  7137. * Constructor for this deferred object.
  7138. */
  7139. function Deferred() {
  7140. var _this = this;
  7141. this.promise = new Promise(function (resolve, reject) {
  7142. _this._resolve = resolve;
  7143. _this._reject = reject;
  7144. });
  7145. }
  7146. Object.defineProperty(Deferred.prototype, "resolve", {
  7147. /**
  7148. * The resolve method of the promise associated with this deferred object.
  7149. */
  7150. get: function () {
  7151. return this._resolve;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(Deferred.prototype, "reject", {
  7157. /**
  7158. * The reject method of the promise associated with this deferred object.
  7159. */
  7160. get: function () {
  7161. return this._reject;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. return Deferred;
  7167. }());
  7168. BABYLON.Deferred = Deferred;
  7169. })(BABYLON || (BABYLON = {}));
  7170. //# sourceMappingURL=babylon.deferred.js.map
  7171. var BABYLON;
  7172. (function (BABYLON) {
  7173. /**
  7174. * A class serves as a medium between the observable and its observers
  7175. */
  7176. var EventState = /** @class */ (function () {
  7177. /**
  7178. * Create a new EventState
  7179. * @param mask defines the mask associated with this state
  7180. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7181. * @param target defines the original target of the state
  7182. * @param currentTarget defines the current target of the state
  7183. */
  7184. function EventState(mask, skipNextObservers, target, currentTarget) {
  7185. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7186. this.initalize(mask, skipNextObservers, target, currentTarget);
  7187. }
  7188. /**
  7189. * Initialize the current event state
  7190. * @param mask defines the mask associated with this state
  7191. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7192. * @param target defines the original target of the state
  7193. * @param currentTarget defines the current target of the state
  7194. * @returns the current event state
  7195. */
  7196. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7197. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7198. this.mask = mask;
  7199. this.skipNextObservers = skipNextObservers;
  7200. this.target = target;
  7201. this.currentTarget = currentTarget;
  7202. return this;
  7203. };
  7204. return EventState;
  7205. }());
  7206. BABYLON.EventState = EventState;
  7207. /**
  7208. * Represent an Observer registered to a given Observable object.
  7209. */
  7210. var Observer = /** @class */ (function () {
  7211. /**
  7212. * Creates a new observer
  7213. * @param callback defines the callback to call when the observer is notified
  7214. * @param mask defines the mask of the observer (used to filter notifications)
  7215. * @param scope defines the current scope used to restore the JS context
  7216. */
  7217. function Observer(
  7218. /**
  7219. * Defines the callback to call when the observer is notified
  7220. */
  7221. callback,
  7222. /**
  7223. * Defines the mask of the observer (used to filter notifications)
  7224. */
  7225. mask,
  7226. /**
  7227. * Defines the current scope used to restore the JS context
  7228. */
  7229. scope) {
  7230. if (scope === void 0) { scope = null; }
  7231. this.callback = callback;
  7232. this.mask = mask;
  7233. this.scope = scope;
  7234. /** @ignore */
  7235. this._willBeUnregistered = false;
  7236. /**
  7237. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7238. */
  7239. this.unregisterOnNextCall = false;
  7240. }
  7241. return Observer;
  7242. }());
  7243. BABYLON.Observer = Observer;
  7244. /**
  7245. * Represent a list of observers registered to multiple Observables object.
  7246. */
  7247. var MultiObserver = /** @class */ (function () {
  7248. function MultiObserver() {
  7249. }
  7250. /**
  7251. * Release associated resources
  7252. */
  7253. MultiObserver.prototype.dispose = function () {
  7254. if (this._observers && this._observables) {
  7255. for (var index = 0; index < this._observers.length; index++) {
  7256. this._observables[index].remove(this._observers[index]);
  7257. }
  7258. }
  7259. this._observers = null;
  7260. this._observables = null;
  7261. };
  7262. /**
  7263. * Raise a callback when one of the observable will notify
  7264. * @param observables defines a list of observables to watch
  7265. * @param callback defines the callback to call on notification
  7266. * @param mask defines the mask used to filter notifications
  7267. * @param scope defines the current scope used to restore the JS context
  7268. * @returns the new MultiObserver
  7269. */
  7270. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7271. if (mask === void 0) { mask = -1; }
  7272. if (scope === void 0) { scope = null; }
  7273. var result = new MultiObserver();
  7274. result._observers = new Array();
  7275. result._observables = observables;
  7276. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7277. var observable = observables_1[_i];
  7278. var observer = observable.add(callback, mask, false, scope);
  7279. if (observer) {
  7280. result._observers.push(observer);
  7281. }
  7282. }
  7283. return result;
  7284. };
  7285. return MultiObserver;
  7286. }());
  7287. BABYLON.MultiObserver = MultiObserver;
  7288. /**
  7289. * The Observable class is a simple implementation of the Observable pattern.
  7290. * 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.
  7291. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7292. * 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).
  7293. * 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.
  7294. */
  7295. var Observable = /** @class */ (function () {
  7296. /**
  7297. * Creates a new observable
  7298. * @param onObserverAdded defines a callback to call when a new observer is added
  7299. */
  7300. function Observable(onObserverAdded) {
  7301. this._observers = new Array();
  7302. this._eventState = new EventState(0);
  7303. if (onObserverAdded) {
  7304. this._onObserverAdded = onObserverAdded;
  7305. }
  7306. }
  7307. /**
  7308. * Create a new Observer with the specified callback
  7309. * @param callback the callback that will be executed for that Observer
  7310. * @param mask the mask used to filter observers
  7311. * @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.
  7312. * @param scope optional scope for the callback to be called from
  7313. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7314. * @returns the new observer created for the callback
  7315. */
  7316. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7317. if (mask === void 0) { mask = -1; }
  7318. if (insertFirst === void 0) { insertFirst = false; }
  7319. if (scope === void 0) { scope = null; }
  7320. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7321. if (!callback) {
  7322. return null;
  7323. }
  7324. var observer = new Observer(callback, mask, scope);
  7325. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7326. if (insertFirst) {
  7327. this._observers.unshift(observer);
  7328. }
  7329. else {
  7330. this._observers.push(observer);
  7331. }
  7332. if (this._onObserverAdded) {
  7333. this._onObserverAdded(observer);
  7334. }
  7335. return observer;
  7336. };
  7337. /**
  7338. * Remove an Observer from the Observable object
  7339. * @param observer the instance of the Observer to remove
  7340. * @returns false if it doesn't belong to this Observable
  7341. */
  7342. Observable.prototype.remove = function (observer) {
  7343. if (!observer) {
  7344. return false;
  7345. }
  7346. var index = this._observers.indexOf(observer);
  7347. if (index !== -1) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. return false;
  7352. };
  7353. /**
  7354. * Remove a callback from the Observable object
  7355. * @param callback the callback to remove
  7356. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7357. * @returns false if it doesn't belong to this Observable
  7358. */
  7359. Observable.prototype.removeCallback = function (callback, scope) {
  7360. for (var index = 0; index < this._observers.length; index++) {
  7361. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7362. this._observers.splice(index, 1);
  7363. return true;
  7364. }
  7365. }
  7366. return false;
  7367. };
  7368. Observable.prototype._deferUnregister = function (observer) {
  7369. var _this = this;
  7370. observer.unregisterOnNextCall = false;
  7371. observer._willBeUnregistered = true;
  7372. BABYLON.Tools.SetImmediate(function () {
  7373. _this.remove(observer);
  7374. });
  7375. };
  7376. /**
  7377. * Notify all Observers by calling their respective callback with the given data
  7378. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7379. * @param eventData defines the data to send to all observers
  7380. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7381. * @param target defines the original target of the state
  7382. * @param currentTarget defines the current target of the state
  7383. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7384. */
  7385. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7386. if (mask === void 0) { mask = -1; }
  7387. if (!this._observers.length) {
  7388. return true;
  7389. }
  7390. var state = this._eventState;
  7391. state.mask = mask;
  7392. state.target = target;
  7393. state.currentTarget = currentTarget;
  7394. state.skipNextObservers = false;
  7395. state.lastReturnValue = eventData;
  7396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7397. var obs = _a[_i];
  7398. if (obs._willBeUnregistered) {
  7399. continue;
  7400. }
  7401. if (obs.mask & mask) {
  7402. if (obs.scope) {
  7403. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7404. }
  7405. else {
  7406. state.lastReturnValue = obs.callback(eventData, state);
  7407. }
  7408. if (obs.unregisterOnNextCall) {
  7409. this._deferUnregister(obs);
  7410. }
  7411. }
  7412. if (state.skipNextObservers) {
  7413. return false;
  7414. }
  7415. }
  7416. return true;
  7417. };
  7418. /**
  7419. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7420. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7421. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7422. * and it is crucial that all callbacks will be executed.
  7423. * The order of the callbacks is kept, callbacks are not executed parallel.
  7424. *
  7425. * @param eventData The data to be sent to each callback
  7426. * @param mask is used to filter observers defaults to -1
  7427. * @param target defines the callback target (see EventState)
  7428. * @param currentTarget defines he current object in the bubbling phase
  7429. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7430. */
  7431. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7432. var _this = this;
  7433. if (mask === void 0) { mask = -1; }
  7434. // create an empty promise
  7435. var p = Promise.resolve(eventData);
  7436. // no observers? return this promise.
  7437. if (!this._observers.length) {
  7438. return p;
  7439. }
  7440. var state = this._eventState;
  7441. state.mask = mask;
  7442. state.target = target;
  7443. state.currentTarget = currentTarget;
  7444. state.skipNextObservers = false;
  7445. // execute one callback after another (not using Promise.all, the order is important)
  7446. this._observers.forEach(function (obs) {
  7447. if (state.skipNextObservers) {
  7448. return;
  7449. }
  7450. if (obs._willBeUnregistered) {
  7451. return;
  7452. }
  7453. if (obs.mask & mask) {
  7454. if (obs.scope) {
  7455. p = p.then(function (lastReturnedValue) {
  7456. state.lastReturnValue = lastReturnedValue;
  7457. return obs.callback.apply(obs.scope, [eventData, state]);
  7458. });
  7459. }
  7460. else {
  7461. p = p.then(function (lastReturnedValue) {
  7462. state.lastReturnValue = lastReturnedValue;
  7463. return obs.callback(eventData, state);
  7464. });
  7465. }
  7466. if (obs.unregisterOnNextCall) {
  7467. _this._deferUnregister(obs);
  7468. }
  7469. }
  7470. });
  7471. // return the eventData
  7472. return p.then(function () { return eventData; });
  7473. };
  7474. /**
  7475. * Notify a specific observer
  7476. * @param observer defines the observer to notify
  7477. * @param eventData defines the data to be sent to each callback
  7478. * @param mask is used to filter observers defaults to -1
  7479. */
  7480. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7481. if (mask === void 0) { mask = -1; }
  7482. var state = this._eventState;
  7483. state.mask = mask;
  7484. state.skipNextObservers = false;
  7485. observer.callback(eventData, state);
  7486. };
  7487. /**
  7488. * Gets a boolean indicating if the observable has at least one observer
  7489. * @returns true is the Observable has at least one Observer registered
  7490. */
  7491. Observable.prototype.hasObservers = function () {
  7492. return this._observers.length > 0;
  7493. };
  7494. /**
  7495. * Clear the list of observers
  7496. */
  7497. Observable.prototype.clear = function () {
  7498. this._observers = new Array();
  7499. this._onObserverAdded = null;
  7500. };
  7501. /**
  7502. * Clone the current observable
  7503. * @returns a new observable
  7504. */
  7505. Observable.prototype.clone = function () {
  7506. var result = new Observable();
  7507. result._observers = this._observers.slice(0);
  7508. return result;
  7509. };
  7510. /**
  7511. * Does this observable handles observer registered with a given mask
  7512. * @param mask defines the mask to be tested
  7513. * @return whether or not one observer registered with the given mask is handeled
  7514. **/
  7515. Observable.prototype.hasSpecificMask = function (mask) {
  7516. if (mask === void 0) { mask = -1; }
  7517. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7518. var obs = _a[_i];
  7519. if (obs.mask & mask || obs.mask === mask) {
  7520. return true;
  7521. }
  7522. }
  7523. return false;
  7524. };
  7525. return Observable;
  7526. }());
  7527. BABYLON.Observable = Observable;
  7528. })(BABYLON || (BABYLON = {}));
  7529. //# sourceMappingURL=babylon.observable.js.map
  7530. var BABYLON;
  7531. (function (BABYLON) {
  7532. var SmartArray = /** @class */ (function () {
  7533. function SmartArray(capacity) {
  7534. this.length = 0;
  7535. this.data = new Array(capacity);
  7536. this._id = SmartArray._GlobalId++;
  7537. }
  7538. SmartArray.prototype.push = function (value) {
  7539. this.data[this.length++] = value;
  7540. if (this.length > this.data.length) {
  7541. this.data.length *= 2;
  7542. }
  7543. };
  7544. SmartArray.prototype.forEach = function (func) {
  7545. for (var index = 0; index < this.length; index++) {
  7546. func(this.data[index]);
  7547. }
  7548. };
  7549. SmartArray.prototype.sort = function (compareFn) {
  7550. this.data.sort(compareFn);
  7551. };
  7552. SmartArray.prototype.reset = function () {
  7553. this.length = 0;
  7554. };
  7555. SmartArray.prototype.dispose = function () {
  7556. this.reset();
  7557. if (this.data) {
  7558. this.data.length = 0;
  7559. this.data = [];
  7560. }
  7561. };
  7562. SmartArray.prototype.concat = function (array) {
  7563. if (array.length === 0) {
  7564. return;
  7565. }
  7566. if (this.length + array.length > this.data.length) {
  7567. this.data.length = (this.length + array.length) * 2;
  7568. }
  7569. for (var index = 0; index < array.length; index++) {
  7570. this.data[this.length++] = (array.data || array)[index];
  7571. }
  7572. };
  7573. SmartArray.prototype.indexOf = function (value) {
  7574. var position = this.data.indexOf(value);
  7575. if (position >= this.length) {
  7576. return -1;
  7577. }
  7578. return position;
  7579. };
  7580. SmartArray.prototype.contains = function (value) {
  7581. return this.data.indexOf(value) !== -1;
  7582. };
  7583. // Statics
  7584. SmartArray._GlobalId = 0;
  7585. return SmartArray;
  7586. }());
  7587. BABYLON.SmartArray = SmartArray;
  7588. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7589. __extends(SmartArrayNoDuplicate, _super);
  7590. function SmartArrayNoDuplicate() {
  7591. var _this = _super !== null && _super.apply(this, arguments) || this;
  7592. _this._duplicateId = 0;
  7593. return _this;
  7594. }
  7595. SmartArrayNoDuplicate.prototype.push = function (value) {
  7596. _super.prototype.push.call(this, value);
  7597. if (!value.__smartArrayFlags) {
  7598. value.__smartArrayFlags = {};
  7599. }
  7600. value.__smartArrayFlags[this._id] = this._duplicateId;
  7601. };
  7602. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7603. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7604. return false;
  7605. }
  7606. this.push(value);
  7607. return true;
  7608. };
  7609. SmartArrayNoDuplicate.prototype.reset = function () {
  7610. _super.prototype.reset.call(this);
  7611. this._duplicateId++;
  7612. };
  7613. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7614. if (array.length === 0) {
  7615. return;
  7616. }
  7617. if (this.length + array.length > this.data.length) {
  7618. this.data.length = (this.length + array.length) * 2;
  7619. }
  7620. for (var index = 0; index < array.length; index++) {
  7621. var item = (array.data || array)[index];
  7622. this.pushNoDuplicate(item);
  7623. }
  7624. };
  7625. return SmartArrayNoDuplicate;
  7626. }(SmartArray));
  7627. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7628. })(BABYLON || (BABYLON = {}));
  7629. //# sourceMappingURL=babylon.smartArray.js.map
  7630. var BABYLON;
  7631. (function (BABYLON) {
  7632. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7633. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7634. var LoadFileError = /** @class */ (function (_super) {
  7635. __extends(LoadFileError, _super);
  7636. function LoadFileError(message, request) {
  7637. var _this = _super.call(this, message) || this;
  7638. _this.request = request;
  7639. _this.name = "LoadFileError";
  7640. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7641. return _this;
  7642. }
  7643. // Polyfill for Object.setPrototypeOf if necessary.
  7644. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7645. return LoadFileError;
  7646. }(Error));
  7647. BABYLON.LoadFileError = LoadFileError;
  7648. var RetryStrategy = /** @class */ (function () {
  7649. function RetryStrategy() {
  7650. }
  7651. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7652. if (maxRetries === void 0) { maxRetries = 3; }
  7653. if (baseInterval === void 0) { baseInterval = 500; }
  7654. return function (url, request, retryIndex) {
  7655. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7656. return -1;
  7657. }
  7658. return Math.pow(2, retryIndex) * baseInterval;
  7659. };
  7660. };
  7661. return RetryStrategy;
  7662. }());
  7663. BABYLON.RetryStrategy = RetryStrategy;
  7664. // Screenshots
  7665. var screenshotCanvas;
  7666. var cloneValue = function (source, destinationObject) {
  7667. if (!source)
  7668. return null;
  7669. if (source instanceof BABYLON.Mesh) {
  7670. return null;
  7671. }
  7672. if (source instanceof BABYLON.SubMesh) {
  7673. return source.clone(destinationObject);
  7674. }
  7675. else if (source.clone) {
  7676. return source.clone();
  7677. }
  7678. return null;
  7679. };
  7680. var Tools = /** @class */ (function () {
  7681. function Tools() {
  7682. }
  7683. /**
  7684. * Interpolates between a and b via alpha
  7685. * @param a The lower value (returned when alpha = 0)
  7686. * @param b The upper value (returned when alpha = 1)
  7687. * @param alpha The interpolation-factor
  7688. * @return The mixed value
  7689. */
  7690. Tools.Mix = function (a, b, alpha) {
  7691. return a * (1 - alpha) + b * alpha;
  7692. };
  7693. Tools.Instantiate = function (className) {
  7694. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7695. return Tools.RegisteredExternalClasses[className];
  7696. }
  7697. var arr = className.split(".");
  7698. var fn = (window || this);
  7699. for (var i = 0, len = arr.length; i < len; i++) {
  7700. fn = fn[arr[i]];
  7701. }
  7702. if (typeof fn !== "function") {
  7703. return null;
  7704. }
  7705. return fn;
  7706. };
  7707. /**
  7708. * Provides a slice function that will work even on IE
  7709. * @param data defines the array to slice
  7710. * @returns the new sliced array
  7711. */
  7712. Tools.Slice = function (data) {
  7713. if (data.slice) {
  7714. return data.slice();
  7715. }
  7716. return Array.prototype.slice.call(data);
  7717. };
  7718. Tools.SetImmediate = function (action) {
  7719. if (window.setImmediate) {
  7720. window.setImmediate(action);
  7721. }
  7722. else {
  7723. setTimeout(action, 1);
  7724. }
  7725. };
  7726. Tools.IsExponentOfTwo = function (value) {
  7727. var count = 1;
  7728. do {
  7729. count *= 2;
  7730. } while (count < value);
  7731. return count === value;
  7732. };
  7733. /**
  7734. * Find the next highest power of two.
  7735. * @param x Number to start search from.
  7736. * @return Next highest power of two.
  7737. */
  7738. Tools.CeilingPOT = function (x) {
  7739. x--;
  7740. x |= x >> 1;
  7741. x |= x >> 2;
  7742. x |= x >> 4;
  7743. x |= x >> 8;
  7744. x |= x >> 16;
  7745. x++;
  7746. return x;
  7747. };
  7748. /**
  7749. * Find the next lowest power of two.
  7750. * @param x Number to start search from.
  7751. * @return Next lowest power of two.
  7752. */
  7753. Tools.FloorPOT = function (x) {
  7754. x = x | (x >> 1);
  7755. x = x | (x >> 2);
  7756. x = x | (x >> 4);
  7757. x = x | (x >> 8);
  7758. x = x | (x >> 16);
  7759. return x - (x >> 1);
  7760. };
  7761. /**
  7762. * Find the nearest power of two.
  7763. * @param x Number to start search from.
  7764. * @return Next nearest power of two.
  7765. */
  7766. Tools.NearestPOT = function (x) {
  7767. var c = Tools.CeilingPOT(x);
  7768. var f = Tools.FloorPOT(x);
  7769. return (c - x) > (x - f) ? f : c;
  7770. };
  7771. Tools.GetExponentOfTwo = function (value, max, mode) {
  7772. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7773. var pot;
  7774. switch (mode) {
  7775. case BABYLON.Engine.SCALEMODE_FLOOR:
  7776. pot = Tools.FloorPOT(value);
  7777. break;
  7778. case BABYLON.Engine.SCALEMODE_NEAREST:
  7779. pot = Tools.NearestPOT(value);
  7780. break;
  7781. case BABYLON.Engine.SCALEMODE_CEILING:
  7782. default:
  7783. pot = Tools.CeilingPOT(value);
  7784. break;
  7785. }
  7786. return Math.min(pot, max);
  7787. };
  7788. Tools.GetFilename = function (path) {
  7789. var index = path.lastIndexOf("/");
  7790. if (index < 0)
  7791. return path;
  7792. return path.substring(index + 1);
  7793. };
  7794. /**
  7795. * Extracts the "folder" part of a path (everything before the filename).
  7796. * @param uri The URI to extract the info from
  7797. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7798. * @returns The "folder" part of the path
  7799. */
  7800. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7801. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7802. var index = uri.lastIndexOf("/");
  7803. if (index < 0) {
  7804. if (returnUnchangedIfNoSlash) {
  7805. return uri;
  7806. }
  7807. return "";
  7808. }
  7809. return uri.substring(0, index + 1);
  7810. };
  7811. Tools.GetDOMTextContent = function (element) {
  7812. var result = "";
  7813. var child = element.firstChild;
  7814. while (child) {
  7815. if (child.nodeType === 3) {
  7816. result += child.textContent;
  7817. }
  7818. child = child.nextSibling;
  7819. }
  7820. return result;
  7821. };
  7822. Tools.ToDegrees = function (angle) {
  7823. return angle * 180 / Math.PI;
  7824. };
  7825. Tools.ToRadians = function (angle) {
  7826. return angle * Math.PI / 180;
  7827. };
  7828. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7829. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7830. var output = "";
  7831. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7832. var i = 0;
  7833. var bytes = new Uint8Array(buffer);
  7834. while (i < bytes.length) {
  7835. chr1 = bytes[i++];
  7836. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7837. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7838. enc1 = chr1 >> 2;
  7839. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7840. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7841. enc4 = chr3 & 63;
  7842. if (isNaN(chr2)) {
  7843. enc3 = enc4 = 64;
  7844. }
  7845. else if (isNaN(chr3)) {
  7846. enc4 = 64;
  7847. }
  7848. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7849. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7850. }
  7851. return "data:image/png;base64," + output;
  7852. };
  7853. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7854. if (bias === void 0) { bias = null; }
  7855. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7856. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7857. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7858. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7859. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7860. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7861. }
  7862. if (bias) {
  7863. minimum.x -= minimum.x * bias.x + bias.y;
  7864. minimum.y -= minimum.y * bias.x + bias.y;
  7865. minimum.z -= minimum.z * bias.x + bias.y;
  7866. maximum.x += maximum.x * bias.x + bias.y;
  7867. maximum.y += maximum.y * bias.x + bias.y;
  7868. maximum.z += maximum.z * bias.x + bias.y;
  7869. }
  7870. return {
  7871. minimum: minimum,
  7872. maximum: maximum
  7873. };
  7874. };
  7875. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7876. if (bias === void 0) { bias = null; }
  7877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7879. if (!stride) {
  7880. stride = 3;
  7881. }
  7882. for (var index = start; index < start + count; index++) {
  7883. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7886. }
  7887. if (bias) {
  7888. minimum.x -= minimum.x * bias.x + bias.y;
  7889. minimum.y -= minimum.y * bias.x + bias.y;
  7890. minimum.z -= minimum.z * bias.x + bias.y;
  7891. maximum.x += maximum.x * bias.x + bias.y;
  7892. maximum.y += maximum.y * bias.x + bias.y;
  7893. maximum.z += maximum.z * bias.x + bias.y;
  7894. }
  7895. return {
  7896. minimum: minimum,
  7897. maximum: maximum
  7898. };
  7899. };
  7900. Tools.Vector2ArrayFeeder = function (array) {
  7901. return function (index) {
  7902. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7903. var length = isFloatArray ? array.length / 2 : array.length;
  7904. if (index >= length) {
  7905. return null;
  7906. }
  7907. if (isFloatArray) {
  7908. var fa = array;
  7909. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7910. }
  7911. var a = array;
  7912. return a[index];
  7913. };
  7914. };
  7915. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7916. if (bias === void 0) { bias = null; }
  7917. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7918. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7919. var i = 0;
  7920. var cur = feeder(i++);
  7921. while (cur) {
  7922. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7923. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7924. cur = feeder(i++);
  7925. }
  7926. if (bias) {
  7927. minimum.x -= minimum.x * bias.x + bias.y;
  7928. minimum.y -= minimum.y * bias.x + bias.y;
  7929. maximum.x += maximum.x * bias.x + bias.y;
  7930. maximum.y += maximum.y * bias.x + bias.y;
  7931. }
  7932. return {
  7933. minimum: minimum,
  7934. maximum: maximum
  7935. };
  7936. };
  7937. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7938. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7939. return null;
  7940. return Array.isArray(obj) ? obj : [obj];
  7941. };
  7942. // Misc.
  7943. Tools.GetPointerPrefix = function () {
  7944. var eventPrefix = "pointer";
  7945. // Check if pointer events are supported
  7946. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7947. eventPrefix = "mouse";
  7948. }
  7949. return eventPrefix;
  7950. };
  7951. /**
  7952. * @param func - the function to be called
  7953. * @param requester - the object that will request the next frame. Falls back to window.
  7954. */
  7955. Tools.QueueNewFrame = function (func, requester) {
  7956. if (!Tools.IsWindowObjectExist()) {
  7957. return setTimeout(func, 16);
  7958. }
  7959. if (!requester) {
  7960. requester = window;
  7961. }
  7962. if (requester.requestAnimationFrame) {
  7963. return requester.requestAnimationFrame(func);
  7964. }
  7965. else if (requester.msRequestAnimationFrame) {
  7966. return requester.msRequestAnimationFrame(func);
  7967. }
  7968. else if (requester.webkitRequestAnimationFrame) {
  7969. return requester.webkitRequestAnimationFrame(func);
  7970. }
  7971. else if (requester.mozRequestAnimationFrame) {
  7972. return requester.mozRequestAnimationFrame(func);
  7973. }
  7974. else if (requester.oRequestAnimationFrame) {
  7975. return requester.oRequestAnimationFrame(func);
  7976. }
  7977. else {
  7978. return window.setTimeout(func, 16);
  7979. }
  7980. };
  7981. Tools.RequestFullscreen = function (element) {
  7982. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7983. if (!requestFunction)
  7984. return;
  7985. requestFunction.call(element);
  7986. };
  7987. Tools.ExitFullscreen = function () {
  7988. if (document.exitFullscreen) {
  7989. document.exitFullscreen();
  7990. }
  7991. else if (document.mozCancelFullScreen) {
  7992. document.mozCancelFullScreen();
  7993. }
  7994. else if (document.webkitCancelFullScreen) {
  7995. document.webkitCancelFullScreen();
  7996. }
  7997. else if (document.msCancelFullScreen) {
  7998. document.msCancelFullScreen();
  7999. }
  8000. };
  8001. Tools.SetCorsBehavior = function (url, element) {
  8002. if (url && url.indexOf("data:") === 0) {
  8003. return;
  8004. }
  8005. if (Tools.CorsBehavior) {
  8006. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8007. element.crossOrigin = Tools.CorsBehavior;
  8008. }
  8009. else {
  8010. var result = Tools.CorsBehavior(url);
  8011. if (result) {
  8012. element.crossOrigin = result;
  8013. }
  8014. }
  8015. }
  8016. };
  8017. // External files
  8018. Tools.CleanUrl = function (url) {
  8019. url = url.replace(/#/mg, "%23");
  8020. return url;
  8021. };
  8022. Tools.LoadImage = function (url, onLoad, onError, database) {
  8023. if (url instanceof ArrayBuffer) {
  8024. url = Tools.EncodeArrayBufferTobase64(url);
  8025. }
  8026. url = Tools.CleanUrl(url);
  8027. url = Tools.PreprocessUrl(url);
  8028. var img = new Image();
  8029. Tools.SetCorsBehavior(url, img);
  8030. var loadHandler = function () {
  8031. img.removeEventListener("load", loadHandler);
  8032. img.removeEventListener("error", errorHandler);
  8033. onLoad(img);
  8034. };
  8035. var errorHandler = function (err) {
  8036. img.removeEventListener("load", loadHandler);
  8037. img.removeEventListener("error", errorHandler);
  8038. Tools.Error("Error while trying to load image: " + url);
  8039. if (onError) {
  8040. onError("Error while trying to load image: " + url, err);
  8041. }
  8042. };
  8043. img.addEventListener("load", loadHandler);
  8044. img.addEventListener("error", errorHandler);
  8045. var noIndexedDB = function () {
  8046. img.src = url;
  8047. };
  8048. var loadFromIndexedDB = function () {
  8049. if (database) {
  8050. database.loadImageFromDB(url, img);
  8051. }
  8052. };
  8053. //ANY database to do!
  8054. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8055. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8056. }
  8057. else {
  8058. if (url.indexOf("file:") !== -1) {
  8059. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8060. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8061. try {
  8062. var blobURL;
  8063. try {
  8064. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8065. }
  8066. catch (ex) {
  8067. // Chrome doesn't support oneTimeOnly parameter
  8068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8069. }
  8070. img.src = blobURL;
  8071. }
  8072. catch (e) {
  8073. img.src = "";
  8074. }
  8075. return img;
  8076. }
  8077. }
  8078. noIndexedDB();
  8079. }
  8080. return img;
  8081. };
  8082. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8083. url = Tools.CleanUrl(url);
  8084. url = Tools.PreprocessUrl(url);
  8085. // If file and file input are set
  8086. if (url.indexOf("file:") !== -1) {
  8087. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8088. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8089. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8090. }
  8091. }
  8092. var loadUrl = Tools.BaseUrl + url;
  8093. var aborted = false;
  8094. var fileRequest = {
  8095. onCompleteObservable: new BABYLON.Observable(),
  8096. abort: function () { return aborted = true; },
  8097. };
  8098. var requestFile = function () {
  8099. var request = new XMLHttpRequest();
  8100. var retryHandle = null;
  8101. fileRequest.abort = function () {
  8102. aborted = true;
  8103. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8104. request.abort();
  8105. }
  8106. if (retryHandle !== null) {
  8107. clearTimeout(retryHandle);
  8108. retryHandle = null;
  8109. }
  8110. };
  8111. var retryLoop = function (retryIndex) {
  8112. request.open('GET', loadUrl, true);
  8113. if (useArrayBuffer) {
  8114. request.responseType = "arraybuffer";
  8115. }
  8116. if (onProgress) {
  8117. request.addEventListener("progress", onProgress);
  8118. }
  8119. var onLoadEnd = function () {
  8120. request.removeEventListener("loadend", onLoadEnd);
  8121. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8122. fileRequest.onCompleteObservable.clear();
  8123. };
  8124. request.addEventListener("loadend", onLoadEnd);
  8125. var onReadyStateChange = function () {
  8126. if (aborted) {
  8127. return;
  8128. }
  8129. // In case of undefined state in some browsers.
  8130. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8131. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8132. request.removeEventListener("readystatechange", onReadyStateChange);
  8133. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8134. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8135. return;
  8136. }
  8137. var retryStrategy = Tools.DefaultRetryStrategy;
  8138. if (retryStrategy) {
  8139. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8140. if (waitTime !== -1) {
  8141. // Prevent the request from completing for retry.
  8142. request.removeEventListener("loadend", onLoadEnd);
  8143. request = new XMLHttpRequest();
  8144. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8145. return;
  8146. }
  8147. }
  8148. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8149. if (onError) {
  8150. onError(request, e);
  8151. }
  8152. else {
  8153. throw e;
  8154. }
  8155. }
  8156. };
  8157. request.addEventListener("readystatechange", onReadyStateChange);
  8158. request.send();
  8159. };
  8160. retryLoop(0);
  8161. };
  8162. // Caching all files
  8163. if (database && database.enableSceneOffline) {
  8164. var noIndexedDB_1 = function () {
  8165. if (!aborted) {
  8166. requestFile();
  8167. }
  8168. };
  8169. var loadFromIndexedDB = function () {
  8170. // TODO: database needs to support aborting and should return a IFileRequest
  8171. if (aborted) {
  8172. return;
  8173. }
  8174. if (database) {
  8175. database.loadFileFromDB(url, function (data) {
  8176. if (!aborted) {
  8177. onSuccess(data);
  8178. }
  8179. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8180. }, onProgress ? function (event) {
  8181. if (!aborted) {
  8182. onProgress(event);
  8183. }
  8184. } : undefined, noIndexedDB_1, useArrayBuffer);
  8185. }
  8186. };
  8187. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8188. }
  8189. else {
  8190. requestFile();
  8191. }
  8192. return fileRequest;
  8193. };
  8194. /**
  8195. * Load a script (identified by an url). When the url returns, the
  8196. * content of this file is added into a new script element, attached to the DOM (body element)
  8197. */
  8198. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8199. var head = document.getElementsByTagName('head')[0];
  8200. var script = document.createElement('script');
  8201. script.type = 'text/javascript';
  8202. script.src = scriptUrl;
  8203. script.onload = function () {
  8204. if (onSuccess) {
  8205. onSuccess();
  8206. }
  8207. };
  8208. script.onerror = function (e) {
  8209. if (onError) {
  8210. onError("Unable to load script", e);
  8211. }
  8212. };
  8213. head.appendChild(script);
  8214. };
  8215. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8216. var reader = new FileReader();
  8217. var request = {
  8218. onCompleteObservable: new BABYLON.Observable(),
  8219. abort: function () { return reader.abort(); },
  8220. };
  8221. reader.onloadend = function (e) {
  8222. request.onCompleteObservable.notifyObservers(request);
  8223. };
  8224. reader.onload = function (e) {
  8225. //target doesn't have result from ts 1.3
  8226. callback(e.target['result']);
  8227. };
  8228. reader.onprogress = progressCallback;
  8229. reader.readAsDataURL(fileToLoad);
  8230. return request;
  8231. };
  8232. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8233. var reader = new FileReader();
  8234. var request = {
  8235. onCompleteObservable: new BABYLON.Observable(),
  8236. abort: function () { return reader.abort(); },
  8237. };
  8238. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8239. reader.onerror = function (e) {
  8240. Tools.Log("Error while reading file: " + fileToLoad.name);
  8241. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8242. };
  8243. reader.onload = function (e) {
  8244. //target doesn't have result from ts 1.3
  8245. callback(e.target['result']);
  8246. };
  8247. if (progressCallBack) {
  8248. reader.onprogress = progressCallBack;
  8249. }
  8250. if (!useArrayBuffer) {
  8251. // Asynchronous read
  8252. reader.readAsText(fileToLoad);
  8253. }
  8254. else {
  8255. reader.readAsArrayBuffer(fileToLoad);
  8256. }
  8257. return request;
  8258. };
  8259. //returns a downloadable url to a file content.
  8260. Tools.FileAsURL = function (content) {
  8261. var fileBlob = new Blob([content]);
  8262. var url = window.URL || window.webkitURL;
  8263. var link = url.createObjectURL(fileBlob);
  8264. return link;
  8265. };
  8266. // Misc.
  8267. Tools.Format = function (value, decimals) {
  8268. if (decimals === void 0) { decimals = 2; }
  8269. return value.toFixed(decimals);
  8270. };
  8271. Tools.CheckExtends = function (v, min, max) {
  8272. if (v.x < min.x)
  8273. min.x = v.x;
  8274. if (v.y < min.y)
  8275. min.y = v.y;
  8276. if (v.z < min.z)
  8277. min.z = v.z;
  8278. if (v.x > max.x)
  8279. max.x = v.x;
  8280. if (v.y > max.y)
  8281. max.y = v.y;
  8282. if (v.z > max.z)
  8283. max.z = v.z;
  8284. };
  8285. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8286. for (var prop in source) {
  8287. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8288. continue;
  8289. }
  8290. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8291. continue;
  8292. }
  8293. var sourceValue = source[prop];
  8294. var typeOfSourceValue = typeof sourceValue;
  8295. if (typeOfSourceValue === "function") {
  8296. continue;
  8297. }
  8298. if (typeOfSourceValue === "object") {
  8299. if (sourceValue instanceof Array) {
  8300. destination[prop] = [];
  8301. if (sourceValue.length > 0) {
  8302. if (typeof sourceValue[0] == "object") {
  8303. for (var index = 0; index < sourceValue.length; index++) {
  8304. var clonedValue = cloneValue(sourceValue[index], destination);
  8305. if (destination[prop].indexOf(clonedValue) === -1) {
  8306. destination[prop].push(clonedValue);
  8307. }
  8308. }
  8309. }
  8310. else {
  8311. destination[prop] = sourceValue.slice(0);
  8312. }
  8313. }
  8314. }
  8315. else {
  8316. destination[prop] = cloneValue(sourceValue, destination);
  8317. }
  8318. }
  8319. else {
  8320. destination[prop] = sourceValue;
  8321. }
  8322. }
  8323. };
  8324. Tools.IsEmpty = function (obj) {
  8325. for (var i in obj) {
  8326. if (obj.hasOwnProperty(i)) {
  8327. return false;
  8328. }
  8329. }
  8330. return true;
  8331. };
  8332. Tools.RegisterTopRootEvents = function (events) {
  8333. for (var index = 0; index < events.length; index++) {
  8334. var event = events[index];
  8335. window.addEventListener(event.name, event.handler, false);
  8336. try {
  8337. if (window.parent) {
  8338. window.parent.addEventListener(event.name, event.handler, false);
  8339. }
  8340. }
  8341. catch (e) {
  8342. // Silently fails...
  8343. }
  8344. }
  8345. };
  8346. Tools.UnregisterTopRootEvents = function (events) {
  8347. for (var index = 0; index < events.length; index++) {
  8348. var event = events[index];
  8349. window.removeEventListener(event.name, event.handler);
  8350. try {
  8351. if (window.parent) {
  8352. window.parent.removeEventListener(event.name, event.handler);
  8353. }
  8354. }
  8355. catch (e) {
  8356. // Silently fails...
  8357. }
  8358. }
  8359. };
  8360. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8361. if (mimeType === void 0) { mimeType = "image/png"; }
  8362. // Read the contents of the framebuffer
  8363. var numberOfChannelsByLine = width * 4;
  8364. var halfHeight = height / 2;
  8365. //Reading datas from WebGL
  8366. var data = engine.readPixels(0, 0, width, height);
  8367. //To flip image on Y axis.
  8368. for (var i = 0; i < halfHeight; i++) {
  8369. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8370. var currentCell = j + i * numberOfChannelsByLine;
  8371. var targetLine = height - i - 1;
  8372. var targetCell = j + targetLine * numberOfChannelsByLine;
  8373. var temp = data[currentCell];
  8374. data[currentCell] = data[targetCell];
  8375. data[targetCell] = temp;
  8376. }
  8377. }
  8378. // Create a 2D canvas to store the result
  8379. if (!screenshotCanvas) {
  8380. screenshotCanvas = document.createElement('canvas');
  8381. }
  8382. screenshotCanvas.width = width;
  8383. screenshotCanvas.height = height;
  8384. var context = screenshotCanvas.getContext('2d');
  8385. if (context) {
  8386. // Copy the pixels to a 2D canvas
  8387. var imageData = context.createImageData(width, height);
  8388. var castData = (imageData.data);
  8389. castData.set(data);
  8390. context.putImageData(imageData, 0, 0);
  8391. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8392. }
  8393. };
  8394. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8395. if (mimeType === void 0) { mimeType = "image/png"; }
  8396. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8397. if (successCallback) {
  8398. successCallback(base64Image);
  8399. }
  8400. else {
  8401. // We need HTMLCanvasElement.toBlob for HD screenshots
  8402. if (!screenshotCanvas.toBlob) {
  8403. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8404. screenshotCanvas.toBlob = function (callback, type, quality) {
  8405. var _this = this;
  8406. setTimeout(function () {
  8407. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8408. for (var i = 0; i < len; i++) {
  8409. arr[i] = binStr.charCodeAt(i);
  8410. }
  8411. callback(new Blob([arr], { type: type || 'image/png' }));
  8412. });
  8413. };
  8414. }
  8415. screenshotCanvas.toBlob(function (blob) {
  8416. var url = URL.createObjectURL(blob);
  8417. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8418. if (("download" in document.createElement("a"))) {
  8419. var a = window.document.createElement("a");
  8420. a.href = url;
  8421. if (fileName) {
  8422. a.setAttribute("download", fileName);
  8423. }
  8424. else {
  8425. var date = new Date();
  8426. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8427. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8428. }
  8429. window.document.body.appendChild(a);
  8430. a.addEventListener("click", function () {
  8431. if (a.parentElement) {
  8432. a.parentElement.removeChild(a);
  8433. }
  8434. });
  8435. a.click();
  8436. }
  8437. else {
  8438. var newWindow = window.open("");
  8439. if (!newWindow)
  8440. return;
  8441. var img = newWindow.document.createElement("img");
  8442. img.onload = function () {
  8443. // no longer need to read the blob so it's revoked
  8444. URL.revokeObjectURL(url);
  8445. };
  8446. img.src = url;
  8447. newWindow.document.body.appendChild(img);
  8448. }
  8449. });
  8450. }
  8451. };
  8452. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8453. if (mimeType === void 0) { mimeType = "image/png"; }
  8454. var width;
  8455. var height;
  8456. // If a precision value is specified
  8457. if (size.precision) {
  8458. width = Math.round(engine.getRenderWidth() * size.precision);
  8459. height = Math.round(width / engine.getAspectRatio(camera));
  8460. }
  8461. else if (size.width && size.height) {
  8462. width = size.width;
  8463. height = size.height;
  8464. }
  8465. else if (size.width && !size.height) {
  8466. width = size.width;
  8467. height = Math.round(width / engine.getAspectRatio(camera));
  8468. }
  8469. else if (size.height && !size.width) {
  8470. height = size.height;
  8471. width = Math.round(height * engine.getAspectRatio(camera));
  8472. }
  8473. else if (!isNaN(size)) {
  8474. height = size;
  8475. width = size;
  8476. }
  8477. else {
  8478. Tools.Error("Invalid 'size' parameter !");
  8479. return;
  8480. }
  8481. if (!screenshotCanvas) {
  8482. screenshotCanvas = document.createElement('canvas');
  8483. }
  8484. screenshotCanvas.width = width;
  8485. screenshotCanvas.height = height;
  8486. var renderContext = screenshotCanvas.getContext("2d");
  8487. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8488. var newWidth = width;
  8489. var newHeight = newWidth / ratio;
  8490. if (newHeight > height) {
  8491. newHeight = height;
  8492. newWidth = newHeight * ratio;
  8493. }
  8494. var offsetX = Math.max(0, width - newWidth) / 2;
  8495. var offsetY = Math.max(0, height - newHeight) / 2;
  8496. var renderingCanvas = engine.getRenderingCanvas();
  8497. if (renderContext && renderingCanvas) {
  8498. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8499. }
  8500. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8501. };
  8502. /**
  8503. * Generates an image screenshot from the specified camera.
  8504. *
  8505. * @param engine The engine to use for rendering
  8506. * @param camera The camera to use for rendering
  8507. * @param size This parameter can be set to a single number or to an object with the
  8508. * following (optional) properties: precision, width, height. If a single number is passed,
  8509. * it will be used for both width and height. If an object is passed, the screenshot size
  8510. * will be derived from the parameters. The precision property is a multiplier allowing
  8511. * rendering at a higher or lower resolution.
  8512. * @param successCallback The callback receives a single parameter which contains the
  8513. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8514. * src parameter of an <img> to display it.
  8515. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8516. * Check your browser for supported MIME types.
  8517. * @param samples Texture samples (default: 1)
  8518. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8519. * @param fileName A name for for the downloaded file.
  8520. * @constructor
  8521. */
  8522. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8523. if (mimeType === void 0) { mimeType = "image/png"; }
  8524. if (samples === void 0) { samples = 1; }
  8525. if (antialiasing === void 0) { antialiasing = false; }
  8526. var width;
  8527. var height;
  8528. //If a precision value is specified
  8529. if (size.precision) {
  8530. width = Math.round(engine.getRenderWidth() * size.precision);
  8531. height = Math.round(width / engine.getAspectRatio(camera));
  8532. size = { width: width, height: height };
  8533. }
  8534. else if (size.width && size.height) {
  8535. width = size.width;
  8536. height = size.height;
  8537. }
  8538. else if (size.width && !size.height) {
  8539. width = size.width;
  8540. height = Math.round(width / engine.getAspectRatio(camera));
  8541. size = { width: width, height: height };
  8542. }
  8543. else if (size.height && !size.width) {
  8544. height = size.height;
  8545. width = Math.round(height * engine.getAspectRatio(camera));
  8546. size = { width: width, height: height };
  8547. }
  8548. else if (!isNaN(size)) {
  8549. height = size;
  8550. width = size;
  8551. }
  8552. else {
  8553. Tools.Error("Invalid 'size' parameter !");
  8554. return;
  8555. }
  8556. var scene = camera.getScene();
  8557. var previousCamera = null;
  8558. if (scene.activeCamera !== camera) {
  8559. previousCamera = scene.activeCamera;
  8560. scene.activeCamera = camera;
  8561. }
  8562. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8563. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8564. texture.renderList = null;
  8565. texture.samples = samples;
  8566. if (antialiasing) {
  8567. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8568. }
  8569. texture.onAfterRenderObservable.add(function () {
  8570. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8571. });
  8572. scene.incrementRenderId();
  8573. scene.resetCachedMaterial();
  8574. texture.render(true);
  8575. texture.dispose();
  8576. if (previousCamera) {
  8577. scene.activeCamera = previousCamera;
  8578. }
  8579. camera.getProjectionMatrix(true); // Force cache refresh;
  8580. };
  8581. // XHR response validator for local file scenario
  8582. Tools.ValidateXHRData = function (xhr, dataType) {
  8583. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8584. if (dataType === void 0) { dataType = 7; }
  8585. try {
  8586. if (dataType & 1) {
  8587. if (xhr.responseText && xhr.responseText.length > 0) {
  8588. return true;
  8589. }
  8590. else if (dataType === 1) {
  8591. return false;
  8592. }
  8593. }
  8594. if (dataType & 2) {
  8595. // Check header width and height since there is no "TGA" magic number
  8596. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8597. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8598. return true;
  8599. }
  8600. else if (dataType === 2) {
  8601. return false;
  8602. }
  8603. }
  8604. if (dataType & 4) {
  8605. // Check for the "DDS" magic number
  8606. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8607. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8608. return true;
  8609. }
  8610. else {
  8611. return false;
  8612. }
  8613. }
  8614. }
  8615. catch (e) {
  8616. // Global protection
  8617. }
  8618. return false;
  8619. };
  8620. /**
  8621. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8622. * Be aware Math.random() could cause collisions, but:
  8623. * "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"
  8624. */
  8625. Tools.RandomId = function () {
  8626. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8627. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8628. return v.toString(16);
  8629. });
  8630. };
  8631. /**
  8632. * Test if the given uri is a base64 string.
  8633. * @param uri The uri to test
  8634. * @return True if the uri is a base64 string or false otherwise.
  8635. */
  8636. Tools.IsBase64 = function (uri) {
  8637. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8638. };
  8639. /**
  8640. * Decode the given base64 uri.
  8641. * @param uri The uri to decode
  8642. * @return The decoded base64 data.
  8643. */
  8644. Tools.DecodeBase64 = function (uri) {
  8645. var decodedString = atob(uri.split(",")[1]);
  8646. var bufferLength = decodedString.length;
  8647. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8648. for (var i = 0; i < bufferLength; i++) {
  8649. bufferView[i] = decodedString.charCodeAt(i);
  8650. }
  8651. return bufferView.buffer;
  8652. };
  8653. Object.defineProperty(Tools, "NoneLogLevel", {
  8654. get: function () {
  8655. return Tools._NoneLogLevel;
  8656. },
  8657. enumerable: true,
  8658. configurable: true
  8659. });
  8660. Object.defineProperty(Tools, "MessageLogLevel", {
  8661. get: function () {
  8662. return Tools._MessageLogLevel;
  8663. },
  8664. enumerable: true,
  8665. configurable: true
  8666. });
  8667. Object.defineProperty(Tools, "WarningLogLevel", {
  8668. get: function () {
  8669. return Tools._WarningLogLevel;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Object.defineProperty(Tools, "ErrorLogLevel", {
  8675. get: function () {
  8676. return Tools._ErrorLogLevel;
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. Object.defineProperty(Tools, "AllLogLevel", {
  8682. get: function () {
  8683. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Tools._AddLogEntry = function (entry) {
  8689. Tools._LogCache = entry + Tools._LogCache;
  8690. if (Tools.OnNewCacheEntry) {
  8691. Tools.OnNewCacheEntry(entry);
  8692. }
  8693. };
  8694. Tools._FormatMessage = function (message) {
  8695. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8696. var date = new Date();
  8697. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8698. };
  8699. Tools._LogDisabled = function (message) {
  8700. // nothing to do
  8701. };
  8702. Tools._LogEnabled = function (message) {
  8703. var formattedMessage = Tools._FormatMessage(message);
  8704. console.log("BJS - " + formattedMessage);
  8705. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8706. Tools._AddLogEntry(entry);
  8707. };
  8708. Tools._WarnDisabled = function (message) {
  8709. // nothing to do
  8710. };
  8711. Tools._WarnEnabled = function (message) {
  8712. var formattedMessage = Tools._FormatMessage(message);
  8713. console.warn("BJS - " + formattedMessage);
  8714. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8715. Tools._AddLogEntry(entry);
  8716. };
  8717. Tools._ErrorDisabled = function (message) {
  8718. // nothing to do
  8719. };
  8720. Tools._ErrorEnabled = function (message) {
  8721. Tools.errorsCount++;
  8722. var formattedMessage = Tools._FormatMessage(message);
  8723. console.error("BJS - " + formattedMessage);
  8724. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8725. Tools._AddLogEntry(entry);
  8726. };
  8727. Object.defineProperty(Tools, "LogCache", {
  8728. get: function () {
  8729. return Tools._LogCache;
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Tools.ClearLogCache = function () {
  8735. Tools._LogCache = "";
  8736. Tools.errorsCount = 0;
  8737. };
  8738. Object.defineProperty(Tools, "LogLevels", {
  8739. set: function (level) {
  8740. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8741. Tools.Log = Tools._LogEnabled;
  8742. }
  8743. else {
  8744. Tools.Log = Tools._LogDisabled;
  8745. }
  8746. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8747. Tools.Warn = Tools._WarnEnabled;
  8748. }
  8749. else {
  8750. Tools.Warn = Tools._WarnDisabled;
  8751. }
  8752. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8753. Tools.Error = Tools._ErrorEnabled;
  8754. }
  8755. else {
  8756. Tools.Error = Tools._ErrorDisabled;
  8757. }
  8758. },
  8759. enumerable: true,
  8760. configurable: true
  8761. });
  8762. Tools.IsWindowObjectExist = function () {
  8763. return (typeof window) !== "undefined";
  8764. };
  8765. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8766. get: function () {
  8767. return Tools._PerformanceNoneLogLevel;
  8768. },
  8769. enumerable: true,
  8770. configurable: true
  8771. });
  8772. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8773. get: function () {
  8774. return Tools._PerformanceUserMarkLogLevel;
  8775. },
  8776. enumerable: true,
  8777. configurable: true
  8778. });
  8779. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8780. get: function () {
  8781. return Tools._PerformanceConsoleLogLevel;
  8782. },
  8783. enumerable: true,
  8784. configurable: true
  8785. });
  8786. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8787. set: function (level) {
  8788. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8789. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8790. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8791. return;
  8792. }
  8793. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8794. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8795. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8796. return;
  8797. }
  8798. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8799. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8805. };
  8806. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8807. };
  8808. Tools._StartUserMark = function (counterName, condition) {
  8809. if (condition === void 0) { condition = true; }
  8810. if (!Tools._performance) {
  8811. if (!Tools.IsWindowObjectExist()) {
  8812. return;
  8813. }
  8814. Tools._performance = window.performance;
  8815. }
  8816. if (!condition || !Tools._performance.mark) {
  8817. return;
  8818. }
  8819. Tools._performance.mark(counterName + "-Begin");
  8820. };
  8821. Tools._EndUserMark = function (counterName, condition) {
  8822. if (condition === void 0) { condition = true; }
  8823. if (!condition || !Tools._performance.mark) {
  8824. return;
  8825. }
  8826. Tools._performance.mark(counterName + "-End");
  8827. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8828. };
  8829. Tools._StartPerformanceConsole = function (counterName, condition) {
  8830. if (condition === void 0) { condition = true; }
  8831. if (!condition) {
  8832. return;
  8833. }
  8834. Tools._StartUserMark(counterName, condition);
  8835. if (console.time) {
  8836. console.time(counterName);
  8837. }
  8838. };
  8839. Tools._EndPerformanceConsole = function (counterName, condition) {
  8840. if (condition === void 0) { condition = true; }
  8841. if (!condition) {
  8842. return;
  8843. }
  8844. Tools._EndUserMark(counterName, condition);
  8845. if (console.time) {
  8846. console.timeEnd(counterName);
  8847. }
  8848. };
  8849. Object.defineProperty(Tools, "Now", {
  8850. get: function () {
  8851. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8852. return window.performance.now();
  8853. }
  8854. return new Date().getTime();
  8855. },
  8856. enumerable: true,
  8857. configurable: true
  8858. });
  8859. /**
  8860. * This method will return the name of the class used to create the instance of the given object.
  8861. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8862. * @param object the object to get the class name from
  8863. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8864. */
  8865. Tools.GetClassName = function (object, isType) {
  8866. if (isType === void 0) { isType = false; }
  8867. var name = null;
  8868. if (!isType && object.getClassName) {
  8869. name = object.getClassName();
  8870. }
  8871. else {
  8872. if (object instanceof Object) {
  8873. var classObj = isType ? object : Object.getPrototypeOf(object);
  8874. name = classObj.constructor["__bjsclassName__"];
  8875. }
  8876. if (!name) {
  8877. name = typeof object;
  8878. }
  8879. }
  8880. return name;
  8881. };
  8882. Tools.First = function (array, predicate) {
  8883. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8884. var el = array_1[_i];
  8885. if (predicate(el)) {
  8886. return el;
  8887. }
  8888. }
  8889. return null;
  8890. };
  8891. /**
  8892. * This method will return the name of the full name of the class, including its owning module (if any).
  8893. * 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).
  8894. * @param object the object to get the class name from
  8895. * @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.
  8896. */
  8897. Tools.getFullClassName = function (object, isType) {
  8898. if (isType === void 0) { isType = false; }
  8899. var className = null;
  8900. var moduleName = null;
  8901. if (!isType && object.getClassName) {
  8902. className = object.getClassName();
  8903. }
  8904. else {
  8905. if (object instanceof Object) {
  8906. var classObj = isType ? object : Object.getPrototypeOf(object);
  8907. className = classObj.constructor["__bjsclassName__"];
  8908. moduleName = classObj.constructor["__bjsmoduleName__"];
  8909. }
  8910. if (!className) {
  8911. className = typeof object;
  8912. }
  8913. }
  8914. if (!className) {
  8915. return null;
  8916. }
  8917. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8918. };
  8919. /**
  8920. * 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.
  8921. * @param array
  8922. */
  8923. Tools.arrayOrStringFeeder = function (array) {
  8924. return function (index) {
  8925. if (index >= array.length) {
  8926. return null;
  8927. }
  8928. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8929. if (val && val.getHashCode) {
  8930. val = val.getHashCode();
  8931. }
  8932. if (typeof val === "string") {
  8933. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8934. }
  8935. return val;
  8936. };
  8937. };
  8938. /**
  8939. * Compute the hashCode of a stream of number
  8940. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8941. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8942. * @return the hash code computed
  8943. */
  8944. Tools.hashCodeFromStream = function (feeder) {
  8945. // Based from here: http://stackoverflow.com/a/7616484/802124
  8946. var hash = 0;
  8947. var index = 0;
  8948. var chr = feeder(index++);
  8949. while (chr != null) {
  8950. hash = ((hash << 5) - hash) + chr;
  8951. hash |= 0; // Convert to 32bit integer
  8952. chr = feeder(index++);
  8953. }
  8954. return hash;
  8955. };
  8956. /**
  8957. * Returns a promise that resolves after the given amount of time.
  8958. * @param delay Number of milliseconds to delay
  8959. * @returns Promise that resolves after the given amount of time
  8960. */
  8961. Tools.DelayAsync = function (delay) {
  8962. return new Promise(function (resolve) {
  8963. setTimeout(function () {
  8964. resolve();
  8965. }, delay);
  8966. });
  8967. };
  8968. Tools.BaseUrl = "";
  8969. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8970. /**
  8971. * Default behaviour for cors in the application.
  8972. * It can be a string if the expected behavior is identical in the entire app.
  8973. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8974. */
  8975. Tools.CorsBehavior = "anonymous";
  8976. Tools.UseFallbackTexture = true;
  8977. /**
  8978. * Use this object to register external classes like custom textures or material
  8979. * to allow the laoders to instantiate them
  8980. */
  8981. Tools.RegisteredExternalClasses = {};
  8982. // Used in case of a texture loading problem
  8983. 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";
  8984. Tools.PreprocessUrl = function (url) {
  8985. return url;
  8986. };
  8987. // Logs
  8988. Tools._NoneLogLevel = 0;
  8989. Tools._MessageLogLevel = 1;
  8990. Tools._WarningLogLevel = 2;
  8991. Tools._ErrorLogLevel = 4;
  8992. Tools._LogCache = "";
  8993. Tools.errorsCount = 0;
  8994. Tools.Log = Tools._LogEnabled;
  8995. Tools.Warn = Tools._WarnEnabled;
  8996. Tools.Error = Tools._ErrorEnabled;
  8997. // Performances
  8998. Tools._PerformanceNoneLogLevel = 0;
  8999. Tools._PerformanceUserMarkLogLevel = 1;
  9000. Tools._PerformanceConsoleLogLevel = 2;
  9001. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9002. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9003. return Tools;
  9004. }());
  9005. BABYLON.Tools = Tools;
  9006. /**
  9007. * This class is used to track a performance counter which is number based.
  9008. * The user has access to many properties which give statistics of different nature
  9009. *
  9010. * The implementer can track two kinds of Performance Counter: time and count
  9011. * 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.
  9012. * 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.
  9013. */
  9014. var PerfCounter = /** @class */ (function () {
  9015. function PerfCounter() {
  9016. this._startMonitoringTime = 0;
  9017. this._min = 0;
  9018. this._max = 0;
  9019. this._average = 0;
  9020. this._lastSecAverage = 0;
  9021. this._current = 0;
  9022. this._totalValueCount = 0;
  9023. this._totalAccumulated = 0;
  9024. this._lastSecAccumulated = 0;
  9025. this._lastSecTime = 0;
  9026. this._lastSecValueCount = 0;
  9027. }
  9028. Object.defineProperty(PerfCounter.prototype, "min", {
  9029. /**
  9030. * Returns the smallest value ever
  9031. */
  9032. get: function () {
  9033. return this._min;
  9034. },
  9035. enumerable: true,
  9036. configurable: true
  9037. });
  9038. Object.defineProperty(PerfCounter.prototype, "max", {
  9039. /**
  9040. * Returns the biggest value ever
  9041. */
  9042. get: function () {
  9043. return this._max;
  9044. },
  9045. enumerable: true,
  9046. configurable: true
  9047. });
  9048. Object.defineProperty(PerfCounter.prototype, "average", {
  9049. /**
  9050. * Returns the average value since the performance counter is running
  9051. */
  9052. get: function () {
  9053. return this._average;
  9054. },
  9055. enumerable: true,
  9056. configurable: true
  9057. });
  9058. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9059. /**
  9060. * Returns the average value of the last second the counter was monitored
  9061. */
  9062. get: function () {
  9063. return this._lastSecAverage;
  9064. },
  9065. enumerable: true,
  9066. configurable: true
  9067. });
  9068. Object.defineProperty(PerfCounter.prototype, "current", {
  9069. /**
  9070. * Returns the current value
  9071. */
  9072. get: function () {
  9073. return this._current;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. Object.defineProperty(PerfCounter.prototype, "total", {
  9079. get: function () {
  9080. return this._totalAccumulated;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(PerfCounter.prototype, "count", {
  9086. get: function () {
  9087. return this._totalValueCount;
  9088. },
  9089. enumerable: true,
  9090. configurable: true
  9091. });
  9092. /**
  9093. * Call this method to start monitoring a new frame.
  9094. * 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.
  9095. */
  9096. PerfCounter.prototype.fetchNewFrame = function () {
  9097. this._totalValueCount++;
  9098. this._current = 0;
  9099. this._lastSecValueCount++;
  9100. };
  9101. /**
  9102. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9103. * @param newCount the count value to add to the monitored count
  9104. * @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.
  9105. */
  9106. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9107. if (!PerfCounter.Enabled) {
  9108. return;
  9109. }
  9110. this._current += newCount;
  9111. if (fetchResult) {
  9112. this._fetchResult();
  9113. }
  9114. };
  9115. /**
  9116. * Start monitoring this performance counter
  9117. */
  9118. PerfCounter.prototype.beginMonitoring = function () {
  9119. if (!PerfCounter.Enabled) {
  9120. return;
  9121. }
  9122. this._startMonitoringTime = Tools.Now;
  9123. };
  9124. /**
  9125. * Compute the time lapsed since the previous beginMonitoring() call.
  9126. * @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
  9127. */
  9128. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9129. if (newFrame === void 0) { newFrame = true; }
  9130. if (!PerfCounter.Enabled) {
  9131. return;
  9132. }
  9133. if (newFrame) {
  9134. this.fetchNewFrame();
  9135. }
  9136. var currentTime = Tools.Now;
  9137. this._current = currentTime - this._startMonitoringTime;
  9138. if (newFrame) {
  9139. this._fetchResult();
  9140. }
  9141. };
  9142. PerfCounter.prototype._fetchResult = function () {
  9143. this._totalAccumulated += this._current;
  9144. this._lastSecAccumulated += this._current;
  9145. // Min/Max update
  9146. this._min = Math.min(this._min, this._current);
  9147. this._max = Math.max(this._max, this._current);
  9148. this._average = this._totalAccumulated / this._totalValueCount;
  9149. // Reset last sec?
  9150. var now = Tools.Now;
  9151. if ((now - this._lastSecTime) > 1000) {
  9152. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9153. this._lastSecTime = now;
  9154. this._lastSecAccumulated = 0;
  9155. this._lastSecValueCount = 0;
  9156. }
  9157. };
  9158. PerfCounter.Enabled = true;
  9159. return PerfCounter;
  9160. }());
  9161. BABYLON.PerfCounter = PerfCounter;
  9162. /**
  9163. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9164. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9165. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9166. * @param name The name of the class, case should be preserved
  9167. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9168. */
  9169. function className(name, module) {
  9170. return function (target) {
  9171. target["__bjsclassName__"] = name;
  9172. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9173. };
  9174. }
  9175. BABYLON.className = className;
  9176. /**
  9177. * An implementation of a loop for asynchronous functions.
  9178. */
  9179. var AsyncLoop = /** @class */ (function () {
  9180. /**
  9181. * Constroctor.
  9182. * @param iterations the number of iterations.
  9183. * @param _fn the function to run each iteration
  9184. * @param _successCallback the callback that will be called upon succesful execution
  9185. * @param offset starting offset.
  9186. */
  9187. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9188. if (offset === void 0) { offset = 0; }
  9189. this.iterations = iterations;
  9190. this._fn = _fn;
  9191. this._successCallback = _successCallback;
  9192. this.index = offset - 1;
  9193. this._done = false;
  9194. }
  9195. /**
  9196. * Execute the next iteration. Must be called after the last iteration was finished.
  9197. */
  9198. AsyncLoop.prototype.executeNext = function () {
  9199. if (!this._done) {
  9200. if (this.index + 1 < this.iterations) {
  9201. ++this.index;
  9202. this._fn(this);
  9203. }
  9204. else {
  9205. this.breakLoop();
  9206. }
  9207. }
  9208. };
  9209. /**
  9210. * Break the loop and run the success callback.
  9211. */
  9212. AsyncLoop.prototype.breakLoop = function () {
  9213. this._done = true;
  9214. this._successCallback();
  9215. };
  9216. /**
  9217. * Helper function
  9218. */
  9219. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9220. if (offset === void 0) { offset = 0; }
  9221. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9222. loop.executeNext();
  9223. return loop;
  9224. };
  9225. /**
  9226. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9227. * @param iterations total number of iterations
  9228. * @param syncedIterations number of synchronous iterations in each async iteration.
  9229. * @param fn the function to call each iteration.
  9230. * @param callback a success call back that will be called when iterating stops.
  9231. * @param breakFunction a break condition (optional)
  9232. * @param timeout timeout settings for the setTimeout function. default - 0.
  9233. * @constructor
  9234. */
  9235. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9236. if (timeout === void 0) { timeout = 0; }
  9237. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9238. if (breakFunction && breakFunction())
  9239. loop.breakLoop();
  9240. else {
  9241. setTimeout(function () {
  9242. for (var i = 0; i < syncedIterations; ++i) {
  9243. var iteration = (loop.index * syncedIterations) + i;
  9244. if (iteration >= iterations)
  9245. break;
  9246. fn(iteration);
  9247. if (breakFunction && breakFunction()) {
  9248. loop.breakLoop();
  9249. break;
  9250. }
  9251. }
  9252. loop.executeNext();
  9253. }, timeout);
  9254. }
  9255. }, callback);
  9256. };
  9257. return AsyncLoop;
  9258. }());
  9259. BABYLON.AsyncLoop = AsyncLoop;
  9260. })(BABYLON || (BABYLON = {}));
  9261. //# sourceMappingURL=babylon.tools.js.map
  9262. var BABYLON;
  9263. (function (BABYLON) {
  9264. var PromiseStates;
  9265. (function (PromiseStates) {
  9266. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9267. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9268. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9269. })(PromiseStates || (PromiseStates = {}));
  9270. var FulFillmentAgregator = /** @class */ (function () {
  9271. function FulFillmentAgregator() {
  9272. this.count = 0;
  9273. this.target = 0;
  9274. this.results = [];
  9275. }
  9276. return FulFillmentAgregator;
  9277. }());
  9278. var InternalPromise = /** @class */ (function () {
  9279. function InternalPromise(resolver) {
  9280. var _this = this;
  9281. this._state = PromiseStates.Pending;
  9282. this._children = new Array();
  9283. this._rejectWasConsumed = false;
  9284. if (!resolver) {
  9285. return;
  9286. }
  9287. try {
  9288. resolver(function (value) {
  9289. _this._resolve(value);
  9290. }, function (reason) {
  9291. _this._reject(reason);
  9292. });
  9293. }
  9294. catch (e) {
  9295. this._reject(e);
  9296. }
  9297. }
  9298. InternalPromise.prototype.catch = function (onRejected) {
  9299. return this.then(undefined, onRejected);
  9300. };
  9301. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9302. var _this = this;
  9303. var newPromise = new InternalPromise();
  9304. newPromise._onFulfilled = onFulfilled;
  9305. newPromise._onRejected = onRejected;
  9306. // Composition
  9307. this._children.push(newPromise);
  9308. if (this._state !== PromiseStates.Pending) {
  9309. BABYLON.Tools.SetImmediate(function () {
  9310. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9311. var returnedValue = newPromise._resolve(_this._result);
  9312. if (returnedValue !== undefined && returnedValue !== null) {
  9313. if (returnedValue._state !== undefined) {
  9314. var returnedPromise = returnedValue;
  9315. newPromise._children.push(returnedPromise);
  9316. newPromise = returnedPromise;
  9317. }
  9318. else {
  9319. newPromise._result = returnedValue;
  9320. }
  9321. }
  9322. }
  9323. else {
  9324. newPromise._reject(_this._reason);
  9325. }
  9326. });
  9327. }
  9328. return newPromise;
  9329. };
  9330. InternalPromise.prototype._moveChildren = function (children) {
  9331. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9332. if (this._state === PromiseStates.Fulfilled) {
  9333. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9334. var child = _b[_i];
  9335. child._resolve(this._result);
  9336. }
  9337. }
  9338. else if (this._state === PromiseStates.Rejected) {
  9339. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9340. var child = _d[_c];
  9341. child._reject(this._reason);
  9342. }
  9343. }
  9344. var _a;
  9345. };
  9346. InternalPromise.prototype._resolve = function (value) {
  9347. try {
  9348. this._state = PromiseStates.Fulfilled;
  9349. this._result = value;
  9350. var returnedValue = null;
  9351. if (this._onFulfilled) {
  9352. returnedValue = this._onFulfilled(value);
  9353. }
  9354. if (returnedValue !== undefined && returnedValue !== null) {
  9355. if (returnedValue._state !== undefined) {
  9356. // Transmit children
  9357. var returnedPromise = returnedValue;
  9358. returnedPromise._moveChildren(this._children);
  9359. }
  9360. else {
  9361. value = returnedValue;
  9362. }
  9363. }
  9364. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9365. var child = _a[_i];
  9366. child._resolve(value);
  9367. }
  9368. this._children.length = 0;
  9369. delete this._onFulfilled;
  9370. delete this._onRejected;
  9371. return returnedValue;
  9372. }
  9373. catch (e) {
  9374. this._reject(e, true);
  9375. }
  9376. return null;
  9377. };
  9378. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9379. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9380. this._state = PromiseStates.Rejected;
  9381. this._reason = reason;
  9382. if (this._onRejected && !onLocalThrow) {
  9383. try {
  9384. this._onRejected(reason);
  9385. this._rejectWasConsumed = true;
  9386. }
  9387. catch (e) {
  9388. reason = e;
  9389. }
  9390. }
  9391. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9392. var child = _a[_i];
  9393. if (this._rejectWasConsumed) {
  9394. child._resolve(null);
  9395. }
  9396. else {
  9397. child._reject(reason);
  9398. }
  9399. }
  9400. this._children.length = 0;
  9401. delete this._onFulfilled;
  9402. delete this._onRejected;
  9403. };
  9404. InternalPromise.resolve = function (value) {
  9405. var newPromise = new InternalPromise();
  9406. newPromise._resolve(value);
  9407. return newPromise;
  9408. };
  9409. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9410. promise.then(function (value) {
  9411. agregator.results[index] = value;
  9412. agregator.count++;
  9413. if (agregator.count === agregator.target) {
  9414. agregator.rootPromise._resolve(agregator.results);
  9415. }
  9416. return null;
  9417. }, function (reason) {
  9418. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9419. agregator.rootPromise._reject(reason);
  9420. }
  9421. });
  9422. };
  9423. InternalPromise.all = function (promises) {
  9424. var newPromise = new InternalPromise();
  9425. var agregator = new FulFillmentAgregator();
  9426. agregator.target = promises.length;
  9427. agregator.rootPromise = newPromise;
  9428. if (promises.length) {
  9429. for (var index = 0; index < promises.length; index++) {
  9430. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9431. }
  9432. }
  9433. else {
  9434. newPromise._resolve([]);
  9435. }
  9436. return newPromise;
  9437. };
  9438. return InternalPromise;
  9439. }());
  9440. /**
  9441. * Helper class that provides a small promise polyfill
  9442. */
  9443. var PromisePolyfill = /** @class */ (function () {
  9444. function PromisePolyfill() {
  9445. }
  9446. /**
  9447. * Static function used to check if the polyfill is required
  9448. * If this is the case then the function will inject the polyfill to window.Promise
  9449. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9450. */
  9451. PromisePolyfill.Apply = function (force) {
  9452. if (force === void 0) { force = false; }
  9453. if (force || typeof Promise === 'undefined') {
  9454. var root = window;
  9455. root.Promise = InternalPromise;
  9456. }
  9457. };
  9458. return PromisePolyfill;
  9459. }());
  9460. BABYLON.PromisePolyfill = PromisePolyfill;
  9461. })(BABYLON || (BABYLON = {}));
  9462. //# sourceMappingURL=babylon.promise.js.map
  9463. var BABYLON;
  9464. (function (BABYLON) {
  9465. var _AlphaState = /** @class */ (function () {
  9466. /**
  9467. * Initializes the state.
  9468. */
  9469. function _AlphaState() {
  9470. this._isAlphaBlendDirty = false;
  9471. this._isBlendFunctionParametersDirty = false;
  9472. this._isBlendEquationParametersDirty = false;
  9473. this._isBlendConstantsDirty = false;
  9474. this._alphaBlend = false;
  9475. this._blendFunctionParameters = new Array(4);
  9476. this._blendEquationParameters = new Array(2);
  9477. this._blendConstants = new Array(4);
  9478. this.reset();
  9479. }
  9480. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9481. get: function () {
  9482. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9488. get: function () {
  9489. return this._alphaBlend;
  9490. },
  9491. set: function (value) {
  9492. if (this._alphaBlend === value) {
  9493. return;
  9494. }
  9495. this._alphaBlend = value;
  9496. this._isAlphaBlendDirty = true;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9502. if (this._blendConstants[0] === r &&
  9503. this._blendConstants[1] === g &&
  9504. this._blendConstants[2] === b &&
  9505. this._blendConstants[3] === a) {
  9506. return;
  9507. }
  9508. this._blendConstants[0] = r;
  9509. this._blendConstants[1] = g;
  9510. this._blendConstants[2] = b;
  9511. this._blendConstants[3] = a;
  9512. this._isBlendConstantsDirty = true;
  9513. };
  9514. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9515. if (this._blendFunctionParameters[0] === value0 &&
  9516. this._blendFunctionParameters[1] === value1 &&
  9517. this._blendFunctionParameters[2] === value2 &&
  9518. this._blendFunctionParameters[3] === value3) {
  9519. return;
  9520. }
  9521. this._blendFunctionParameters[0] = value0;
  9522. this._blendFunctionParameters[1] = value1;
  9523. this._blendFunctionParameters[2] = value2;
  9524. this._blendFunctionParameters[3] = value3;
  9525. this._isBlendFunctionParametersDirty = true;
  9526. };
  9527. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9528. if (this._blendEquationParameters[0] === rgb &&
  9529. this._blendEquationParameters[1] === alpha) {
  9530. return;
  9531. }
  9532. this._blendEquationParameters[0] = rgb;
  9533. this._blendEquationParameters[1] = alpha;
  9534. this._isBlendEquationParametersDirty = true;
  9535. };
  9536. _AlphaState.prototype.reset = function () {
  9537. this._alphaBlend = false;
  9538. this._blendFunctionParameters[0] = null;
  9539. this._blendFunctionParameters[1] = null;
  9540. this._blendFunctionParameters[2] = null;
  9541. this._blendFunctionParameters[3] = null;
  9542. this._blendEquationParameters[0] = null;
  9543. this._blendEquationParameters[1] = null;
  9544. this._blendConstants[0] = null;
  9545. this._blendConstants[1] = null;
  9546. this._blendConstants[2] = null;
  9547. this._blendConstants[3] = null;
  9548. this._isAlphaBlendDirty = true;
  9549. this._isBlendFunctionParametersDirty = false;
  9550. this._isBlendEquationParametersDirty = false;
  9551. this._isBlendConstantsDirty = false;
  9552. };
  9553. _AlphaState.prototype.apply = function (gl) {
  9554. if (!this.isDirty) {
  9555. return;
  9556. }
  9557. // Alpha blend
  9558. if (this._isAlphaBlendDirty) {
  9559. if (this._alphaBlend) {
  9560. gl.enable(gl.BLEND);
  9561. }
  9562. else {
  9563. gl.disable(gl.BLEND);
  9564. }
  9565. this._isAlphaBlendDirty = false;
  9566. }
  9567. // Alpha function
  9568. if (this._isBlendFunctionParametersDirty) {
  9569. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9570. this._isBlendFunctionParametersDirty = false;
  9571. }
  9572. // Alpha equation
  9573. if (this._isBlendEquationParametersDirty) {
  9574. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9575. this._isBlendEquationParametersDirty = false;
  9576. }
  9577. // Constants
  9578. if (this._isBlendConstantsDirty) {
  9579. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9580. this._isBlendConstantsDirty = false;
  9581. }
  9582. };
  9583. return _AlphaState;
  9584. }());
  9585. BABYLON._AlphaState = _AlphaState;
  9586. })(BABYLON || (BABYLON = {}));
  9587. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9588. var BABYLON;
  9589. (function (BABYLON) {
  9590. var _DepthCullingState = /** @class */ (function () {
  9591. /**
  9592. * Initializes the state.
  9593. */
  9594. function _DepthCullingState() {
  9595. this._isDepthTestDirty = false;
  9596. this._isDepthMaskDirty = false;
  9597. this._isDepthFuncDirty = false;
  9598. this._isCullFaceDirty = false;
  9599. this._isCullDirty = false;
  9600. this._isZOffsetDirty = false;
  9601. this._isFrontFaceDirty = false;
  9602. this.reset();
  9603. }
  9604. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9605. get: function () {
  9606. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9612. get: function () {
  9613. return this._zOffset;
  9614. },
  9615. set: function (value) {
  9616. if (this._zOffset === value) {
  9617. return;
  9618. }
  9619. this._zOffset = value;
  9620. this._isZOffsetDirty = true;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9626. get: function () {
  9627. return this._cullFace;
  9628. },
  9629. set: function (value) {
  9630. if (this._cullFace === value) {
  9631. return;
  9632. }
  9633. this._cullFace = value;
  9634. this._isCullFaceDirty = true;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9640. get: function () {
  9641. return this._cull;
  9642. },
  9643. set: function (value) {
  9644. if (this._cull === value) {
  9645. return;
  9646. }
  9647. this._cull = value;
  9648. this._isCullDirty = true;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9654. get: function () {
  9655. return this._depthFunc;
  9656. },
  9657. set: function (value) {
  9658. if (this._depthFunc === value) {
  9659. return;
  9660. }
  9661. this._depthFunc = value;
  9662. this._isDepthFuncDirty = true;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9668. get: function () {
  9669. return this._depthMask;
  9670. },
  9671. set: function (value) {
  9672. if (this._depthMask === value) {
  9673. return;
  9674. }
  9675. this._depthMask = value;
  9676. this._isDepthMaskDirty = true;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9682. get: function () {
  9683. return this._depthTest;
  9684. },
  9685. set: function (value) {
  9686. if (this._depthTest === value) {
  9687. return;
  9688. }
  9689. this._depthTest = value;
  9690. this._isDepthTestDirty = true;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9696. get: function () {
  9697. return this._frontFace;
  9698. },
  9699. set: function (value) {
  9700. if (this._frontFace === value) {
  9701. return;
  9702. }
  9703. this._frontFace = value;
  9704. this._isFrontFaceDirty = true;
  9705. },
  9706. enumerable: true,
  9707. configurable: true
  9708. });
  9709. _DepthCullingState.prototype.reset = function () {
  9710. this._depthMask = true;
  9711. this._depthTest = true;
  9712. this._depthFunc = null;
  9713. this._cullFace = null;
  9714. this._cull = null;
  9715. this._zOffset = 0;
  9716. this._frontFace = null;
  9717. this._isDepthTestDirty = true;
  9718. this._isDepthMaskDirty = true;
  9719. this._isDepthFuncDirty = false;
  9720. this._isCullFaceDirty = false;
  9721. this._isCullDirty = false;
  9722. this._isZOffsetDirty = false;
  9723. this._isFrontFaceDirty = false;
  9724. };
  9725. _DepthCullingState.prototype.apply = function (gl) {
  9726. if (!this.isDirty) {
  9727. return;
  9728. }
  9729. // Cull
  9730. if (this._isCullDirty) {
  9731. if (this.cull) {
  9732. gl.enable(gl.CULL_FACE);
  9733. }
  9734. else {
  9735. gl.disable(gl.CULL_FACE);
  9736. }
  9737. this._isCullDirty = false;
  9738. }
  9739. // Cull face
  9740. if (this._isCullFaceDirty) {
  9741. gl.cullFace(this.cullFace);
  9742. this._isCullFaceDirty = false;
  9743. }
  9744. // Depth mask
  9745. if (this._isDepthMaskDirty) {
  9746. gl.depthMask(this.depthMask);
  9747. this._isDepthMaskDirty = false;
  9748. }
  9749. // Depth test
  9750. if (this._isDepthTestDirty) {
  9751. if (this.depthTest) {
  9752. gl.enable(gl.DEPTH_TEST);
  9753. }
  9754. else {
  9755. gl.disable(gl.DEPTH_TEST);
  9756. }
  9757. this._isDepthTestDirty = false;
  9758. }
  9759. // Depth func
  9760. if (this._isDepthFuncDirty) {
  9761. gl.depthFunc(this.depthFunc);
  9762. this._isDepthFuncDirty = false;
  9763. }
  9764. // zOffset
  9765. if (this._isZOffsetDirty) {
  9766. if (this.zOffset) {
  9767. gl.enable(gl.POLYGON_OFFSET_FILL);
  9768. gl.polygonOffset(this.zOffset, 0);
  9769. }
  9770. else {
  9771. gl.disable(gl.POLYGON_OFFSET_FILL);
  9772. }
  9773. this._isZOffsetDirty = false;
  9774. }
  9775. // Front face
  9776. if (this._isFrontFaceDirty) {
  9777. gl.frontFace(this.frontFace);
  9778. this._isFrontFaceDirty = false;
  9779. }
  9780. };
  9781. return _DepthCullingState;
  9782. }());
  9783. BABYLON._DepthCullingState = _DepthCullingState;
  9784. })(BABYLON || (BABYLON = {}));
  9785. //# sourceMappingURL=babylon.depthCullingState.js.map
  9786. var BABYLON;
  9787. (function (BABYLON) {
  9788. var _StencilState = /** @class */ (function () {
  9789. function _StencilState() {
  9790. this._isStencilTestDirty = false;
  9791. this._isStencilMaskDirty = false;
  9792. this._isStencilFuncDirty = false;
  9793. this._isStencilOpDirty = false;
  9794. this.reset();
  9795. }
  9796. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9797. get: function () {
  9798. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9804. get: function () {
  9805. return this._stencilFunc;
  9806. },
  9807. set: function (value) {
  9808. if (this._stencilFunc === value) {
  9809. return;
  9810. }
  9811. this._stencilFunc = value;
  9812. this._isStencilFuncDirty = true;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9818. get: function () {
  9819. return this._stencilFuncRef;
  9820. },
  9821. set: function (value) {
  9822. if (this._stencilFuncRef === value) {
  9823. return;
  9824. }
  9825. this._stencilFuncRef = value;
  9826. this._isStencilFuncDirty = true;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9832. get: function () {
  9833. return this._stencilFuncMask;
  9834. },
  9835. set: function (value) {
  9836. if (this._stencilFuncMask === value) {
  9837. return;
  9838. }
  9839. this._stencilFuncMask = value;
  9840. this._isStencilFuncDirty = true;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9846. get: function () {
  9847. return this._stencilOpStencilFail;
  9848. },
  9849. set: function (value) {
  9850. if (this._stencilOpStencilFail === value) {
  9851. return;
  9852. }
  9853. this._stencilOpStencilFail = value;
  9854. this._isStencilOpDirty = true;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9860. get: function () {
  9861. return this._stencilOpDepthFail;
  9862. },
  9863. set: function (value) {
  9864. if (this._stencilOpDepthFail === value) {
  9865. return;
  9866. }
  9867. this._stencilOpDepthFail = value;
  9868. this._isStencilOpDirty = true;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9874. get: function () {
  9875. return this._stencilOpStencilDepthPass;
  9876. },
  9877. set: function (value) {
  9878. if (this._stencilOpStencilDepthPass === value) {
  9879. return;
  9880. }
  9881. this._stencilOpStencilDepthPass = value;
  9882. this._isStencilOpDirty = true;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9888. get: function () {
  9889. return this._stencilMask;
  9890. },
  9891. set: function (value) {
  9892. if (this._stencilMask === value) {
  9893. return;
  9894. }
  9895. this._stencilMask = value;
  9896. this._isStencilMaskDirty = true;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9902. get: function () {
  9903. return this._stencilTest;
  9904. },
  9905. set: function (value) {
  9906. if (this._stencilTest === value) {
  9907. return;
  9908. }
  9909. this._stencilTest = value;
  9910. this._isStencilTestDirty = true;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. _StencilState.prototype.reset = function () {
  9916. this._stencilTest = false;
  9917. this._stencilMask = 0xFF;
  9918. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9919. this._stencilFuncRef = 1;
  9920. this._stencilFuncMask = 0xFF;
  9921. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9922. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9923. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9924. this._isStencilTestDirty = true;
  9925. this._isStencilMaskDirty = true;
  9926. this._isStencilFuncDirty = true;
  9927. this._isStencilOpDirty = true;
  9928. };
  9929. _StencilState.prototype.apply = function (gl) {
  9930. if (!this.isDirty) {
  9931. return;
  9932. }
  9933. // Stencil test
  9934. if (this._isStencilTestDirty) {
  9935. if (this.stencilTest) {
  9936. gl.enable(gl.STENCIL_TEST);
  9937. }
  9938. else {
  9939. gl.disable(gl.STENCIL_TEST);
  9940. }
  9941. this._isStencilTestDirty = false;
  9942. }
  9943. // Stencil mask
  9944. if (this._isStencilMaskDirty) {
  9945. gl.stencilMask(this.stencilMask);
  9946. this._isStencilMaskDirty = false;
  9947. }
  9948. // Stencil func
  9949. if (this._isStencilFuncDirty) {
  9950. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9951. this._isStencilFuncDirty = false;
  9952. }
  9953. // Stencil op
  9954. if (this._isStencilOpDirty) {
  9955. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9956. this._isStencilOpDirty = false;
  9957. }
  9958. };
  9959. return _StencilState;
  9960. }());
  9961. BABYLON._StencilState = _StencilState;
  9962. })(BABYLON || (BABYLON = {}));
  9963. //# sourceMappingURL=babylon.stencilState.js.map
  9964. var BABYLON;
  9965. (function (BABYLON) {
  9966. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9967. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9968. };
  9969. var compileRawShader = function (gl, source, type) {
  9970. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9971. gl.shaderSource(shader, source);
  9972. gl.compileShader(shader);
  9973. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9974. var log = gl.getShaderInfoLog(shader);
  9975. if (log) {
  9976. throw new Error(log);
  9977. }
  9978. }
  9979. if (!shader) {
  9980. throw new Error("Something went wrong while compile the shader.");
  9981. }
  9982. return shader;
  9983. };
  9984. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9985. var magFilter = gl.NEAREST;
  9986. var minFilter = gl.NEAREST;
  9987. switch (samplingMode) {
  9988. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9989. magFilter = gl.LINEAR;
  9990. if (generateMipMaps) {
  9991. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9992. }
  9993. else {
  9994. minFilter = gl.LINEAR;
  9995. }
  9996. break;
  9997. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9998. magFilter = gl.LINEAR;
  9999. if (generateMipMaps) {
  10000. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10001. }
  10002. else {
  10003. minFilter = gl.LINEAR;
  10004. }
  10005. break;
  10006. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10007. magFilter = gl.NEAREST;
  10008. if (generateMipMaps) {
  10009. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10010. }
  10011. else {
  10012. minFilter = gl.NEAREST;
  10013. }
  10014. break;
  10015. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10016. magFilter = gl.NEAREST;
  10017. if (generateMipMaps) {
  10018. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10019. }
  10020. else {
  10021. minFilter = gl.NEAREST;
  10022. }
  10023. break;
  10024. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10025. magFilter = gl.NEAREST;
  10026. if (generateMipMaps) {
  10027. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10028. }
  10029. else {
  10030. minFilter = gl.LINEAR;
  10031. }
  10032. break;
  10033. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10034. magFilter = gl.NEAREST;
  10035. if (generateMipMaps) {
  10036. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10037. }
  10038. else {
  10039. minFilter = gl.LINEAR;
  10040. }
  10041. break;
  10042. case BABYLON.Texture.NEAREST_LINEAR:
  10043. magFilter = gl.NEAREST;
  10044. minFilter = gl.LINEAR;
  10045. break;
  10046. case BABYLON.Texture.NEAREST_NEAREST:
  10047. magFilter = gl.NEAREST;
  10048. minFilter = gl.NEAREST;
  10049. break;
  10050. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10051. magFilter = gl.LINEAR;
  10052. if (generateMipMaps) {
  10053. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10054. }
  10055. else {
  10056. minFilter = gl.NEAREST;
  10057. }
  10058. break;
  10059. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10060. magFilter = gl.LINEAR;
  10061. if (generateMipMaps) {
  10062. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10063. }
  10064. else {
  10065. minFilter = gl.NEAREST;
  10066. }
  10067. break;
  10068. case BABYLON.Texture.LINEAR_LINEAR:
  10069. magFilter = gl.LINEAR;
  10070. minFilter = gl.LINEAR;
  10071. break;
  10072. case BABYLON.Texture.LINEAR_NEAREST:
  10073. magFilter = gl.LINEAR;
  10074. minFilter = gl.NEAREST;
  10075. break;
  10076. }
  10077. return {
  10078. min: minFilter,
  10079. mag: magFilter
  10080. };
  10081. };
  10082. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10083. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10084. var img;
  10085. var onload = function () {
  10086. loadedImages[index] = img;
  10087. loadedImages._internalCount++;
  10088. if (scene) {
  10089. scene._removePendingData(img);
  10090. }
  10091. if (loadedImages._internalCount === 6) {
  10092. onfinish(loadedImages);
  10093. }
  10094. };
  10095. var onerror = function (message, exception) {
  10096. if (scene) {
  10097. scene._removePendingData(img);
  10098. }
  10099. if (onErrorCallBack) {
  10100. onErrorCallBack(message, exception);
  10101. }
  10102. };
  10103. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10104. if (scene) {
  10105. scene._addPendingData(img);
  10106. }
  10107. };
  10108. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10109. if (onError === void 0) { onError = null; }
  10110. var loadedImages = [];
  10111. loadedImages._internalCount = 0;
  10112. for (var index = 0; index < 6; index++) {
  10113. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10114. }
  10115. };
  10116. var BufferPointer = /** @class */ (function () {
  10117. function BufferPointer() {
  10118. }
  10119. return BufferPointer;
  10120. }());
  10121. var InstancingAttributeInfo = /** @class */ (function () {
  10122. function InstancingAttributeInfo() {
  10123. }
  10124. return InstancingAttributeInfo;
  10125. }());
  10126. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10127. /**
  10128. * Define options used to create a render target texture
  10129. */
  10130. var RenderTargetCreationOptions = /** @class */ (function () {
  10131. function RenderTargetCreationOptions() {
  10132. }
  10133. return RenderTargetCreationOptions;
  10134. }());
  10135. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10136. /**
  10137. * Regroup several parameters relative to the browser in use
  10138. */
  10139. var EngineCapabilities = /** @class */ (function () {
  10140. function EngineCapabilities() {
  10141. }
  10142. return EngineCapabilities;
  10143. }());
  10144. BABYLON.EngineCapabilities = EngineCapabilities;
  10145. /**
  10146. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10147. */
  10148. var Engine = /** @class */ (function () {
  10149. /**
  10150. * @constructor
  10151. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10152. * @param antialias defines enable antialiasing (default: false)
  10153. * @param options defines further options to be sent to the getContext() function
  10154. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10155. */
  10156. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10157. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10158. var _this = this;
  10159. // Public members
  10160. this.forcePOTTextures = false;
  10161. this.isFullscreen = false;
  10162. this.isPointerLock = false;
  10163. this.cullBackFaces = true;
  10164. this.renderEvenInBackground = true;
  10165. this.preventCacheWipeBetweenFrames = false;
  10166. // To enable/disable IDB support and avoid XHR on .manifest
  10167. this.enableOfflineSupport = false;
  10168. this.scenes = new Array();
  10169. this.postProcesses = new Array();
  10170. // Observables
  10171. /**
  10172. * Observable event triggered each time the rendering canvas is resized
  10173. */
  10174. this.onResizeObservable = new BABYLON.Observable();
  10175. /**
  10176. * Observable event triggered each time the canvas loses focus
  10177. */
  10178. this.onCanvasBlurObservable = new BABYLON.Observable();
  10179. /**
  10180. * Observable event triggered each time the canvas gains focus
  10181. */
  10182. this.onCanvasFocusObservable = new BABYLON.Observable();
  10183. /**
  10184. * Observable event triggered each time the canvas receives pointerout event
  10185. */
  10186. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10187. /**
  10188. * Observable event triggered before each texture is initialized
  10189. */
  10190. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10191. //WebVR
  10192. this._vrDisplay = undefined;
  10193. this._vrSupported = false;
  10194. this._vrExclusivePointerMode = false;
  10195. // Uniform buffers list
  10196. this.disableUniformBuffers = false;
  10197. this._uniformBuffers = new Array();
  10198. // Observables
  10199. /**
  10200. * Observable raised when the engine begins a new frame
  10201. */
  10202. this.onBeginFrameObservable = new BABYLON.Observable();
  10203. /**
  10204. * Observable raised when the engine ends the current frame
  10205. */
  10206. this.onEndFrameObservable = new BABYLON.Observable();
  10207. /**
  10208. * Observable raised when the engine is about to compile a shader
  10209. */
  10210. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10211. /**
  10212. * Observable raised when the engine has jsut compiled a shader
  10213. */
  10214. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10215. this._windowIsBackground = false;
  10216. this._webGLVersion = 1.0;
  10217. this._badOS = false;
  10218. this._badDesktopOS = false;
  10219. /**
  10220. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10221. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10222. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10223. */
  10224. this.disableTextureBindingOptimization = false;
  10225. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10226. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10227. this.onVRRequestPresentStart = new BABYLON.Observable();
  10228. this._colorWrite = true;
  10229. this._drawCalls = new BABYLON.PerfCounter();
  10230. this._textureCollisions = new BABYLON.PerfCounter();
  10231. this._renderingQueueLaunched = false;
  10232. this._activeRenderLoops = new Array();
  10233. // Deterministic lockstepMaxSteps
  10234. this._deterministicLockstep = false;
  10235. this._lockstepMaxSteps = 4;
  10236. // Lost context
  10237. this.onContextLostObservable = new BABYLON.Observable();
  10238. this.onContextRestoredObservable = new BABYLON.Observable();
  10239. this._contextWasLost = false;
  10240. this._doNotHandleContextLost = false;
  10241. // FPS
  10242. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10243. this._fps = 60;
  10244. this._deltaTime = 0;
  10245. /**
  10246. * Turn this value on if you want to pause FPS computation when in background
  10247. */
  10248. this.disablePerformanceMonitorInBackground = false;
  10249. // States
  10250. this._depthCullingState = new BABYLON._DepthCullingState();
  10251. this._stencilState = new BABYLON._StencilState();
  10252. this._alphaState = new BABYLON._AlphaState();
  10253. this._alphaMode = Engine.ALPHA_DISABLE;
  10254. // Cache
  10255. this._internalTexturesCache = new Array();
  10256. this._activeChannel = 0;
  10257. this._currentTextureChannel = -1;
  10258. this._boundTexturesCache = {};
  10259. this._compiledEffects = {};
  10260. this._vertexAttribArraysEnabled = [];
  10261. this._uintIndicesCurrentlySet = false;
  10262. this._currentBoundBuffer = new Array();
  10263. this._currentBufferPointers = new Array();
  10264. this._currentInstanceLocations = new Array();
  10265. this._currentInstanceBuffers = new Array();
  10266. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10267. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10268. this._vaoRecordInProgress = false;
  10269. this._mustWipeVertexAttributes = false;
  10270. this._nextFreeTextureSlots = new Array();
  10271. this._maxSimultaneousTextures = 0;
  10272. this._activeRequests = new Array();
  10273. // Hardware supported Compressed Textures
  10274. this._texturesSupported = new Array();
  10275. this._onVRFullScreenTriggered = function () {
  10276. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10277. //get the old size before we change
  10278. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10279. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10280. //get the width and height, change the render size
  10281. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10282. _this.setHardwareScalingLevel(1);
  10283. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10284. }
  10285. else {
  10286. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10287. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10288. }
  10289. };
  10290. this._boundUniforms = {};
  10291. // Register promises
  10292. BABYLON.PromisePolyfill.Apply();
  10293. var canvas = null;
  10294. Engine.Instances.push(this);
  10295. if (!canvasOrContext) {
  10296. return;
  10297. }
  10298. options = options || {};
  10299. if (canvasOrContext.getContext) {
  10300. canvas = canvasOrContext;
  10301. this._renderingCanvas = canvas;
  10302. if (antialias != null) {
  10303. options.antialias = antialias;
  10304. }
  10305. if (options.deterministicLockstep === undefined) {
  10306. options.deterministicLockstep = false;
  10307. }
  10308. if (options.lockstepMaxSteps === undefined) {
  10309. options.lockstepMaxSteps = 4;
  10310. }
  10311. if (options.preserveDrawingBuffer === undefined) {
  10312. options.preserveDrawingBuffer = false;
  10313. }
  10314. if (options.audioEngine === undefined) {
  10315. options.audioEngine = true;
  10316. }
  10317. if (options.stencil === undefined) {
  10318. options.stencil = true;
  10319. }
  10320. this._deterministicLockstep = options.deterministicLockstep;
  10321. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10322. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10323. // Exceptions
  10324. if (navigator && navigator.userAgent) {
  10325. var ua = navigator.userAgent;
  10326. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10327. var exception = _a[_i];
  10328. var key = exception.key;
  10329. var targets = exception.targets;
  10330. if (ua.indexOf(key) > -1) {
  10331. if (exception.capture && exception.captureConstraint) {
  10332. var capture = exception.capture;
  10333. var constraint = exception.captureConstraint;
  10334. var regex = new RegExp(capture);
  10335. var matches = regex.exec(ua);
  10336. if (matches && matches.length > 0) {
  10337. var capturedValue = parseInt(matches[matches.length - 1]);
  10338. if (capturedValue >= constraint) {
  10339. continue;
  10340. }
  10341. }
  10342. }
  10343. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10344. var target = targets_1[_b];
  10345. switch (target) {
  10346. case "uniformBuffer":
  10347. this.disableUniformBuffers = true;
  10348. break;
  10349. case "textureBindingOptimization":
  10350. this.disableTextureBindingOptimization = true;
  10351. break;
  10352. }
  10353. }
  10354. break;
  10355. }
  10356. }
  10357. }
  10358. // GL
  10359. if (!options.disableWebGL2Support) {
  10360. try {
  10361. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10362. if (this._gl) {
  10363. this._webGLVersion = 2.0;
  10364. }
  10365. }
  10366. catch (e) {
  10367. // Do nothing
  10368. }
  10369. }
  10370. if (!this._gl) {
  10371. if (!canvas) {
  10372. throw new Error("The provided canvas is null or undefined.");
  10373. }
  10374. try {
  10375. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10376. }
  10377. catch (e) {
  10378. throw new Error("WebGL not supported");
  10379. }
  10380. }
  10381. if (!this._gl) {
  10382. throw new Error("WebGL not supported");
  10383. }
  10384. this._onCanvasFocus = function () {
  10385. _this.onCanvasFocusObservable.notifyObservers(_this);
  10386. };
  10387. this._onCanvasBlur = function () {
  10388. _this.onCanvasBlurObservable.notifyObservers(_this);
  10389. };
  10390. canvas.addEventListener("focus", this._onCanvasFocus);
  10391. canvas.addEventListener("blur", this._onCanvasBlur);
  10392. this._onBlur = function () {
  10393. if (_this.disablePerformanceMonitorInBackground) {
  10394. _this._performanceMonitor.disable();
  10395. }
  10396. _this._windowIsBackground = true;
  10397. };
  10398. this._onFocus = function () {
  10399. if (_this.disablePerformanceMonitorInBackground) {
  10400. _this._performanceMonitor.enable();
  10401. }
  10402. _this._windowIsBackground = false;
  10403. };
  10404. this._onCanvasPointerOut = function () {
  10405. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10406. };
  10407. window.addEventListener("blur", this._onBlur);
  10408. window.addEventListener("focus", this._onFocus);
  10409. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10410. // Context lost
  10411. if (!this._doNotHandleContextLost) {
  10412. this._onContextLost = function (evt) {
  10413. evt.preventDefault();
  10414. _this._contextWasLost = true;
  10415. BABYLON.Tools.Warn("WebGL context lost.");
  10416. _this.onContextLostObservable.notifyObservers(_this);
  10417. };
  10418. this._onContextRestored = function (evt) {
  10419. // Adding a timeout to avoid race condition at browser level
  10420. setTimeout(function () {
  10421. // Rebuild gl context
  10422. _this._initGLContext();
  10423. // Rebuild effects
  10424. _this._rebuildEffects();
  10425. // Rebuild textures
  10426. _this._rebuildInternalTextures();
  10427. // Rebuild buffers
  10428. _this._rebuildBuffers();
  10429. // Cache
  10430. _this.wipeCaches(true);
  10431. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10432. _this.onContextRestoredObservable.notifyObservers(_this);
  10433. _this._contextWasLost = false;
  10434. }, 0);
  10435. };
  10436. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10437. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10438. }
  10439. }
  10440. else {
  10441. this._gl = canvasOrContext;
  10442. this._renderingCanvas = this._gl.canvas;
  10443. if (this._gl.renderbufferStorageMultisample) {
  10444. this._webGLVersion = 2.0;
  10445. }
  10446. options.stencil = this._gl.getContextAttributes().stencil;
  10447. }
  10448. // Viewport
  10449. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10450. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10451. this.resize();
  10452. this._isStencilEnable = options.stencil ? true : false;
  10453. this._initGLContext();
  10454. if (canvas) {
  10455. // Fullscreen
  10456. this._onFullscreenChange = function () {
  10457. if (document.fullscreen !== undefined) {
  10458. _this.isFullscreen = document.fullscreen;
  10459. }
  10460. else if (document.mozFullScreen !== undefined) {
  10461. _this.isFullscreen = document.mozFullScreen;
  10462. }
  10463. else if (document.webkitIsFullScreen !== undefined) {
  10464. _this.isFullscreen = document.webkitIsFullScreen;
  10465. }
  10466. else if (document.msIsFullScreen !== undefined) {
  10467. _this.isFullscreen = document.msIsFullScreen;
  10468. }
  10469. // Pointer lock
  10470. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10471. canvas.requestPointerLock = canvas.requestPointerLock ||
  10472. canvas.msRequestPointerLock ||
  10473. canvas.mozRequestPointerLock ||
  10474. canvas.webkitRequestPointerLock;
  10475. if (canvas.requestPointerLock) {
  10476. canvas.requestPointerLock();
  10477. }
  10478. }
  10479. };
  10480. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10481. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10482. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10483. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10484. // Pointer lock
  10485. this._onPointerLockChange = function () {
  10486. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10487. document.webkitPointerLockElement === canvas ||
  10488. document.msPointerLockElement === canvas ||
  10489. document.pointerLockElement === canvas);
  10490. };
  10491. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10492. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10493. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10494. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10495. this._onVRDisplayPointerRestricted = function () {
  10496. if (canvas) {
  10497. canvas.requestPointerLock();
  10498. }
  10499. };
  10500. this._onVRDisplayPointerUnrestricted = function () {
  10501. document.exitPointerLock();
  10502. };
  10503. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10504. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10505. }
  10506. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10507. Engine.audioEngine = new BABYLON.AudioEngine();
  10508. }
  10509. // Prepare buffer pointers
  10510. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10511. this._currentBufferPointers[i] = new BufferPointer();
  10512. }
  10513. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10514. // Load WebVR Devices
  10515. if (options.autoEnableWebVR) {
  10516. this.initWebVR();
  10517. }
  10518. // Detect if we are running on a faulty buggy OS.
  10519. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10520. // Detect if we are running on a faulty buggy desktop OS.
  10521. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10522. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10523. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10524. }
  10525. Object.defineProperty(Engine, "LastCreatedEngine", {
  10526. get: function () {
  10527. if (Engine.Instances.length === 0) {
  10528. return null;
  10529. }
  10530. return Engine.Instances[Engine.Instances.length - 1];
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. Object.defineProperty(Engine, "LastCreatedScene", {
  10536. get: function () {
  10537. var lastCreatedEngine = Engine.LastCreatedEngine;
  10538. if (!lastCreatedEngine) {
  10539. return null;
  10540. }
  10541. if (lastCreatedEngine.scenes.length === 0) {
  10542. return null;
  10543. }
  10544. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. /**
  10550. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10551. */
  10552. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10553. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10554. var engine = Engine.Instances[engineIndex];
  10555. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10556. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10557. }
  10558. }
  10559. };
  10560. Object.defineProperty(Engine, "NEVER", {
  10561. get: function () {
  10562. return Engine._NEVER;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(Engine, "ALWAYS", {
  10568. get: function () {
  10569. return Engine._ALWAYS;
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Object.defineProperty(Engine, "LESS", {
  10575. get: function () {
  10576. return Engine._LESS;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(Engine, "EQUAL", {
  10582. get: function () {
  10583. return Engine._EQUAL;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(Engine, "LEQUAL", {
  10589. get: function () {
  10590. return Engine._LEQUAL;
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. Object.defineProperty(Engine, "GREATER", {
  10596. get: function () {
  10597. return Engine._GREATER;
  10598. },
  10599. enumerable: true,
  10600. configurable: true
  10601. });
  10602. Object.defineProperty(Engine, "GEQUAL", {
  10603. get: function () {
  10604. return Engine._GEQUAL;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Object.defineProperty(Engine, "NOTEQUAL", {
  10610. get: function () {
  10611. return Engine._NOTEQUAL;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(Engine, "KEEP", {
  10617. get: function () {
  10618. return Engine._KEEP;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(Engine, "REPLACE", {
  10624. get: function () {
  10625. return Engine._REPLACE;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(Engine, "INCR", {
  10631. get: function () {
  10632. return Engine._INCR;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(Engine, "DECR", {
  10638. get: function () {
  10639. return Engine._DECR;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(Engine, "INVERT", {
  10645. get: function () {
  10646. return Engine._INVERT;
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. Object.defineProperty(Engine, "INCR_WRAP", {
  10652. get: function () {
  10653. return Engine._INCR_WRAP;
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. Object.defineProperty(Engine, "DECR_WRAP", {
  10659. get: function () {
  10660. return Engine._DECR_WRAP;
  10661. },
  10662. enumerable: true,
  10663. configurable: true
  10664. });
  10665. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10666. get: function () {
  10667. return Engine._ALPHA_DISABLE;
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10673. get: function () {
  10674. return Engine._ALPHA_ONEONE;
  10675. },
  10676. enumerable: true,
  10677. configurable: true
  10678. });
  10679. Object.defineProperty(Engine, "ALPHA_ADD", {
  10680. get: function () {
  10681. return Engine._ALPHA_ADD;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10687. get: function () {
  10688. return Engine._ALPHA_COMBINE;
  10689. },
  10690. enumerable: true,
  10691. configurable: true
  10692. });
  10693. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10694. get: function () {
  10695. return Engine._ALPHA_SUBTRACT;
  10696. },
  10697. enumerable: true,
  10698. configurable: true
  10699. });
  10700. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10701. get: function () {
  10702. return Engine._ALPHA_MULTIPLY;
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10708. get: function () {
  10709. return Engine._ALPHA_MAXIMIZED;
  10710. },
  10711. enumerable: true,
  10712. configurable: true
  10713. });
  10714. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10715. get: function () {
  10716. return Engine._ALPHA_PREMULTIPLIED;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10722. get: function () {
  10723. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10729. get: function () {
  10730. return Engine._ALPHA_INTERPOLATE;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10736. get: function () {
  10737. return Engine._ALPHA_SCREENMODE;
  10738. },
  10739. enumerable: true,
  10740. configurable: true
  10741. });
  10742. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10743. get: function () {
  10744. return Engine._DELAYLOADSTATE_NONE;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10750. get: function () {
  10751. return Engine._DELAYLOADSTATE_LOADED;
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10757. get: function () {
  10758. return Engine._DELAYLOADSTATE_LOADING;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10764. get: function () {
  10765. return Engine._DELAYLOADSTATE_NOTLOADED;
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10771. get: function () {
  10772. return Engine._TEXTUREFORMAT_ALPHA;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10778. get: function () {
  10779. return Engine._TEXTUREFORMAT_LUMINANCE;
  10780. },
  10781. enumerable: true,
  10782. configurable: true
  10783. });
  10784. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10785. get: function () {
  10786. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10792. get: function () {
  10793. return Engine._TEXTUREFORMAT_RGB;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10799. get: function () {
  10800. return Engine._TEXTUREFORMAT_RGBA;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10806. get: function () {
  10807. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10813. get: function () {
  10814. return Engine._TEXTURETYPE_FLOAT;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10820. get: function () {
  10821. return Engine._TEXTURETYPE_HALF_FLOAT;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10827. get: function () {
  10828. return Engine._SCALEMODE_FLOOR;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10834. get: function () {
  10835. return Engine._SCALEMODE_NEAREST;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10841. get: function () {
  10842. return Engine._SCALEMODE_CEILING;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Object.defineProperty(Engine, "Version", {
  10848. get: function () {
  10849. return "3.2.0-alpha7";
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10855. get: function () {
  10856. return this._vrExclusivePointerMode;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10862. get: function () {
  10863. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10869. get: function () {
  10870. return this._webGLVersion < 2 || this.forcePOTTextures;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(Engine.prototype, "badOS", {
  10876. get: function () {
  10877. return this._badOS;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10883. get: function () {
  10884. return this._badDesktopOS;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10890. get: function () {
  10891. return this._performanceMonitor;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10897. get: function () {
  10898. return this._texturesSupported;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10904. get: function () {
  10905. return this._textureFormatInUse;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(Engine.prototype, "currentViewport", {
  10911. get: function () {
  10912. return this._cachedViewport;
  10913. },
  10914. enumerable: true,
  10915. configurable: true
  10916. });
  10917. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10918. // Empty texture
  10919. get: function () {
  10920. if (!this._emptyTexture) {
  10921. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10922. }
  10923. return this._emptyTexture;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10929. get: function () {
  10930. if (!this._emptyTexture3D) {
  10931. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10932. }
  10933. return this._emptyTexture3D;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10939. get: function () {
  10940. if (!this._emptyCubeTexture) {
  10941. var faceData = new Uint8Array(4);
  10942. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10943. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10944. }
  10945. return this._emptyCubeTexture;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Engine.prototype._rebuildInternalTextures = function () {
  10951. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10952. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10953. var internalTexture = currentState_1[_i];
  10954. internalTexture._rebuild();
  10955. }
  10956. };
  10957. Engine.prototype._rebuildEffects = function () {
  10958. for (var key in this._compiledEffects) {
  10959. var effect = this._compiledEffects[key];
  10960. effect._prepareEffect();
  10961. }
  10962. BABYLON.Effect.ResetCache();
  10963. };
  10964. Engine.prototype._rebuildBuffers = function () {
  10965. // Index / Vertex
  10966. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10967. var scene = _a[_i];
  10968. scene.resetCachedMaterial();
  10969. scene._rebuildGeometries();
  10970. scene._rebuildTextures();
  10971. }
  10972. // Uniforms
  10973. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10974. var uniformBuffer = _c[_b];
  10975. uniformBuffer._rebuild();
  10976. }
  10977. };
  10978. Engine.prototype._initGLContext = function () {
  10979. // Caps
  10980. this._caps = new EngineCapabilities();
  10981. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10982. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10983. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10984. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10985. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10986. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10987. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10988. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10989. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10990. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10991. // Infos
  10992. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10993. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10994. if (rendererInfo != null) {
  10995. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10996. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10997. }
  10998. if (!this._glVendor) {
  10999. this._glVendor = "Unknown vendor";
  11000. }
  11001. if (!this._glRenderer) {
  11002. this._glRenderer = "Unknown renderer";
  11003. }
  11004. // Constants
  11005. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11006. if (this._gl.RGBA16F !== 0x881A) {
  11007. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11008. }
  11009. if (this._gl.RGBA32F !== 0x8814) {
  11010. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11011. }
  11012. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11013. this._gl.DEPTH24_STENCIL8 = 35056;
  11014. }
  11015. // Extensions
  11016. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11017. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11018. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11019. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11020. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11021. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11022. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11023. 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');
  11024. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11025. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11026. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11027. this._caps.highPrecisionShaderSupported = true;
  11028. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11029. if (this._caps.timerQuery) {
  11030. if (this._webGLVersion === 1) {
  11031. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11032. }
  11033. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11034. }
  11035. // Checks if some of the format renders first to allow the use of webgl inspector.
  11036. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11037. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11038. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11039. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11040. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11041. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11042. if (this._webGLVersion > 1) {
  11043. this._gl.HALF_FLOAT_OES = 0x140B;
  11044. }
  11045. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11046. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11047. // Draw buffers
  11048. if (this._webGLVersion > 1) {
  11049. this._caps.drawBuffersExtension = true;
  11050. }
  11051. else {
  11052. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11053. if (drawBuffersExtension !== null) {
  11054. this._caps.drawBuffersExtension = true;
  11055. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11056. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11057. for (var i = 0; i < 16; i++) {
  11058. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11059. }
  11060. }
  11061. else {
  11062. this._caps.drawBuffersExtension = false;
  11063. }
  11064. }
  11065. // Depth Texture
  11066. if (this._webGLVersion > 1) {
  11067. this._caps.depthTextureExtension = true;
  11068. }
  11069. else {
  11070. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11071. if (depthTextureExtension != null) {
  11072. this._caps.depthTextureExtension = true;
  11073. }
  11074. }
  11075. // Vertex array object
  11076. if (this._webGLVersion > 1) {
  11077. this._caps.vertexArrayObject = true;
  11078. }
  11079. else {
  11080. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11081. if (vertexArrayObjectExtension != null) {
  11082. this._caps.vertexArrayObject = true;
  11083. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11084. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11085. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11086. }
  11087. else {
  11088. this._caps.vertexArrayObject = false;
  11089. }
  11090. }
  11091. // Instances count
  11092. if (this._webGLVersion > 1) {
  11093. this._caps.instancedArrays = true;
  11094. }
  11095. else {
  11096. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11097. if (instanceExtension != null) {
  11098. this._caps.instancedArrays = true;
  11099. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11100. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11101. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11102. }
  11103. else {
  11104. this._caps.instancedArrays = false;
  11105. }
  11106. }
  11107. // Intelligently add supported compressed formats in order to check for.
  11108. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11109. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11110. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11111. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11112. if (this._caps.astc)
  11113. this.texturesSupported.push('-astc.ktx');
  11114. if (this._caps.s3tc)
  11115. this.texturesSupported.push('-dxt.ktx');
  11116. if (this._caps.pvrtc)
  11117. this.texturesSupported.push('-pvrtc.ktx');
  11118. if (this._caps.etc2)
  11119. this.texturesSupported.push('-etc2.ktx');
  11120. if (this._caps.etc1)
  11121. this.texturesSupported.push('-etc1.ktx');
  11122. if (this._gl.getShaderPrecisionFormat) {
  11123. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11124. if (highp) {
  11125. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11126. }
  11127. }
  11128. // Depth buffer
  11129. this.setDepthBuffer(true);
  11130. this.setDepthFunctionToLessOrEqual();
  11131. this.setDepthWrite(true);
  11132. // Texture maps
  11133. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11134. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11135. this._nextFreeTextureSlots.push(slot);
  11136. }
  11137. };
  11138. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11139. get: function () {
  11140. return this._webGLVersion;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11146. /**
  11147. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11148. */
  11149. get: function () {
  11150. return this._isStencilEnable;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Engine.prototype._prepareWorkingCanvas = function () {
  11156. if (this._workingCanvas) {
  11157. return;
  11158. }
  11159. this._workingCanvas = document.createElement("canvas");
  11160. var context = this._workingCanvas.getContext("2d");
  11161. if (context) {
  11162. this._workingContext = context;
  11163. }
  11164. };
  11165. Engine.prototype.resetTextureCache = function () {
  11166. for (var key in this._boundTexturesCache) {
  11167. var boundTexture = this._boundTexturesCache[key];
  11168. if (boundTexture) {
  11169. this._removeDesignatedSlot(boundTexture);
  11170. }
  11171. this._boundTexturesCache[key] = null;
  11172. }
  11173. if (!this.disableTextureBindingOptimization) {
  11174. this._nextFreeTextureSlots = [];
  11175. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11176. this._nextFreeTextureSlots.push(slot);
  11177. }
  11178. }
  11179. this._currentTextureChannel = -1;
  11180. };
  11181. Engine.prototype.isDeterministicLockStep = function () {
  11182. return this._deterministicLockstep;
  11183. };
  11184. Engine.prototype.getLockstepMaxSteps = function () {
  11185. return this._lockstepMaxSteps;
  11186. };
  11187. Engine.prototype.getGlInfo = function () {
  11188. return {
  11189. vendor: this._glVendor,
  11190. renderer: this._glRenderer,
  11191. version: this._glVersion
  11192. };
  11193. };
  11194. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11195. if (useScreen === void 0) { useScreen = false; }
  11196. var viewport = camera.viewport;
  11197. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11198. };
  11199. Engine.prototype.getRenderWidth = function (useScreen) {
  11200. if (useScreen === void 0) { useScreen = false; }
  11201. if (!useScreen && this._currentRenderTarget) {
  11202. return this._currentRenderTarget.width;
  11203. }
  11204. return this._gl.drawingBufferWidth;
  11205. };
  11206. Engine.prototype.getRenderHeight = function (useScreen) {
  11207. if (useScreen === void 0) { useScreen = false; }
  11208. if (!useScreen && this._currentRenderTarget) {
  11209. return this._currentRenderTarget.height;
  11210. }
  11211. return this._gl.drawingBufferHeight;
  11212. };
  11213. Engine.prototype.getRenderingCanvas = function () {
  11214. return this._renderingCanvas;
  11215. };
  11216. Engine.prototype.getRenderingCanvasClientRect = function () {
  11217. if (!this._renderingCanvas) {
  11218. return null;
  11219. }
  11220. return this._renderingCanvas.getBoundingClientRect();
  11221. };
  11222. Engine.prototype.setHardwareScalingLevel = function (level) {
  11223. this._hardwareScalingLevel = level;
  11224. this.resize();
  11225. };
  11226. Engine.prototype.getHardwareScalingLevel = function () {
  11227. return this._hardwareScalingLevel;
  11228. };
  11229. Engine.prototype.getLoadedTexturesCache = function () {
  11230. return this._internalTexturesCache;
  11231. };
  11232. Engine.prototype.getCaps = function () {
  11233. return this._caps;
  11234. };
  11235. Object.defineProperty(Engine.prototype, "drawCalls", {
  11236. /** The number of draw calls submitted last frame */
  11237. get: function () {
  11238. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11239. return 0;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11245. get: function () {
  11246. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11247. return null;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Engine.prototype.getDepthFunction = function () {
  11253. return this._depthCullingState.depthFunc;
  11254. };
  11255. Engine.prototype.setDepthFunction = function (depthFunc) {
  11256. this._depthCullingState.depthFunc = depthFunc;
  11257. };
  11258. Engine.prototype.setDepthFunctionToGreater = function () {
  11259. this._depthCullingState.depthFunc = this._gl.GREATER;
  11260. };
  11261. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11262. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11263. };
  11264. Engine.prototype.setDepthFunctionToLess = function () {
  11265. this._depthCullingState.depthFunc = this._gl.LESS;
  11266. };
  11267. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11268. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11269. };
  11270. Engine.prototype.getStencilBuffer = function () {
  11271. return this._stencilState.stencilTest;
  11272. };
  11273. Engine.prototype.setStencilBuffer = function (enable) {
  11274. this._stencilState.stencilTest = enable;
  11275. };
  11276. Engine.prototype.getStencilMask = function () {
  11277. return this._stencilState.stencilMask;
  11278. };
  11279. Engine.prototype.setStencilMask = function (mask) {
  11280. this._stencilState.stencilMask = mask;
  11281. };
  11282. Engine.prototype.getStencilFunction = function () {
  11283. return this._stencilState.stencilFunc;
  11284. };
  11285. Engine.prototype.getStencilFunctionReference = function () {
  11286. return this._stencilState.stencilFuncRef;
  11287. };
  11288. Engine.prototype.getStencilFunctionMask = function () {
  11289. return this._stencilState.stencilFuncMask;
  11290. };
  11291. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11292. this._stencilState.stencilFunc = stencilFunc;
  11293. };
  11294. Engine.prototype.setStencilFunctionReference = function (reference) {
  11295. this._stencilState.stencilFuncRef = reference;
  11296. };
  11297. Engine.prototype.setStencilFunctionMask = function (mask) {
  11298. this._stencilState.stencilFuncMask = mask;
  11299. };
  11300. Engine.prototype.getStencilOperationFail = function () {
  11301. return this._stencilState.stencilOpStencilFail;
  11302. };
  11303. Engine.prototype.getStencilOperationDepthFail = function () {
  11304. return this._stencilState.stencilOpDepthFail;
  11305. };
  11306. Engine.prototype.getStencilOperationPass = function () {
  11307. return this._stencilState.stencilOpStencilDepthPass;
  11308. };
  11309. Engine.prototype.setStencilOperationFail = function (operation) {
  11310. this._stencilState.stencilOpStencilFail = operation;
  11311. };
  11312. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11313. this._stencilState.stencilOpDepthFail = operation;
  11314. };
  11315. Engine.prototype.setStencilOperationPass = function (operation) {
  11316. this._stencilState.stencilOpStencilDepthPass = operation;
  11317. };
  11318. Engine.prototype.setDitheringState = function (value) {
  11319. if (value) {
  11320. this._gl.enable(this._gl.DITHER);
  11321. }
  11322. else {
  11323. this._gl.disable(this._gl.DITHER);
  11324. }
  11325. };
  11326. Engine.prototype.setRasterizerState = function (value) {
  11327. if (value) {
  11328. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11329. }
  11330. else {
  11331. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11332. }
  11333. };
  11334. /**
  11335. * stop executing a render loop function and remove it from the execution array
  11336. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11337. */
  11338. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11339. if (!renderFunction) {
  11340. this._activeRenderLoops = [];
  11341. return;
  11342. }
  11343. var index = this._activeRenderLoops.indexOf(renderFunction);
  11344. if (index >= 0) {
  11345. this._activeRenderLoops.splice(index, 1);
  11346. }
  11347. };
  11348. Engine.prototype._renderLoop = function () {
  11349. if (!this._contextWasLost) {
  11350. var shouldRender = true;
  11351. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11352. shouldRender = false;
  11353. }
  11354. if (shouldRender) {
  11355. // Start new frame
  11356. this.beginFrame();
  11357. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11358. var renderFunction = this._activeRenderLoops[index];
  11359. renderFunction();
  11360. }
  11361. // Present
  11362. this.endFrame();
  11363. }
  11364. }
  11365. if (this._activeRenderLoops.length > 0) {
  11366. // Register new frame
  11367. var requester = null;
  11368. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11369. requester = this._vrDisplay;
  11370. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11371. }
  11372. else {
  11373. this._renderingQueueLaunched = false;
  11374. }
  11375. };
  11376. /**
  11377. * Register and execute a render loop. The engine can have more than one render function.
  11378. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11379. * @example
  11380. * engine.runRenderLoop(function () {
  11381. * scene.render()
  11382. * })
  11383. */
  11384. Engine.prototype.runRenderLoop = function (renderFunction) {
  11385. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11386. return;
  11387. }
  11388. this._activeRenderLoops.push(renderFunction);
  11389. if (!this._renderingQueueLaunched) {
  11390. this._renderingQueueLaunched = true;
  11391. this._bindedRenderFunction = this._renderLoop.bind(this);
  11392. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11393. }
  11394. };
  11395. /**
  11396. * Toggle full screen mode.
  11397. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11398. * @param {any} options - an options object to be sent to the requestFullscreen function
  11399. */
  11400. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11401. if (this.isFullscreen) {
  11402. BABYLON.Tools.ExitFullscreen();
  11403. }
  11404. else {
  11405. this._pointerLockRequested = requestPointerLock;
  11406. if (this._renderingCanvas) {
  11407. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11408. }
  11409. }
  11410. };
  11411. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11412. if (stencil === void 0) { stencil = false; }
  11413. this.applyStates();
  11414. var mode = 0;
  11415. if (backBuffer && color) {
  11416. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11417. mode |= this._gl.COLOR_BUFFER_BIT;
  11418. }
  11419. if (depth) {
  11420. this._gl.clearDepth(1.0);
  11421. mode |= this._gl.DEPTH_BUFFER_BIT;
  11422. }
  11423. if (stencil) {
  11424. this._gl.clearStencil(0);
  11425. mode |= this._gl.STENCIL_BUFFER_BIT;
  11426. }
  11427. this._gl.clear(mode);
  11428. };
  11429. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11430. var gl = this._gl;
  11431. // Save state
  11432. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11433. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11434. // Change state
  11435. gl.enable(gl.SCISSOR_TEST);
  11436. gl.scissor(x, y, width, height);
  11437. // Clear
  11438. this.clear(clearColor, true, true, true);
  11439. // Restore state
  11440. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11441. if (curScissor === true) {
  11442. gl.enable(gl.SCISSOR_TEST);
  11443. }
  11444. else {
  11445. gl.disable(gl.SCISSOR_TEST);
  11446. }
  11447. };
  11448. /**
  11449. * Set the WebGL's viewport
  11450. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11451. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11452. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11453. */
  11454. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11455. var width = requiredWidth || this.getRenderWidth();
  11456. var height = requiredHeight || this.getRenderHeight();
  11457. var x = viewport.x || 0;
  11458. var y = viewport.y || 0;
  11459. this._cachedViewport = viewport;
  11460. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11461. };
  11462. /**
  11463. * Directly set the WebGL Viewport
  11464. * The x, y, width & height are directly passed to the WebGL call
  11465. * @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.
  11466. */
  11467. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11468. var currentViewport = this._cachedViewport;
  11469. this._cachedViewport = null;
  11470. this._gl.viewport(x, y, width, height);
  11471. return currentViewport;
  11472. };
  11473. Engine.prototype.beginFrame = function () {
  11474. this.onBeginFrameObservable.notifyObservers(this);
  11475. this._measureFps();
  11476. };
  11477. Engine.prototype.endFrame = function () {
  11478. //force a flush in case we are using a bad OS.
  11479. if (this._badOS) {
  11480. this.flushFramebuffer();
  11481. }
  11482. //submit frame to the vr device, if enabled
  11483. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11484. // TODO: We should only submit the frame if we read frameData successfully.
  11485. this._vrDisplay.submitFrame();
  11486. }
  11487. this.onEndFrameObservable.notifyObservers(this);
  11488. };
  11489. /**
  11490. * resize the view according to the canvas' size.
  11491. * @example
  11492. * window.addEventListener("resize", function () {
  11493. * engine.resize();
  11494. * });
  11495. */
  11496. Engine.prototype.resize = function () {
  11497. // We're not resizing the size of the canvas while in VR mode & presenting
  11498. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11499. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11500. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11501. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11502. }
  11503. };
  11504. /**
  11505. * force a specific size of the canvas
  11506. * @param {number} width - the new canvas' width
  11507. * @param {number} height - the new canvas' height
  11508. */
  11509. Engine.prototype.setSize = function (width, height) {
  11510. if (!this._renderingCanvas) {
  11511. return;
  11512. }
  11513. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11514. return;
  11515. }
  11516. this._renderingCanvas.width = width;
  11517. this._renderingCanvas.height = height;
  11518. for (var index = 0; index < this.scenes.length; index++) {
  11519. var scene = this.scenes[index];
  11520. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11521. var cam = scene.cameras[camIndex];
  11522. cam._currentRenderId = 0;
  11523. }
  11524. }
  11525. if (this.onResizeObservable.hasObservers) {
  11526. this.onResizeObservable.notifyObservers(this);
  11527. }
  11528. };
  11529. // WebVR functions
  11530. Engine.prototype.isVRDevicePresent = function () {
  11531. return !!this._vrDisplay;
  11532. };
  11533. Engine.prototype.getVRDevice = function () {
  11534. return this._vrDisplay;
  11535. };
  11536. Engine.prototype.initWebVR = function () {
  11537. var _this = this;
  11538. var notifyObservers = function () {
  11539. var eventArgs = {
  11540. vrDisplay: _this._vrDisplay,
  11541. vrSupported: _this._vrSupported
  11542. };
  11543. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11544. };
  11545. if (!this._onVrDisplayConnect) {
  11546. this._onVrDisplayConnect = function (event) {
  11547. _this._vrDisplay = event.display;
  11548. notifyObservers();
  11549. };
  11550. this._onVrDisplayDisconnect = function () {
  11551. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11552. _this._vrDisplay = undefined;
  11553. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11554. notifyObservers();
  11555. };
  11556. this._onVrDisplayPresentChange = function () {
  11557. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11558. };
  11559. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11560. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11561. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11562. }
  11563. this._getVRDisplays(notifyObservers);
  11564. return this.onVRDisplayChangedObservable;
  11565. };
  11566. Engine.prototype.enableVR = function () {
  11567. var _this = this;
  11568. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11569. var onResolved = function () {
  11570. _this.onVRRequestPresentComplete.notifyObservers(true);
  11571. _this._onVRFullScreenTriggered();
  11572. };
  11573. var onRejected = function () {
  11574. _this.onVRRequestPresentComplete.notifyObservers(false);
  11575. };
  11576. this.onVRRequestPresentStart.notifyObservers(this);
  11577. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11578. }
  11579. };
  11580. Engine.prototype.disableVR = function () {
  11581. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11582. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11583. }
  11584. };
  11585. Engine.prototype._getVRDisplays = function (callback) {
  11586. var _this = this;
  11587. var getWebVRDevices = function (devices) {
  11588. _this._vrSupported = true;
  11589. // note that devices may actually be an empty array. This is fine;
  11590. // we expect this._vrDisplay to be undefined in this case.
  11591. return _this._vrDisplay = devices[0];
  11592. };
  11593. if (navigator.getVRDisplays) {
  11594. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11595. // TODO: System CANNOT support WebVR, despite API presence.
  11596. _this._vrSupported = false;
  11597. callback();
  11598. });
  11599. }
  11600. else {
  11601. // TODO: Browser does not support WebVR
  11602. this._vrDisplay = undefined;
  11603. this._vrSupported = false;
  11604. callback();
  11605. }
  11606. };
  11607. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11608. if (this._currentRenderTarget) {
  11609. this.unBindFramebuffer(this._currentRenderTarget);
  11610. }
  11611. this._currentRenderTarget = texture;
  11612. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11613. var gl = this._gl;
  11614. if (texture.isCube) {
  11615. if (faceIndex === undefined) {
  11616. faceIndex = 0;
  11617. }
  11618. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11619. }
  11620. if (this._cachedViewport && !forceFullscreenViewport) {
  11621. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11622. }
  11623. else {
  11624. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11625. }
  11626. this.wipeCaches();
  11627. };
  11628. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11629. if (this._currentFramebuffer !== framebuffer) {
  11630. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11631. this._currentFramebuffer = framebuffer;
  11632. }
  11633. };
  11634. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11635. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11636. this._currentRenderTarget = null;
  11637. // If MSAA, we need to bitblt back to main texture
  11638. var gl = this._gl;
  11639. if (texture._MSAAFramebuffer) {
  11640. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11641. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11642. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11643. }
  11644. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11645. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11646. gl.generateMipmap(gl.TEXTURE_2D);
  11647. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11648. }
  11649. if (onBeforeUnbind) {
  11650. if (texture._MSAAFramebuffer) {
  11651. // Bind the correct framebuffer
  11652. this.bindUnboundFramebuffer(texture._framebuffer);
  11653. }
  11654. onBeforeUnbind();
  11655. }
  11656. this.bindUnboundFramebuffer(null);
  11657. };
  11658. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11659. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11660. this._currentRenderTarget = null;
  11661. // If MSAA, we need to bitblt back to main texture
  11662. var gl = this._gl;
  11663. if (textures[0]._MSAAFramebuffer) {
  11664. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11665. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11666. var attachments = textures[0]._attachments;
  11667. if (!attachments) {
  11668. attachments = new Array(textures.length);
  11669. textures[0]._attachments = attachments;
  11670. }
  11671. for (var i = 0; i < textures.length; i++) {
  11672. var texture = textures[i];
  11673. for (var j = 0; j < attachments.length; j++) {
  11674. attachments[j] = gl.NONE;
  11675. }
  11676. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11677. gl.readBuffer(attachments[i]);
  11678. gl.drawBuffers(attachments);
  11679. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11680. }
  11681. for (var i = 0; i < attachments.length; i++) {
  11682. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11683. }
  11684. gl.drawBuffers(attachments);
  11685. }
  11686. for (var i = 0; i < textures.length; i++) {
  11687. var texture = textures[i];
  11688. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11689. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11690. gl.generateMipmap(gl.TEXTURE_2D);
  11691. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11692. }
  11693. }
  11694. if (onBeforeUnbind) {
  11695. if (textures[0]._MSAAFramebuffer) {
  11696. // Bind the correct framebuffer
  11697. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11698. }
  11699. onBeforeUnbind();
  11700. }
  11701. this.bindUnboundFramebuffer(null);
  11702. };
  11703. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11704. if (texture.generateMipMaps) {
  11705. var gl = this._gl;
  11706. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11707. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11708. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11709. }
  11710. };
  11711. Engine.prototype.flushFramebuffer = function () {
  11712. this._gl.flush();
  11713. };
  11714. Engine.prototype.restoreDefaultFramebuffer = function () {
  11715. if (this._currentRenderTarget) {
  11716. this.unBindFramebuffer(this._currentRenderTarget);
  11717. }
  11718. else {
  11719. this.bindUnboundFramebuffer(null);
  11720. }
  11721. if (this._cachedViewport) {
  11722. this.setViewport(this._cachedViewport);
  11723. }
  11724. this.wipeCaches();
  11725. };
  11726. // UBOs
  11727. Engine.prototype.createUniformBuffer = function (elements) {
  11728. var ubo = this._gl.createBuffer();
  11729. if (!ubo) {
  11730. throw new Error("Unable to create uniform buffer");
  11731. }
  11732. this.bindUniformBuffer(ubo);
  11733. if (elements instanceof Float32Array) {
  11734. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11735. }
  11736. else {
  11737. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11738. }
  11739. this.bindUniformBuffer(null);
  11740. ubo.references = 1;
  11741. return ubo;
  11742. };
  11743. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11744. var ubo = this._gl.createBuffer();
  11745. if (!ubo) {
  11746. throw new Error("Unable to create dynamic uniform buffer");
  11747. }
  11748. this.bindUniformBuffer(ubo);
  11749. if (elements instanceof Float32Array) {
  11750. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11751. }
  11752. else {
  11753. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11754. }
  11755. this.bindUniformBuffer(null);
  11756. ubo.references = 1;
  11757. return ubo;
  11758. };
  11759. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11760. this.bindUniformBuffer(uniformBuffer);
  11761. if (offset === undefined) {
  11762. offset = 0;
  11763. }
  11764. if (count === undefined) {
  11765. if (elements instanceof Float32Array) {
  11766. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11767. }
  11768. else {
  11769. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11770. }
  11771. }
  11772. else {
  11773. if (elements instanceof Float32Array) {
  11774. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11775. }
  11776. else {
  11777. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11778. }
  11779. }
  11780. this.bindUniformBuffer(null);
  11781. };
  11782. // VBOs
  11783. Engine.prototype._resetVertexBufferBinding = function () {
  11784. this.bindArrayBuffer(null);
  11785. this._cachedVertexBuffers = null;
  11786. };
  11787. Engine.prototype.createVertexBuffer = function (vertices) {
  11788. var vbo = this._gl.createBuffer();
  11789. if (!vbo) {
  11790. throw new Error("Unable to create vertex buffer");
  11791. }
  11792. this.bindArrayBuffer(vbo);
  11793. if (vertices instanceof Float32Array) {
  11794. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11795. }
  11796. else {
  11797. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11798. }
  11799. this._resetVertexBufferBinding();
  11800. vbo.references = 1;
  11801. return vbo;
  11802. };
  11803. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11804. var vbo = this._gl.createBuffer();
  11805. if (!vbo) {
  11806. throw new Error("Unable to create dynamic vertex buffer");
  11807. }
  11808. this.bindArrayBuffer(vbo);
  11809. if (vertices instanceof Float32Array) {
  11810. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11811. }
  11812. else {
  11813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11814. }
  11815. this._resetVertexBufferBinding();
  11816. vbo.references = 1;
  11817. return vbo;
  11818. };
  11819. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11820. if (offset === void 0) { offset = 0; }
  11821. // Force cache update
  11822. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11823. this.bindIndexBuffer(indexBuffer);
  11824. var arrayBuffer;
  11825. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11826. arrayBuffer = indices;
  11827. }
  11828. else {
  11829. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11830. }
  11831. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11832. this._resetIndexBufferBinding();
  11833. };
  11834. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11835. this.bindArrayBuffer(vertexBuffer);
  11836. if (offset === undefined) {
  11837. offset = 0;
  11838. }
  11839. if (count === undefined) {
  11840. if (vertices instanceof Float32Array) {
  11841. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11842. }
  11843. else {
  11844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11845. }
  11846. }
  11847. else {
  11848. if (vertices instanceof Float32Array) {
  11849. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11850. }
  11851. else {
  11852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11853. }
  11854. }
  11855. this._resetVertexBufferBinding();
  11856. };
  11857. Engine.prototype._resetIndexBufferBinding = function () {
  11858. this.bindIndexBuffer(null);
  11859. this._cachedIndexBuffer = null;
  11860. };
  11861. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11862. var vbo = this._gl.createBuffer();
  11863. if (!vbo) {
  11864. throw new Error("Unable to create index buffer");
  11865. }
  11866. this.bindIndexBuffer(vbo);
  11867. // Check for 32 bits indices
  11868. var arrayBuffer;
  11869. var need32Bits = false;
  11870. if (indices instanceof Uint16Array) {
  11871. arrayBuffer = indices;
  11872. }
  11873. else {
  11874. //check 32 bit support
  11875. if (this._caps.uintIndices) {
  11876. if (indices instanceof Uint32Array) {
  11877. arrayBuffer = indices;
  11878. need32Bits = true;
  11879. }
  11880. else {
  11881. //number[] or Int32Array, check if 32 bit is necessary
  11882. for (var index = 0; index < indices.length; index++) {
  11883. if (indices[index] > 65535) {
  11884. need32Bits = true;
  11885. break;
  11886. }
  11887. }
  11888. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11889. }
  11890. }
  11891. else {
  11892. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11893. arrayBuffer = new Uint16Array(indices);
  11894. }
  11895. }
  11896. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11897. this._resetIndexBufferBinding();
  11898. vbo.references = 1;
  11899. vbo.is32Bits = need32Bits;
  11900. return vbo;
  11901. };
  11902. Engine.prototype.bindArrayBuffer = function (buffer) {
  11903. if (!this._vaoRecordInProgress) {
  11904. this._unbindVertexArrayObject();
  11905. }
  11906. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11907. };
  11908. Engine.prototype.bindUniformBuffer = function (buffer) {
  11909. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11910. };
  11911. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11912. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11913. };
  11914. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11915. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11916. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11917. };
  11918. ;
  11919. Engine.prototype.bindIndexBuffer = function (buffer) {
  11920. if (!this._vaoRecordInProgress) {
  11921. this._unbindVertexArrayObject();
  11922. }
  11923. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11924. };
  11925. Engine.prototype.bindBuffer = function (buffer, target) {
  11926. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11927. this._gl.bindBuffer(target, buffer);
  11928. this._currentBoundBuffer[target] = buffer;
  11929. }
  11930. };
  11931. Engine.prototype.updateArrayBuffer = function (data) {
  11932. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11933. };
  11934. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11935. var pointer = this._currentBufferPointers[indx];
  11936. var changed = false;
  11937. if (!pointer.active) {
  11938. changed = true;
  11939. pointer.active = true;
  11940. pointer.index = indx;
  11941. pointer.size = size;
  11942. pointer.type = type;
  11943. pointer.normalized = normalized;
  11944. pointer.stride = stride;
  11945. pointer.offset = offset;
  11946. pointer.buffer = buffer;
  11947. }
  11948. else {
  11949. if (pointer.buffer !== buffer) {
  11950. pointer.buffer = buffer;
  11951. changed = true;
  11952. }
  11953. if (pointer.size !== size) {
  11954. pointer.size = size;
  11955. changed = true;
  11956. }
  11957. if (pointer.type !== type) {
  11958. pointer.type = type;
  11959. changed = true;
  11960. }
  11961. if (pointer.normalized !== normalized) {
  11962. pointer.normalized = normalized;
  11963. changed = true;
  11964. }
  11965. if (pointer.stride !== stride) {
  11966. pointer.stride = stride;
  11967. changed = true;
  11968. }
  11969. if (pointer.offset !== offset) {
  11970. pointer.offset = offset;
  11971. changed = true;
  11972. }
  11973. }
  11974. if (changed || this._vaoRecordInProgress) {
  11975. this.bindArrayBuffer(buffer);
  11976. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11977. }
  11978. };
  11979. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11980. if (indexBuffer == null) {
  11981. return;
  11982. }
  11983. if (this._cachedIndexBuffer !== indexBuffer) {
  11984. this._cachedIndexBuffer = indexBuffer;
  11985. this.bindIndexBuffer(indexBuffer);
  11986. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11987. }
  11988. };
  11989. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11990. var attributes = effect.getAttributesNames();
  11991. if (!this._vaoRecordInProgress) {
  11992. this._unbindVertexArrayObject();
  11993. }
  11994. this.unbindAllAttributes();
  11995. for (var index = 0; index < attributes.length; index++) {
  11996. var order = effect.getAttributeLocation(index);
  11997. if (order >= 0) {
  11998. var vertexBuffer = vertexBuffers[attributes[index]];
  11999. if (!vertexBuffer) {
  12000. continue;
  12001. }
  12002. this._gl.enableVertexAttribArray(order);
  12003. if (!this._vaoRecordInProgress) {
  12004. this._vertexAttribArraysEnabled[order] = true;
  12005. }
  12006. var buffer = vertexBuffer.getBuffer();
  12007. if (buffer) {
  12008. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12009. if (vertexBuffer.getIsInstanced()) {
  12010. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12011. if (!this._vaoRecordInProgress) {
  12012. this._currentInstanceLocations.push(order);
  12013. this._currentInstanceBuffers.push(buffer);
  12014. }
  12015. }
  12016. }
  12017. }
  12018. }
  12019. };
  12020. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12021. var vao = this._gl.createVertexArray();
  12022. this._vaoRecordInProgress = true;
  12023. this._gl.bindVertexArray(vao);
  12024. this._mustWipeVertexAttributes = true;
  12025. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12026. this.bindIndexBuffer(indexBuffer);
  12027. this._vaoRecordInProgress = false;
  12028. this._gl.bindVertexArray(null);
  12029. return vao;
  12030. };
  12031. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12032. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12033. this._cachedVertexArrayObject = vertexArrayObject;
  12034. this._gl.bindVertexArray(vertexArrayObject);
  12035. this._cachedVertexBuffers = null;
  12036. this._cachedIndexBuffer = null;
  12037. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12038. this._mustWipeVertexAttributes = true;
  12039. }
  12040. };
  12041. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12042. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12043. this._cachedVertexBuffers = vertexBuffer;
  12044. this._cachedEffectForVertexBuffers = effect;
  12045. var attributesCount = effect.getAttributesCount();
  12046. this._unbindVertexArrayObject();
  12047. this.unbindAllAttributes();
  12048. var offset = 0;
  12049. for (var index = 0; index < attributesCount; index++) {
  12050. if (index < vertexDeclaration.length) {
  12051. var order = effect.getAttributeLocation(index);
  12052. if (order >= 0) {
  12053. this._gl.enableVertexAttribArray(order);
  12054. this._vertexAttribArraysEnabled[order] = true;
  12055. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12056. }
  12057. offset += vertexDeclaration[index] * 4;
  12058. }
  12059. }
  12060. }
  12061. this._bindIndexBufferWithCache(indexBuffer);
  12062. };
  12063. Engine.prototype._unbindVertexArrayObject = function () {
  12064. if (!this._cachedVertexArrayObject) {
  12065. return;
  12066. }
  12067. this._cachedVertexArrayObject = null;
  12068. this._gl.bindVertexArray(null);
  12069. };
  12070. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12071. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12072. this._cachedVertexBuffers = vertexBuffers;
  12073. this._cachedEffectForVertexBuffers = effect;
  12074. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12075. }
  12076. this._bindIndexBufferWithCache(indexBuffer);
  12077. };
  12078. Engine.prototype.unbindInstanceAttributes = function () {
  12079. var boundBuffer;
  12080. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12081. var instancesBuffer = this._currentInstanceBuffers[i];
  12082. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12083. boundBuffer = instancesBuffer;
  12084. this.bindArrayBuffer(instancesBuffer);
  12085. }
  12086. var offsetLocation = this._currentInstanceLocations[i];
  12087. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12088. }
  12089. this._currentInstanceBuffers.length = 0;
  12090. this._currentInstanceLocations.length = 0;
  12091. };
  12092. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12093. this._gl.deleteVertexArray(vao);
  12094. };
  12095. Engine.prototype._releaseBuffer = function (buffer) {
  12096. buffer.references--;
  12097. if (buffer.references === 0) {
  12098. this._gl.deleteBuffer(buffer);
  12099. return true;
  12100. }
  12101. return false;
  12102. };
  12103. Engine.prototype.createInstancesBuffer = function (capacity) {
  12104. var buffer = this._gl.createBuffer();
  12105. if (!buffer) {
  12106. throw new Error("Unable to create instance buffer");
  12107. }
  12108. buffer.capacity = capacity;
  12109. this.bindArrayBuffer(buffer);
  12110. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12111. return buffer;
  12112. };
  12113. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12114. this._gl.deleteBuffer(buffer);
  12115. };
  12116. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12117. this.bindArrayBuffer(instancesBuffer);
  12118. if (data) {
  12119. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12120. }
  12121. if (offsetLocations[0].index !== undefined) {
  12122. var stride = 0;
  12123. for (var i = 0; i < offsetLocations.length; i++) {
  12124. var ai = offsetLocations[i];
  12125. stride += ai.attributeSize * 4;
  12126. }
  12127. for (var i = 0; i < offsetLocations.length; i++) {
  12128. var ai = offsetLocations[i];
  12129. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12130. this._gl.enableVertexAttribArray(ai.index);
  12131. this._vertexAttribArraysEnabled[ai.index] = true;
  12132. }
  12133. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12134. this._gl.vertexAttribDivisor(ai.index, 1);
  12135. this._currentInstanceLocations.push(ai.index);
  12136. this._currentInstanceBuffers.push(instancesBuffer);
  12137. }
  12138. }
  12139. else {
  12140. for (var index = 0; index < 4; index++) {
  12141. var offsetLocation = offsetLocations[index];
  12142. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12143. this._gl.enableVertexAttribArray(offsetLocation);
  12144. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12145. }
  12146. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12147. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12148. this._currentInstanceLocations.push(offsetLocation);
  12149. this._currentInstanceBuffers.push(instancesBuffer);
  12150. }
  12151. }
  12152. };
  12153. Engine.prototype.applyStates = function () {
  12154. this._depthCullingState.apply(this._gl);
  12155. this._stencilState.apply(this._gl);
  12156. this._alphaState.apply(this._gl);
  12157. };
  12158. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12159. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12160. };
  12161. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12162. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12163. };
  12164. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12165. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12166. };
  12167. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12168. // Apply states
  12169. this.applyStates();
  12170. this._drawCalls.addCount(1, false);
  12171. // Render
  12172. var drawMode = this.DrawMode(fillMode);
  12173. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12174. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12175. if (instancesCount) {
  12176. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12177. }
  12178. else {
  12179. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12180. }
  12181. };
  12182. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12183. // Apply states
  12184. this.applyStates();
  12185. this._drawCalls.addCount(1, false);
  12186. var drawMode = this.DrawMode(fillMode);
  12187. if (instancesCount) {
  12188. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12189. }
  12190. else {
  12191. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12192. }
  12193. };
  12194. Engine.prototype.DrawMode = function (fillMode) {
  12195. switch (fillMode) {
  12196. // Triangle views
  12197. case BABYLON.Material.TriangleFillMode:
  12198. return this._gl.TRIANGLES;
  12199. case BABYLON.Material.PointFillMode:
  12200. return this._gl.POINTS;
  12201. case BABYLON.Material.WireFrameFillMode:
  12202. return this._gl.LINES;
  12203. // Draw modes
  12204. case BABYLON.Material.PointListDrawMode:
  12205. return this._gl.POINTS;
  12206. case BABYLON.Material.LineListDrawMode:
  12207. return this._gl.LINES;
  12208. case BABYLON.Material.LineLoopDrawMode:
  12209. return this._gl.LINE_LOOP;
  12210. case BABYLON.Material.LineStripDrawMode:
  12211. return this._gl.LINE_STRIP;
  12212. case BABYLON.Material.TriangleStripDrawMode:
  12213. return this._gl.TRIANGLE_STRIP;
  12214. case BABYLON.Material.TriangleFanDrawMode:
  12215. return this._gl.TRIANGLE_FAN;
  12216. default:
  12217. return this._gl.TRIANGLES;
  12218. }
  12219. };
  12220. // Shaders
  12221. Engine.prototype._releaseEffect = function (effect) {
  12222. if (this._compiledEffects[effect._key]) {
  12223. delete this._compiledEffects[effect._key];
  12224. this._deleteProgram(effect.getProgram());
  12225. }
  12226. };
  12227. Engine.prototype._deleteProgram = function (program) {
  12228. if (program) {
  12229. program.__SPECTOR_rebuildProgram = null;
  12230. if (program.transformFeedback) {
  12231. this.deleteTransformFeedback(program.transformFeedback);
  12232. program.transformFeedback = null;
  12233. }
  12234. this._gl.deleteProgram(program);
  12235. }
  12236. };
  12237. /**
  12238. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12239. * @param samplers An array of string used to represent textures
  12240. */
  12241. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12242. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12243. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12244. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12245. if (this._compiledEffects[name]) {
  12246. var compiledEffect = this._compiledEffects[name];
  12247. if (onCompiled && compiledEffect.isReady()) {
  12248. onCompiled(compiledEffect);
  12249. }
  12250. return compiledEffect;
  12251. }
  12252. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12253. effect._key = name;
  12254. this._compiledEffects[name] = effect;
  12255. return effect;
  12256. };
  12257. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12258. if (uniformsNames === void 0) { uniformsNames = []; }
  12259. if (samplers === void 0) { samplers = []; }
  12260. if (defines === void 0) { defines = ""; }
  12261. return this.createEffect({
  12262. vertex: "particles",
  12263. fragmentElement: fragmentName
  12264. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12265. };
  12266. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12267. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12268. context = context || this._gl;
  12269. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12270. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12271. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12272. };
  12273. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12274. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12275. context = context || this._gl;
  12276. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12277. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12278. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12279. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12280. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12281. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12282. return program;
  12283. };
  12284. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12285. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12286. var shaderProgram = context.createProgram();
  12287. if (!shaderProgram) {
  12288. throw new Error("Unable to create program");
  12289. }
  12290. context.attachShader(shaderProgram, vertexShader);
  12291. context.attachShader(shaderProgram, fragmentShader);
  12292. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12293. var transformFeedback = this.createTransformFeedback();
  12294. this.bindTransformFeedback(transformFeedback);
  12295. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12296. shaderProgram.transformFeedback = transformFeedback;
  12297. }
  12298. context.linkProgram(shaderProgram);
  12299. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12300. this.bindTransformFeedback(null);
  12301. }
  12302. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12303. if (!linked) {
  12304. context.validateProgram(shaderProgram);
  12305. var error = context.getProgramInfoLog(shaderProgram);
  12306. if (error) {
  12307. throw new Error(error);
  12308. }
  12309. }
  12310. context.deleteShader(vertexShader);
  12311. context.deleteShader(fragmentShader);
  12312. return shaderProgram;
  12313. };
  12314. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12315. var results = new Array();
  12316. for (var index = 0; index < uniformsNames.length; index++) {
  12317. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12318. }
  12319. return results;
  12320. };
  12321. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12322. var results = [];
  12323. for (var index = 0; index < attributesNames.length; index++) {
  12324. try {
  12325. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12326. }
  12327. catch (e) {
  12328. results.push(-1);
  12329. }
  12330. }
  12331. return results;
  12332. };
  12333. Engine.prototype.enableEffect = function (effect) {
  12334. if (!effect) {
  12335. return;
  12336. }
  12337. // Use program
  12338. this.bindSamplers(effect);
  12339. this._currentEffect = effect;
  12340. if (effect.onBind) {
  12341. effect.onBind(effect);
  12342. }
  12343. effect.onBindObservable.notifyObservers(effect);
  12344. };
  12345. Engine.prototype.setIntArray = function (uniform, array) {
  12346. if (!uniform)
  12347. return;
  12348. this._gl.uniform1iv(uniform, array);
  12349. };
  12350. Engine.prototype.setIntArray2 = function (uniform, array) {
  12351. if (!uniform || array.length % 2 !== 0)
  12352. return;
  12353. this._gl.uniform2iv(uniform, array);
  12354. };
  12355. Engine.prototype.setIntArray3 = function (uniform, array) {
  12356. if (!uniform || array.length % 3 !== 0)
  12357. return;
  12358. this._gl.uniform3iv(uniform, array);
  12359. };
  12360. Engine.prototype.setIntArray4 = function (uniform, array) {
  12361. if (!uniform || array.length % 4 !== 0)
  12362. return;
  12363. this._gl.uniform4iv(uniform, array);
  12364. };
  12365. Engine.prototype.setFloatArray = function (uniform, array) {
  12366. if (!uniform)
  12367. return;
  12368. this._gl.uniform1fv(uniform, array);
  12369. };
  12370. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12371. if (!uniform || array.length % 2 !== 0)
  12372. return;
  12373. this._gl.uniform2fv(uniform, array);
  12374. };
  12375. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12376. if (!uniform || array.length % 3 !== 0)
  12377. return;
  12378. this._gl.uniform3fv(uniform, array);
  12379. };
  12380. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12381. if (!uniform || array.length % 4 !== 0)
  12382. return;
  12383. this._gl.uniform4fv(uniform, array);
  12384. };
  12385. Engine.prototype.setArray = function (uniform, array) {
  12386. if (!uniform)
  12387. return;
  12388. this._gl.uniform1fv(uniform, array);
  12389. };
  12390. Engine.prototype.setArray2 = function (uniform, array) {
  12391. if (!uniform || array.length % 2 !== 0)
  12392. return;
  12393. this._gl.uniform2fv(uniform, array);
  12394. };
  12395. Engine.prototype.setArray3 = function (uniform, array) {
  12396. if (!uniform || array.length % 3 !== 0)
  12397. return;
  12398. this._gl.uniform3fv(uniform, array);
  12399. };
  12400. Engine.prototype.setArray4 = function (uniform, array) {
  12401. if (!uniform || array.length % 4 !== 0)
  12402. return;
  12403. this._gl.uniform4fv(uniform, array);
  12404. };
  12405. Engine.prototype.setMatrices = function (uniform, matrices) {
  12406. if (!uniform)
  12407. return;
  12408. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12409. };
  12410. Engine.prototype.setMatrix = function (uniform, matrix) {
  12411. if (!uniform)
  12412. return;
  12413. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12414. };
  12415. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12416. if (!uniform)
  12417. return;
  12418. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12419. };
  12420. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12421. if (!uniform)
  12422. return;
  12423. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12424. };
  12425. Engine.prototype.setInt = function (uniform, value) {
  12426. if (!uniform)
  12427. return;
  12428. this._gl.uniform1i(uniform, value);
  12429. };
  12430. Engine.prototype.setFloat = function (uniform, value) {
  12431. if (!uniform)
  12432. return;
  12433. this._gl.uniform1f(uniform, value);
  12434. };
  12435. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12436. if (!uniform)
  12437. return;
  12438. this._gl.uniform2f(uniform, x, y);
  12439. };
  12440. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12441. if (!uniform)
  12442. return;
  12443. this._gl.uniform3f(uniform, x, y, z);
  12444. };
  12445. Engine.prototype.setBool = function (uniform, bool) {
  12446. if (!uniform)
  12447. return;
  12448. this._gl.uniform1i(uniform, bool);
  12449. };
  12450. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12451. if (!uniform)
  12452. return;
  12453. this._gl.uniform4f(uniform, x, y, z, w);
  12454. };
  12455. Engine.prototype.setColor3 = function (uniform, color3) {
  12456. if (!uniform)
  12457. return;
  12458. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12459. };
  12460. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12461. if (!uniform)
  12462. return;
  12463. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12464. };
  12465. // States
  12466. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12467. if (zOffset === void 0) { zOffset = 0; }
  12468. if (reverseSide === void 0) { reverseSide = false; }
  12469. // Culling
  12470. if (this._depthCullingState.cull !== culling || force) {
  12471. this._depthCullingState.cull = culling;
  12472. }
  12473. // Cull face
  12474. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12475. if (this._depthCullingState.cullFace !== cullFace || force) {
  12476. this._depthCullingState.cullFace = cullFace;
  12477. }
  12478. // Z offset
  12479. this.setZOffset(zOffset);
  12480. // Front face
  12481. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12482. if (this._depthCullingState.frontFace !== frontFace || force) {
  12483. this._depthCullingState.frontFace = frontFace;
  12484. }
  12485. };
  12486. Engine.prototype.setZOffset = function (value) {
  12487. this._depthCullingState.zOffset = value;
  12488. };
  12489. Engine.prototype.getZOffset = function () {
  12490. return this._depthCullingState.zOffset;
  12491. };
  12492. Engine.prototype.setDepthBuffer = function (enable) {
  12493. this._depthCullingState.depthTest = enable;
  12494. };
  12495. Engine.prototype.getDepthWrite = function () {
  12496. return this._depthCullingState.depthMask;
  12497. };
  12498. Engine.prototype.setDepthWrite = function (enable) {
  12499. this._depthCullingState.depthMask = enable;
  12500. };
  12501. Engine.prototype.setColorWrite = function (enable) {
  12502. this._gl.colorMask(enable, enable, enable, enable);
  12503. this._colorWrite = enable;
  12504. };
  12505. Engine.prototype.getColorWrite = function () {
  12506. return this._colorWrite;
  12507. };
  12508. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12509. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12510. };
  12511. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12512. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12513. if (this._alphaMode === mode) {
  12514. return;
  12515. }
  12516. switch (mode) {
  12517. case Engine.ALPHA_DISABLE:
  12518. this._alphaState.alphaBlend = false;
  12519. break;
  12520. case Engine.ALPHA_PREMULTIPLIED:
  12521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12522. this._alphaState.alphaBlend = true;
  12523. break;
  12524. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12526. this._alphaState.alphaBlend = true;
  12527. break;
  12528. case Engine.ALPHA_COMBINE:
  12529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12530. this._alphaState.alphaBlend = true;
  12531. break;
  12532. case Engine.ALPHA_ONEONE:
  12533. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12534. this._alphaState.alphaBlend = true;
  12535. break;
  12536. case Engine.ALPHA_ADD:
  12537. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12538. this._alphaState.alphaBlend = true;
  12539. break;
  12540. case Engine.ALPHA_SUBTRACT:
  12541. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12542. this._alphaState.alphaBlend = true;
  12543. break;
  12544. case Engine.ALPHA_MULTIPLY:
  12545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12546. this._alphaState.alphaBlend = true;
  12547. break;
  12548. case Engine.ALPHA_MAXIMIZED:
  12549. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12550. this._alphaState.alphaBlend = true;
  12551. break;
  12552. case Engine.ALPHA_INTERPOLATE:
  12553. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12554. this._alphaState.alphaBlend = true;
  12555. break;
  12556. case Engine.ALPHA_SCREENMODE:
  12557. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12558. this._alphaState.alphaBlend = true;
  12559. break;
  12560. }
  12561. if (!noDepthWriteChange) {
  12562. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12563. }
  12564. this._alphaMode = mode;
  12565. };
  12566. Engine.prototype.getAlphaMode = function () {
  12567. return this._alphaMode;
  12568. };
  12569. // Textures
  12570. Engine.prototype.wipeCaches = function (bruteForce) {
  12571. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12572. return;
  12573. }
  12574. this._currentEffect = null;
  12575. // 6/8/2017: deltakosh: Should not be required anymore.
  12576. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12577. if (bruteForce) {
  12578. this.resetTextureCache();
  12579. this._currentProgram = null;
  12580. this._stencilState.reset();
  12581. this._depthCullingState.reset();
  12582. this.setDepthFunctionToLessOrEqual();
  12583. this._alphaState.reset();
  12584. }
  12585. this._resetVertexBufferBinding();
  12586. this._cachedIndexBuffer = null;
  12587. this._cachedEffectForVertexBuffers = null;
  12588. this._unbindVertexArrayObject();
  12589. this.bindIndexBuffer(null);
  12590. };
  12591. /**
  12592. * Set the compressed texture format to use, based on the formats you have, and the formats
  12593. * supported by the hardware / browser.
  12594. *
  12595. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12596. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12597. * to API arguments needed to compressed textures. This puts the burden on the container
  12598. * generator to house the arcane code for determining these for current & future formats.
  12599. *
  12600. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12601. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12602. *
  12603. * Note: The result of this call is not taken into account when a texture is base64.
  12604. *
  12605. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12606. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12607. *
  12608. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12609. * @returns The extension selected.
  12610. */
  12611. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12612. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12613. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12614. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12615. return this._textureFormatInUse = this._texturesSupported[i];
  12616. }
  12617. }
  12618. }
  12619. // actively set format to nothing, to allow this to be called more than once
  12620. // and possibly fail the 2nd time
  12621. this._textureFormatInUse = null;
  12622. return null;
  12623. };
  12624. Engine.prototype._createTexture = function () {
  12625. var texture = this._gl.createTexture();
  12626. if (!texture) {
  12627. throw new Error("Unable to create texture");
  12628. }
  12629. return texture;
  12630. };
  12631. /**
  12632. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12633. * @param {string} urlArg- This contains one of the following:
  12634. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12635. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12636. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12637. *
  12638. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12639. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12640. * @param {Scene} scene- Needed for loading to the correct scene.
  12641. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12642. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12643. * @param {callback} onError- Optional callback to be called upon failure.
  12644. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12645. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12646. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12647. *
  12648. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12649. */
  12650. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12651. var _this = this;
  12652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12653. if (onLoad === void 0) { onLoad = null; }
  12654. if (onError === void 0) { onError = null; }
  12655. if (buffer === void 0) { buffer = null; }
  12656. if (fallBack === void 0) { fallBack = null; }
  12657. if (format === void 0) { format = null; }
  12658. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12659. var fromData = url.substr(0, 5) === "data:";
  12660. var fromBlob = url.substr(0, 5) === "blob:";
  12661. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12662. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12663. // establish the file extension, if possible
  12664. var lastDot = url.lastIndexOf('.');
  12665. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12666. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12667. var isTGA = (extension.indexOf(".tga") === 0);
  12668. // determine if a ktx file should be substituted
  12669. var isKTX = false;
  12670. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12671. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12672. isKTX = true;
  12673. }
  12674. if (scene) {
  12675. scene._addPendingData(texture);
  12676. }
  12677. texture.url = url;
  12678. texture.generateMipMaps = !noMipmap;
  12679. texture.samplingMode = samplingMode;
  12680. texture.invertY = invertY;
  12681. if (!this._doNotHandleContextLost) {
  12682. // Keep a link to the buffer only if we plan to handle context lost
  12683. texture._buffer = buffer;
  12684. }
  12685. var onLoadObserver = null;
  12686. if (onLoad && !fallBack) {
  12687. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12688. }
  12689. if (!fallBack)
  12690. this._internalTexturesCache.push(texture);
  12691. var onerror = function (message, exception) {
  12692. if (scene) {
  12693. scene._removePendingData(texture);
  12694. }
  12695. if (onLoadObserver) {
  12696. texture.onLoadedObservable.remove(onLoadObserver);
  12697. }
  12698. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12699. if (isKTX) {
  12700. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12701. }
  12702. else if (BABYLON.Tools.UseFallbackTexture) {
  12703. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12704. }
  12705. if (onError) {
  12706. onError(message || "Unknown error", exception);
  12707. }
  12708. };
  12709. var callback = null;
  12710. // processing for non-image formats
  12711. if (isKTX || isTGA || isDDS) {
  12712. if (isKTX) {
  12713. callback = function (data) {
  12714. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12715. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12716. ktx.uploadLevels(_this._gl, !noMipmap);
  12717. return false;
  12718. }, samplingMode);
  12719. };
  12720. }
  12721. else if (isTGA) {
  12722. callback = function (arrayBuffer) {
  12723. var data = new Uint8Array(arrayBuffer);
  12724. var header = BABYLON.TGATools.GetTGAHeader(data);
  12725. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12726. BABYLON.TGATools.UploadContent(_this._gl, data);
  12727. return false;
  12728. }, samplingMode);
  12729. };
  12730. }
  12731. else if (isDDS) {
  12732. callback = function (data) {
  12733. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12734. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12735. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12736. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12737. return false;
  12738. }, samplingMode);
  12739. };
  12740. }
  12741. if (!buffer) {
  12742. this._loadFile(url, function (data) {
  12743. if (callback) {
  12744. callback(data);
  12745. }
  12746. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12747. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12748. });
  12749. }
  12750. else {
  12751. if (callback) {
  12752. callback(buffer);
  12753. }
  12754. }
  12755. // image format processing
  12756. }
  12757. else {
  12758. var onload = function (img) {
  12759. if (fromBlob && !_this._doNotHandleContextLost) {
  12760. // We need to store the image if we need to rebuild the texture
  12761. // in case of a webgl context lost
  12762. texture._buffer = img;
  12763. }
  12764. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12765. var gl = _this._gl;
  12766. var isPot = (img.width === potWidth && img.height === potHeight);
  12767. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12768. if (isPot) {
  12769. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12770. return false;
  12771. }
  12772. // Using shaders to rescale because canvas.drawImage is lossy
  12773. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12774. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12775. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12780. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12781. _this._releaseTexture(source);
  12782. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12783. continuationCallback();
  12784. });
  12785. return true;
  12786. }, samplingMode);
  12787. };
  12788. if (!fromData || isBase64)
  12789. if (buffer instanceof HTMLImageElement) {
  12790. onload(buffer);
  12791. }
  12792. else {
  12793. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12794. }
  12795. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12796. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12797. else
  12798. onload(buffer);
  12799. }
  12800. return texture;
  12801. };
  12802. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12803. var _this = this;
  12804. var rtt = this.createRenderTargetTexture({
  12805. width: destination.width,
  12806. height: destination.height,
  12807. }, {
  12808. generateMipMaps: false,
  12809. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12810. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12811. generateDepthBuffer: false,
  12812. generateStencilBuffer: false
  12813. });
  12814. if (!this._rescalePostProcess) {
  12815. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12816. }
  12817. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12818. _this._rescalePostProcess.onApply = function (effect) {
  12819. effect._bindTexture("textureSampler", source);
  12820. };
  12821. var hostingScene = scene;
  12822. if (!hostingScene) {
  12823. hostingScene = _this.scenes[_this.scenes.length - 1];
  12824. }
  12825. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12826. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12827. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12828. _this.unBindFramebuffer(rtt);
  12829. _this._releaseTexture(rtt);
  12830. if (onComplete) {
  12831. onComplete();
  12832. }
  12833. });
  12834. };
  12835. Engine.prototype._getInternalFormat = function (format) {
  12836. var internalFormat = this._gl.RGBA;
  12837. switch (format) {
  12838. case Engine.TEXTUREFORMAT_ALPHA:
  12839. internalFormat = this._gl.ALPHA;
  12840. break;
  12841. case Engine.TEXTUREFORMAT_LUMINANCE:
  12842. internalFormat = this._gl.LUMINANCE;
  12843. break;
  12844. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12845. internalFormat = this._gl.LUMINANCE_ALPHA;
  12846. break;
  12847. case Engine.TEXTUREFORMAT_RGB:
  12848. internalFormat = this._gl.RGB;
  12849. break;
  12850. case Engine.TEXTUREFORMAT_RGBA:
  12851. internalFormat = this._gl.RGBA;
  12852. break;
  12853. }
  12854. return internalFormat;
  12855. };
  12856. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12857. if (compression === void 0) { compression = null; }
  12858. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12859. if (!texture) {
  12860. return;
  12861. }
  12862. var internalFormat = this._getInternalFormat(format);
  12863. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12864. var textureType = this._getWebGLTextureType(type);
  12865. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12866. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12867. if (!this._doNotHandleContextLost) {
  12868. texture._bufferView = data;
  12869. texture.format = format;
  12870. texture.type = type;
  12871. texture.invertY = invertY;
  12872. texture._compression = compression;
  12873. }
  12874. if (texture.width % 4 !== 0) {
  12875. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12876. }
  12877. if (compression && data) {
  12878. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12879. }
  12880. else {
  12881. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12882. }
  12883. if (texture.generateMipMaps) {
  12884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12885. }
  12886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12887. // this.resetTextureCache();
  12888. texture.isReady = true;
  12889. };
  12890. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12891. if (compression === void 0) { compression = null; }
  12892. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12893. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12894. texture.baseWidth = width;
  12895. texture.baseHeight = height;
  12896. texture.width = width;
  12897. texture.height = height;
  12898. texture.format = format;
  12899. texture.generateMipMaps = generateMipMaps;
  12900. texture.samplingMode = samplingMode;
  12901. texture.invertY = invertY;
  12902. texture._compression = compression;
  12903. texture.type = type;
  12904. if (!this._doNotHandleContextLost) {
  12905. texture._bufferView = data;
  12906. }
  12907. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12908. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12909. // Filters
  12910. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12913. if (generateMipMaps) {
  12914. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12915. }
  12916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12917. this._internalTexturesCache.push(texture);
  12918. return texture;
  12919. };
  12920. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12921. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12922. texture.baseWidth = width;
  12923. texture.baseHeight = height;
  12924. if (generateMipMaps) {
  12925. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12926. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12927. }
  12928. // this.resetTextureCache();
  12929. texture.width = width;
  12930. texture.height = height;
  12931. texture.isReady = false;
  12932. texture.generateMipMaps = generateMipMaps;
  12933. texture.samplingMode = samplingMode;
  12934. this.updateTextureSamplingMode(samplingMode, texture);
  12935. this._internalTexturesCache.push(texture);
  12936. return texture;
  12937. };
  12938. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12939. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12940. if (texture.isCube) {
  12941. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12942. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12943. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12945. }
  12946. else if (texture.is3D) {
  12947. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12948. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12949. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12950. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12951. }
  12952. else {
  12953. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12954. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12956. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12957. }
  12958. texture.samplingMode = samplingMode;
  12959. };
  12960. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12961. if (premulAlpha === void 0) { premulAlpha = false; }
  12962. if (!texture) {
  12963. return;
  12964. }
  12965. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12966. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12967. if (premulAlpha) {
  12968. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12969. }
  12970. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12971. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12972. if (texture.generateMipMaps) {
  12973. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12974. }
  12975. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12976. if (premulAlpha) {
  12977. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12978. }
  12979. texture.isReady = true;
  12980. };
  12981. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12982. if (!texture || texture._isDisabled) {
  12983. return;
  12984. }
  12985. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12986. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12987. try {
  12988. // Testing video texture support
  12989. if (this._videoTextureSupported === undefined) {
  12990. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12991. if (this._gl.getError() !== 0) {
  12992. this._videoTextureSupported = false;
  12993. }
  12994. else {
  12995. this._videoTextureSupported = true;
  12996. }
  12997. }
  12998. // Copy video through the current working canvas if video texture is not supported
  12999. if (!this._videoTextureSupported) {
  13000. if (!texture._workingCanvas) {
  13001. texture._workingCanvas = document.createElement("canvas");
  13002. var context = texture._workingCanvas.getContext("2d");
  13003. if (!context) {
  13004. throw new Error("Unable to get 2d context");
  13005. }
  13006. texture._workingContext = context;
  13007. texture._workingCanvas.width = texture.width;
  13008. texture._workingCanvas.height = texture.height;
  13009. }
  13010. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13011. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13012. }
  13013. else {
  13014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13015. }
  13016. if (texture.generateMipMaps) {
  13017. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13018. }
  13019. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13020. // this.resetTextureCache();
  13021. texture.isReady = true;
  13022. }
  13023. catch (ex) {
  13024. // Something unexpected
  13025. // Let's disable the texture
  13026. texture._isDisabled = true;
  13027. }
  13028. };
  13029. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13030. var fullOptions = new RenderTargetCreationOptions();
  13031. if (options !== undefined && typeof options === "object") {
  13032. fullOptions.generateMipMaps = options.generateMipMaps;
  13033. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13034. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13035. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13036. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13037. }
  13038. else {
  13039. fullOptions.generateMipMaps = options;
  13040. fullOptions.generateDepthBuffer = true;
  13041. fullOptions.generateStencilBuffer = false;
  13042. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13043. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13044. }
  13045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13046. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13047. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13048. }
  13049. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13050. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13051. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13052. }
  13053. var gl = this._gl;
  13054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13055. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13056. var width = size.width || size;
  13057. var height = size.height || size;
  13058. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13060. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13061. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13062. }
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13067. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13068. // Create the framebuffer
  13069. var framebuffer = gl.createFramebuffer();
  13070. this.bindUnboundFramebuffer(framebuffer);
  13071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13073. if (fullOptions.generateMipMaps) {
  13074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13075. }
  13076. // Unbind
  13077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13079. this.bindUnboundFramebuffer(null);
  13080. texture._framebuffer = framebuffer;
  13081. texture.baseWidth = width;
  13082. texture.baseHeight = height;
  13083. texture.width = width;
  13084. texture.height = height;
  13085. texture.isReady = true;
  13086. texture.samples = 1;
  13087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13088. texture.samplingMode = fullOptions.samplingMode;
  13089. texture.type = fullOptions.type;
  13090. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13091. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13092. // this.resetTextureCache();
  13093. this._internalTexturesCache.push(texture);
  13094. return texture;
  13095. };
  13096. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13097. var generateMipMaps = false;
  13098. var generateDepthBuffer = true;
  13099. var generateStencilBuffer = false;
  13100. var generateDepthTexture = false;
  13101. var textureCount = 1;
  13102. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13103. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13104. var types = [], samplingModes = [];
  13105. if (options !== undefined) {
  13106. generateMipMaps = options.generateMipMaps;
  13107. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13108. generateStencilBuffer = options.generateStencilBuffer;
  13109. generateDepthTexture = options.generateDepthTexture;
  13110. textureCount = options.textureCount || 1;
  13111. if (options.types) {
  13112. types = options.types;
  13113. }
  13114. if (options.samplingModes) {
  13115. samplingModes = options.samplingModes;
  13116. }
  13117. }
  13118. var gl = this._gl;
  13119. // Create the framebuffer
  13120. var framebuffer = gl.createFramebuffer();
  13121. this.bindUnboundFramebuffer(framebuffer);
  13122. var width = size.width || size;
  13123. var height = size.height || size;
  13124. var textures = [];
  13125. var attachments = [];
  13126. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13127. for (var i = 0; i < textureCount; i++) {
  13128. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13129. var type = types[i] || defaultType;
  13130. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13131. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13132. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13133. }
  13134. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13135. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13136. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13137. }
  13138. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13139. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13140. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13141. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13142. }
  13143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13144. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13145. textures.push(texture);
  13146. attachments.push(attachment);
  13147. gl.activeTexture(gl["TEXTURE" + i]);
  13148. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13153. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13154. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13155. if (generateMipMaps) {
  13156. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13157. }
  13158. // Unbind
  13159. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13160. texture._framebuffer = framebuffer;
  13161. texture._depthStencilBuffer = depthStencilBuffer;
  13162. texture.baseWidth = width;
  13163. texture.baseHeight = height;
  13164. texture.width = width;
  13165. texture.height = height;
  13166. texture.isReady = true;
  13167. texture.samples = 1;
  13168. texture.generateMipMaps = generateMipMaps;
  13169. texture.samplingMode = samplingMode;
  13170. texture.type = type;
  13171. texture._generateDepthBuffer = generateDepthBuffer;
  13172. texture._generateStencilBuffer = generateStencilBuffer;
  13173. texture._attachments = attachments;
  13174. this._internalTexturesCache.push(texture);
  13175. }
  13176. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13177. // Depth texture
  13178. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13179. gl.activeTexture(gl.TEXTURE0);
  13180. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13185. 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);
  13186. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13187. depthTexture._framebuffer = framebuffer;
  13188. depthTexture.baseWidth = width;
  13189. depthTexture.baseHeight = height;
  13190. depthTexture.width = width;
  13191. depthTexture.height = height;
  13192. depthTexture.isReady = true;
  13193. depthTexture.samples = 1;
  13194. depthTexture.generateMipMaps = generateMipMaps;
  13195. depthTexture.samplingMode = gl.NEAREST;
  13196. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13197. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13198. textures.push(depthTexture);
  13199. this._internalTexturesCache.push(depthTexture);
  13200. }
  13201. gl.drawBuffers(attachments);
  13202. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13203. this.bindUnboundFramebuffer(null);
  13204. this.resetTextureCache();
  13205. return textures;
  13206. };
  13207. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13208. if (samples === void 0) { samples = 1; }
  13209. var depthStencilBuffer = null;
  13210. var gl = this._gl;
  13211. // Create the depth/stencil buffer
  13212. if (generateStencilBuffer) {
  13213. depthStencilBuffer = gl.createRenderbuffer();
  13214. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13215. if (samples > 1) {
  13216. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13217. }
  13218. else {
  13219. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13220. }
  13221. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13222. }
  13223. else if (generateDepthBuffer) {
  13224. depthStencilBuffer = gl.createRenderbuffer();
  13225. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13226. if (samples > 1) {
  13227. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13228. }
  13229. else {
  13230. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13231. }
  13232. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13233. }
  13234. return depthStencilBuffer;
  13235. };
  13236. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13237. if (this.webGLVersion < 2 || !texture) {
  13238. return 1;
  13239. }
  13240. if (texture.samples === samples) {
  13241. return samples;
  13242. }
  13243. var gl = this._gl;
  13244. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13245. // Dispose previous render buffers
  13246. if (texture._depthStencilBuffer) {
  13247. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13248. texture._depthStencilBuffer = null;
  13249. }
  13250. if (texture._MSAAFramebuffer) {
  13251. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13252. texture._MSAAFramebuffer = null;
  13253. }
  13254. if (texture._MSAARenderBuffer) {
  13255. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13256. texture._MSAARenderBuffer = null;
  13257. }
  13258. if (samples > 1) {
  13259. var framebuffer = gl.createFramebuffer();
  13260. if (!framebuffer) {
  13261. throw new Error("Unable to create multi sampled framebuffer");
  13262. }
  13263. texture._MSAAFramebuffer = framebuffer;
  13264. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13265. var colorRenderbuffer = gl.createRenderbuffer();
  13266. if (!colorRenderbuffer) {
  13267. throw new Error("Unable to create multi sampled framebuffer");
  13268. }
  13269. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13270. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13271. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13272. texture._MSAARenderBuffer = colorRenderbuffer;
  13273. }
  13274. else {
  13275. this.bindUnboundFramebuffer(texture._framebuffer);
  13276. }
  13277. texture.samples = samples;
  13278. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13279. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13280. this.bindUnboundFramebuffer(null);
  13281. return samples;
  13282. };
  13283. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13284. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13285. return 1;
  13286. }
  13287. if (textures[0].samples === samples) {
  13288. return samples;
  13289. }
  13290. var gl = this._gl;
  13291. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13292. // Dispose previous render buffers
  13293. if (textures[0]._depthStencilBuffer) {
  13294. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13295. textures[0]._depthStencilBuffer = null;
  13296. }
  13297. if (textures[0]._MSAAFramebuffer) {
  13298. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13299. textures[0]._MSAAFramebuffer = null;
  13300. }
  13301. for (var i = 0; i < textures.length; i++) {
  13302. if (textures[i]._MSAARenderBuffer) {
  13303. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13304. textures[i]._MSAARenderBuffer = null;
  13305. }
  13306. }
  13307. if (samples > 1) {
  13308. var framebuffer = gl.createFramebuffer();
  13309. if (!framebuffer) {
  13310. throw new Error("Unable to create multi sampled framebuffer");
  13311. }
  13312. this.bindUnboundFramebuffer(framebuffer);
  13313. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13314. var attachments = [];
  13315. for (var i = 0; i < textures.length; i++) {
  13316. var texture = textures[i];
  13317. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13318. var colorRenderbuffer = gl.createRenderbuffer();
  13319. if (!colorRenderbuffer) {
  13320. throw new Error("Unable to create multi sampled framebuffer");
  13321. }
  13322. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13323. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13324. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13325. texture._MSAAFramebuffer = framebuffer;
  13326. texture._MSAARenderBuffer = colorRenderbuffer;
  13327. texture.samples = samples;
  13328. texture._depthStencilBuffer = depthStencilBuffer;
  13329. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13330. attachments.push(attachment);
  13331. }
  13332. gl.drawBuffers(attachments);
  13333. }
  13334. else {
  13335. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13336. }
  13337. this.bindUnboundFramebuffer(null);
  13338. return samples;
  13339. };
  13340. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13341. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13342. };
  13343. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13344. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13345. };
  13346. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13347. var gl = this._gl;
  13348. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13349. var generateMipMaps = true;
  13350. var generateDepthBuffer = true;
  13351. var generateStencilBuffer = false;
  13352. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13353. if (options !== undefined) {
  13354. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13355. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13356. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13357. if (options.samplingMode !== undefined) {
  13358. samplingMode = options.samplingMode;
  13359. }
  13360. }
  13361. texture.isCube = true;
  13362. texture.generateMipMaps = generateMipMaps;
  13363. texture.samples = 1;
  13364. texture.samplingMode = samplingMode;
  13365. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13367. for (var face = 0; face < 6; face++) {
  13368. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13369. }
  13370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13374. // Create the framebuffer
  13375. var framebuffer = gl.createFramebuffer();
  13376. this.bindUnboundFramebuffer(framebuffer);
  13377. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13378. // Mipmaps
  13379. if (texture.generateMipMaps) {
  13380. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13381. }
  13382. // Unbind
  13383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13384. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13385. this.bindUnboundFramebuffer(null);
  13386. texture._framebuffer = framebuffer;
  13387. texture.width = size;
  13388. texture.height = size;
  13389. texture.isReady = true;
  13390. //this.resetTextureCache();
  13391. this._internalTexturesCache.push(texture);
  13392. return texture;
  13393. };
  13394. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13395. var _this = this;
  13396. if (onLoad === void 0) { onLoad = null; }
  13397. if (onError === void 0) { onError = null; }
  13398. if (forcedExtension === void 0) { forcedExtension = null; }
  13399. var callback = function (loadData) {
  13400. if (!loadData) {
  13401. if (onLoad) {
  13402. onLoad(null);
  13403. }
  13404. return;
  13405. }
  13406. var texture = loadData.texture;
  13407. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13408. texture._lodGenerationScale = scale;
  13409. texture._lodGenerationOffset = offset;
  13410. if (_this._caps.textureLOD) {
  13411. // Do not add extra process if texture lod is supported.
  13412. if (onLoad) {
  13413. onLoad(texture);
  13414. }
  13415. return;
  13416. }
  13417. var mipSlices = 3;
  13418. var gl = _this._gl;
  13419. var width = loadData.width;
  13420. if (!width) {
  13421. return;
  13422. }
  13423. var textures = [];
  13424. for (var i = 0; i < mipSlices; i++) {
  13425. //compute LOD from even spacing in smoothness (matching shader calculation)
  13426. var smoothness = i / (mipSlices - 1);
  13427. var roughness = 1 - smoothness;
  13428. var minLODIndex = offset; // roughness = 0
  13429. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13430. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13431. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13432. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13433. glTextureFromLod.isCube = true;
  13434. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13439. if (loadData.isDDS) {
  13440. var info = loadData.info;
  13441. var data = loadData.data;
  13442. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13443. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13444. }
  13445. else {
  13446. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13447. }
  13448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13449. // Wrap in a base texture for easy binding.
  13450. var lodTexture = new BABYLON.BaseTexture(scene);
  13451. lodTexture.isCube = true;
  13452. lodTexture._texture = glTextureFromLod;
  13453. glTextureFromLod.isReady = true;
  13454. textures.push(lodTexture);
  13455. }
  13456. texture._lodTextureHigh = textures[2];
  13457. texture._lodTextureMid = textures[1];
  13458. texture._lodTextureLow = textures[0];
  13459. if (onLoad) {
  13460. onLoad(texture);
  13461. }
  13462. };
  13463. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13464. };
  13465. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13466. var _this = this;
  13467. if (onLoad === void 0) { onLoad = null; }
  13468. if (onError === void 0) { onError = null; }
  13469. if (forcedExtension === void 0) { forcedExtension = null; }
  13470. var gl = this._gl;
  13471. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13472. texture.isCube = true;
  13473. texture.url = rootUrl;
  13474. texture.generateMipMaps = !noMipmap;
  13475. if (!this._doNotHandleContextLost) {
  13476. texture._extension = forcedExtension;
  13477. texture._files = files;
  13478. }
  13479. var isKTX = false;
  13480. var isDDS = false;
  13481. var lastDot = rootUrl.lastIndexOf('.');
  13482. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13483. if (this._textureFormatInUse) {
  13484. extension = this._textureFormatInUse;
  13485. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13486. isKTX = true;
  13487. }
  13488. else {
  13489. isDDS = (extension === ".dds");
  13490. }
  13491. var onerror = function (request, exception) {
  13492. if (onError && request) {
  13493. onError(request.status + " " + request.statusText, exception);
  13494. }
  13495. };
  13496. if (isKTX) {
  13497. this._loadFile(rootUrl, function (data) {
  13498. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13499. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13500. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13501. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13502. ktx.uploadLevels(_this._gl, !noMipmap);
  13503. _this.setCubeMapTextureParams(gl, loadMipmap);
  13504. texture.width = ktx.pixelWidth;
  13505. texture.height = ktx.pixelHeight;
  13506. texture.isReady = true;
  13507. }, undefined, undefined, true, onerror);
  13508. }
  13509. else if (isDDS) {
  13510. if (files && files.length === 6) {
  13511. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13512. var info;
  13513. var loadMipmap = false;
  13514. var width = 0;
  13515. for (var index = 0; index < imgs.length; index++) {
  13516. var data = imgs[index];
  13517. info = BABYLON.DDSTools.GetDDSInfo(data);
  13518. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13520. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13521. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13522. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13523. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13524. }
  13525. texture.width = info.width;
  13526. texture.height = info.height;
  13527. texture.type = info.textureType;
  13528. width = info.width;
  13529. }
  13530. _this.setCubeMapTextureParams(gl, loadMipmap);
  13531. texture.isReady = true;
  13532. if (onLoad) {
  13533. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13534. }
  13535. }, files, onError);
  13536. }
  13537. else {
  13538. this._loadFile(rootUrl, function (data) {
  13539. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13540. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13541. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13542. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13543. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13544. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13545. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13546. }
  13547. _this.setCubeMapTextureParams(gl, loadMipmap);
  13548. texture.width = info.width;
  13549. texture.height = info.height;
  13550. texture.isReady = true;
  13551. texture.type = info.textureType;
  13552. if (onLoad) {
  13553. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13554. }
  13555. }, undefined, undefined, true, onerror);
  13556. }
  13557. }
  13558. else {
  13559. if (!files) {
  13560. throw new Error("Cannot load cubemap because files were not defined");
  13561. }
  13562. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13563. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13564. var height = width;
  13565. _this._prepareWorkingCanvas();
  13566. if (!_this._workingCanvas || !_this._workingContext) {
  13567. return;
  13568. }
  13569. _this._workingCanvas.width = width;
  13570. _this._workingCanvas.height = height;
  13571. var faces = [
  13572. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13573. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13574. ];
  13575. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13576. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13577. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13578. for (var index = 0; index < faces.length; index++) {
  13579. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13580. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13581. }
  13582. if (!noMipmap) {
  13583. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13584. }
  13585. _this.setCubeMapTextureParams(gl, !noMipmap);
  13586. texture.width = width;
  13587. texture.height = height;
  13588. texture.isReady = true;
  13589. if (format) {
  13590. texture.format = format;
  13591. }
  13592. texture.onLoadedObservable.notifyObservers(texture);
  13593. texture.onLoadedObservable.clear();
  13594. if (onLoad) {
  13595. onLoad();
  13596. }
  13597. }, files, onError);
  13598. }
  13599. this._internalTexturesCache.push(texture);
  13600. return texture;
  13601. };
  13602. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13608. // this.resetTextureCache();
  13609. };
  13610. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13611. if (compression === void 0) { compression = null; }
  13612. if (level === void 0) { level = 0; }
  13613. texture._bufferViewArray = data;
  13614. texture.format = format;
  13615. texture.type = type;
  13616. texture.invertY = invertY;
  13617. texture._compression = compression;
  13618. var gl = this._gl;
  13619. var textureType = this._getWebGLTextureType(type);
  13620. var internalFormat = this._getInternalFormat(format);
  13621. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13622. var needConversion = false;
  13623. if (internalFormat === gl.RGB) {
  13624. internalFormat = gl.RGBA;
  13625. needConversion = true;
  13626. }
  13627. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13628. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13629. if (texture.width % 4 !== 0) {
  13630. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13631. }
  13632. // Data are known to be in +X +Y +Z -X -Y -Z
  13633. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13634. var faceData = data[faceIndex];
  13635. if (compression) {
  13636. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13637. }
  13638. else {
  13639. if (needConversion) {
  13640. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13641. }
  13642. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13643. }
  13644. }
  13645. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13646. if (isPot && texture.generateMipMaps && level === 0) {
  13647. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13648. }
  13649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13650. // this.resetTextureCache();
  13651. texture.isReady = true;
  13652. };
  13653. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13654. if (compression === void 0) { compression = null; }
  13655. var gl = this._gl;
  13656. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13657. texture.isCube = true;
  13658. texture.generateMipMaps = generateMipMaps;
  13659. texture.format = format;
  13660. texture.type = type;
  13661. if (!this._doNotHandleContextLost) {
  13662. texture._bufferViewArray = data;
  13663. }
  13664. var textureType = this._getWebGLTextureType(type);
  13665. var internalFormat = this._getInternalFormat(format);
  13666. if (internalFormat === gl.RGB) {
  13667. internalFormat = gl.RGBA;
  13668. }
  13669. var width = size;
  13670. var height = width;
  13671. texture.width = width;
  13672. texture.height = height;
  13673. // Double check on POT to generate Mips.
  13674. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13675. if (!isPot) {
  13676. generateMipMaps = false;
  13677. }
  13678. // Upload data if needed. The texture won't be ready until then.
  13679. if (data) {
  13680. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13681. }
  13682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13683. // Filters
  13684. if (data && generateMipMaps) {
  13685. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13686. }
  13687. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13690. }
  13691. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13694. }
  13695. else {
  13696. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13699. }
  13700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13702. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13703. return texture;
  13704. };
  13705. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13706. var _this = this;
  13707. if (onLoad === void 0) { onLoad = null; }
  13708. if (onError === void 0) { onError = null; }
  13709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13710. if (invertY === void 0) { invertY = false; }
  13711. var gl = this._gl;
  13712. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13713. scene._addPendingData(texture);
  13714. texture.url = url;
  13715. this._internalTexturesCache.push(texture);
  13716. var onerror = function (request, exception) {
  13717. scene._removePendingData(texture);
  13718. if (onError && request) {
  13719. onError(request.status + " " + request.statusText, exception);
  13720. }
  13721. };
  13722. var internalCallback = function (data) {
  13723. var width = texture.width;
  13724. var faceDataArrays = callback(data);
  13725. if (!faceDataArrays) {
  13726. return;
  13727. }
  13728. if (mipmmapGenerator) {
  13729. var textureType = _this._getWebGLTextureType(type);
  13730. var internalFormat = _this._getInternalFormat(format);
  13731. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13732. var needConversion = false;
  13733. if (internalFormat === gl.RGB) {
  13734. internalFormat = gl.RGBA;
  13735. needConversion = true;
  13736. }
  13737. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13738. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13739. var mipData = mipmmapGenerator(faceDataArrays);
  13740. for (var level = 0; level < mipData.length; level++) {
  13741. var mipSize = width >> level;
  13742. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13743. var mipFaceData = mipData[level][faceIndex];
  13744. if (needConversion) {
  13745. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13746. }
  13747. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13748. }
  13749. }
  13750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13751. }
  13752. else {
  13753. texture.generateMipMaps = !noMipmap;
  13754. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13755. }
  13756. texture.isReady = true;
  13757. // this.resetTextureCache();
  13758. scene._removePendingData(texture);
  13759. if (onLoad) {
  13760. onLoad();
  13761. }
  13762. };
  13763. this._loadFile(url, function (data) {
  13764. internalCallback(data);
  13765. }, undefined, scene.database, true, onerror);
  13766. return texture;
  13767. };
  13768. ;
  13769. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13770. if (compression === void 0) { compression = null; }
  13771. var internalFormat = this._getInternalFormat(format);
  13772. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13773. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13774. if (!this._doNotHandleContextLost) {
  13775. texture._bufferView = data;
  13776. texture.format = format;
  13777. texture.invertY = invertY;
  13778. texture._compression = compression;
  13779. }
  13780. if (texture.width % 4 !== 0) {
  13781. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13782. }
  13783. if (compression && data) {
  13784. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13785. }
  13786. else {
  13787. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13788. }
  13789. if (texture.generateMipMaps) {
  13790. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13791. }
  13792. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13793. // this.resetTextureCache();
  13794. texture.isReady = true;
  13795. };
  13796. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13797. if (compression === void 0) { compression = null; }
  13798. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13799. texture.baseWidth = width;
  13800. texture.baseHeight = height;
  13801. texture.baseDepth = depth;
  13802. texture.width = width;
  13803. texture.height = height;
  13804. texture.depth = depth;
  13805. texture.format = format;
  13806. texture.generateMipMaps = generateMipMaps;
  13807. texture.samplingMode = samplingMode;
  13808. texture.is3D = true;
  13809. if (!this._doNotHandleContextLost) {
  13810. texture._bufferView = data;
  13811. }
  13812. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13813. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13814. // Filters
  13815. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13817. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13818. if (generateMipMaps) {
  13819. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13820. }
  13821. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13822. this._internalTexturesCache.push(texture);
  13823. return texture;
  13824. };
  13825. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13826. var gl = this._gl;
  13827. if (!gl) {
  13828. return;
  13829. }
  13830. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13833. if (!noMipmap && !isCompressed) {
  13834. gl.generateMipmap(gl.TEXTURE_2D);
  13835. }
  13836. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13837. // this.resetTextureCache();
  13838. if (scene) {
  13839. scene._removePendingData(texture);
  13840. }
  13841. texture.onLoadedObservable.notifyObservers(texture);
  13842. texture.onLoadedObservable.clear();
  13843. };
  13844. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13845. var _this = this;
  13846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13847. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13848. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13849. var gl = this._gl;
  13850. if (!gl) {
  13851. return;
  13852. }
  13853. if (!texture._webGLTexture) {
  13854. // this.resetTextureCache();
  13855. if (scene) {
  13856. scene._removePendingData(texture);
  13857. }
  13858. return;
  13859. }
  13860. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13861. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13862. texture.baseWidth = width;
  13863. texture.baseHeight = height;
  13864. texture.width = potWidth;
  13865. texture.height = potHeight;
  13866. texture.isReady = true;
  13867. if (processFunction(potWidth, potHeight, function () {
  13868. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13869. })) {
  13870. // Returning as texture needs extra async steps
  13871. return;
  13872. }
  13873. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13874. };
  13875. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13876. // Create new RGBA data container.
  13877. var rgbaData;
  13878. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13879. rgbaData = new Float32Array(width * height * 4);
  13880. }
  13881. else {
  13882. rgbaData = new Uint32Array(width * height * 4);
  13883. }
  13884. // Convert each pixel.
  13885. for (var x = 0; x < width; x++) {
  13886. for (var y = 0; y < height; y++) {
  13887. var index = (y * width + x) * 3;
  13888. var newIndex = (y * width + x) * 4;
  13889. // Map Old Value to new value.
  13890. rgbaData[newIndex + 0] = rgbData[index + 0];
  13891. rgbaData[newIndex + 1] = rgbData[index + 1];
  13892. rgbaData[newIndex + 2] = rgbData[index + 2];
  13893. // Add fully opaque alpha channel.
  13894. rgbaData[newIndex + 3] = 1;
  13895. }
  13896. }
  13897. return rgbaData;
  13898. };
  13899. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13900. var gl = this._gl;
  13901. if (texture._framebuffer) {
  13902. gl.deleteFramebuffer(texture._framebuffer);
  13903. texture._framebuffer = null;
  13904. }
  13905. if (texture._depthStencilBuffer) {
  13906. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13907. texture._depthStencilBuffer = null;
  13908. }
  13909. if (texture._MSAAFramebuffer) {
  13910. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13911. texture._MSAAFramebuffer = null;
  13912. }
  13913. if (texture._MSAARenderBuffer) {
  13914. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13915. texture._MSAARenderBuffer = null;
  13916. }
  13917. };
  13918. Engine.prototype._releaseTexture = function (texture) {
  13919. var gl = this._gl;
  13920. this._releaseFramebufferObjects(texture);
  13921. gl.deleteTexture(texture._webGLTexture);
  13922. // Unbind channels
  13923. this.unbindAllTextures();
  13924. var index = this._internalTexturesCache.indexOf(texture);
  13925. if (index !== -1) {
  13926. this._internalTexturesCache.splice(index, 1);
  13927. }
  13928. // Integrated fixed lod samplers.
  13929. if (texture._lodTextureHigh) {
  13930. texture._lodTextureHigh.dispose();
  13931. }
  13932. if (texture._lodTextureMid) {
  13933. texture._lodTextureMid.dispose();
  13934. }
  13935. if (texture._lodTextureLow) {
  13936. texture._lodTextureLow.dispose();
  13937. }
  13938. };
  13939. Engine.prototype.setProgram = function (program) {
  13940. if (this._currentProgram !== program) {
  13941. this._gl.useProgram(program);
  13942. this._currentProgram = program;
  13943. }
  13944. };
  13945. Engine.prototype.bindSamplers = function (effect) {
  13946. this.setProgram(effect.getProgram());
  13947. var samplers = effect.getSamplers();
  13948. for (var index = 0; index < samplers.length; index++) {
  13949. var uniform = effect.getUniform(samplers[index]);
  13950. if (uniform) {
  13951. this._boundUniforms[index] = uniform;
  13952. }
  13953. }
  13954. this._currentEffect = null;
  13955. };
  13956. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13957. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13958. return;
  13959. }
  13960. // Remove
  13961. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13962. // Bind last to it
  13963. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13964. // Bind to dummy
  13965. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13966. };
  13967. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13968. if (!internalTexture) {
  13969. return -1;
  13970. }
  13971. internalTexture._initialSlot = channel;
  13972. if (this.disableTextureBindingOptimization) {
  13973. if (channel !== internalTexture._designatedSlot) {
  13974. this._textureCollisions.addCount(1, false);
  13975. }
  13976. }
  13977. else {
  13978. if (channel !== internalTexture._designatedSlot) {
  13979. if (internalTexture._designatedSlot > -1) {
  13980. return internalTexture._designatedSlot;
  13981. }
  13982. else {
  13983. // No slot for this texture, let's pick a new one (if we find a free slot)
  13984. if (this._nextFreeTextureSlots.length) {
  13985. return this._nextFreeTextureSlots[0];
  13986. }
  13987. // We need to recycle the oldest bound texture, sorry.
  13988. this._textureCollisions.addCount(1, false);
  13989. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13990. }
  13991. }
  13992. }
  13993. return channel;
  13994. };
  13995. Engine.prototype._linkTrackers = function (previous, next) {
  13996. previous.next = next;
  13997. next.previous = previous;
  13998. };
  13999. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14000. var currentSlot = internalTexture._designatedSlot;
  14001. if (currentSlot === -1) {
  14002. return -1;
  14003. }
  14004. internalTexture._designatedSlot = -1;
  14005. if (this.disableTextureBindingOptimization) {
  14006. return -1;
  14007. }
  14008. // Remove from bound list
  14009. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14010. // Free the slot
  14011. this._boundTexturesCache[currentSlot] = null;
  14012. this._nextFreeTextureSlots.push(currentSlot);
  14013. return currentSlot;
  14014. };
  14015. Engine.prototype._activateCurrentTexture = function () {
  14016. if (this._currentTextureChannel !== this._activeChannel) {
  14017. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14018. this._currentTextureChannel = this._activeChannel;
  14019. }
  14020. };
  14021. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14022. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14023. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14024. this._activeChannel = texture._designatedSlot;
  14025. }
  14026. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14027. var isTextureForRendering = texture && texture._initialSlot > -1;
  14028. if (currentTextureBound !== texture) {
  14029. if (currentTextureBound) {
  14030. this._removeDesignatedSlot(currentTextureBound);
  14031. }
  14032. this._activateCurrentTexture();
  14033. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14034. this._boundTexturesCache[this._activeChannel] = texture;
  14035. if (texture) {
  14036. if (!this.disableTextureBindingOptimization) {
  14037. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14038. if (slotIndex > -1) {
  14039. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14040. }
  14041. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14042. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14043. }
  14044. texture._designatedSlot = this._activeChannel;
  14045. }
  14046. }
  14047. else if (forTextureDataUpdate) {
  14048. this._activateCurrentTexture();
  14049. }
  14050. if (isTextureForRendering && !forTextureDataUpdate) {
  14051. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14052. }
  14053. };
  14054. Engine.prototype._bindTexture = function (channel, texture) {
  14055. if (channel < 0) {
  14056. return;
  14057. }
  14058. if (texture) {
  14059. channel = this._getCorrectTextureChannel(channel, texture);
  14060. }
  14061. this._activeChannel = channel;
  14062. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14063. };
  14064. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14065. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14066. };
  14067. Engine.prototype.unbindAllTextures = function () {
  14068. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14069. this._activeChannel = channel;
  14070. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14071. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14072. if (this.webGLVersion > 1) {
  14073. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14074. }
  14075. }
  14076. };
  14077. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14078. if (channel < 0) {
  14079. return;
  14080. }
  14081. if (uniform) {
  14082. this._boundUniforms[channel] = uniform;
  14083. }
  14084. this._setTexture(channel, texture);
  14085. };
  14086. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14087. var uniform = this._boundUniforms[sourceSlot];
  14088. if (uniform._currentState === destination) {
  14089. return;
  14090. }
  14091. this._gl.uniform1i(uniform, destination);
  14092. uniform._currentState = destination;
  14093. };
  14094. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14095. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14096. // Not ready?
  14097. if (!texture) {
  14098. if (this._boundTexturesCache[channel] != null) {
  14099. this._activeChannel = channel;
  14100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14101. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14102. if (this.webGLVersion > 1) {
  14103. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14104. }
  14105. }
  14106. return false;
  14107. }
  14108. // Video
  14109. if (texture.video) {
  14110. this._activeChannel = channel;
  14111. texture.update();
  14112. }
  14113. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14114. texture.delayLoad();
  14115. return false;
  14116. }
  14117. var internalTexture;
  14118. if (texture.isReady()) {
  14119. internalTexture = texture.getInternalTexture();
  14120. }
  14121. else if (texture.isCube) {
  14122. internalTexture = this.emptyCubeTexture;
  14123. }
  14124. else if (texture.is3D) {
  14125. internalTexture = this.emptyTexture3D;
  14126. }
  14127. else {
  14128. internalTexture = this.emptyTexture;
  14129. }
  14130. if (!isPartOfTextureArray) {
  14131. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14132. }
  14133. if (this._boundTexturesCache[channel] === internalTexture) {
  14134. this._moveBoundTextureOnTop(internalTexture);
  14135. if (!isPartOfTextureArray) {
  14136. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14137. }
  14138. return false;
  14139. }
  14140. this._activeChannel = channel;
  14141. if (internalTexture && internalTexture.is3D) {
  14142. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14143. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14144. internalTexture._cachedWrapU = texture.wrapU;
  14145. switch (texture.wrapU) {
  14146. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14147. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14148. break;
  14149. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14150. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14151. break;
  14152. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14154. break;
  14155. }
  14156. }
  14157. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14158. internalTexture._cachedWrapV = texture.wrapV;
  14159. switch (texture.wrapV) {
  14160. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14161. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14162. break;
  14163. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14165. break;
  14166. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14168. break;
  14169. }
  14170. }
  14171. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14172. internalTexture._cachedWrapR = texture.wrapR;
  14173. switch (texture.wrapR) {
  14174. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14175. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14176. break;
  14177. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14179. break;
  14180. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14181. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14182. break;
  14183. }
  14184. }
  14185. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14186. }
  14187. else if (internalTexture && internalTexture.isCube) {
  14188. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14189. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14190. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14191. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14192. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14193. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14194. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14195. }
  14196. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14197. }
  14198. else {
  14199. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14200. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14201. internalTexture._cachedWrapU = texture.wrapU;
  14202. switch (texture.wrapU) {
  14203. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14205. break;
  14206. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14208. break;
  14209. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14211. break;
  14212. }
  14213. }
  14214. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14215. internalTexture._cachedWrapV = texture.wrapV;
  14216. switch (texture.wrapV) {
  14217. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14218. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14219. break;
  14220. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14221. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14222. break;
  14223. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14224. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14225. break;
  14226. }
  14227. }
  14228. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14229. }
  14230. return true;
  14231. };
  14232. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14233. if (channel < 0 || !uniform) {
  14234. return;
  14235. }
  14236. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14237. this._textureUnits = new Int32Array(textures.length);
  14238. }
  14239. for (var i = 0; i < textures.length; i++) {
  14240. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14241. }
  14242. this._gl.uniform1iv(uniform, this._textureUnits);
  14243. for (var index = 0; index < textures.length; index++) {
  14244. this._setTexture(this._textureUnits[index], textures[index], true);
  14245. }
  14246. };
  14247. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14248. var internalTexture = texture.getInternalTexture();
  14249. if (!internalTexture) {
  14250. return;
  14251. }
  14252. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14253. var value = texture.anisotropicFilteringLevel;
  14254. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14255. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14256. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14257. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14258. }
  14259. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14260. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14261. internalTexture._cachedAnisotropicFilteringLevel = value;
  14262. }
  14263. };
  14264. Engine.prototype.readPixels = function (x, y, width, height) {
  14265. var data = new Uint8Array(height * width * 4);
  14266. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14267. return data;
  14268. };
  14269. /**
  14270. * Add an externaly attached data from its key.
  14271. * This method call will fail and return false, if such key already exists.
  14272. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14273. * @param key the unique key that identifies the data
  14274. * @param data the data object to associate to the key for this Engine instance
  14275. * @return true if no such key were already present and the data was added successfully, false otherwise
  14276. */
  14277. Engine.prototype.addExternalData = function (key, data) {
  14278. if (!this._externalData) {
  14279. this._externalData = new BABYLON.StringDictionary();
  14280. }
  14281. return this._externalData.add(key, data);
  14282. };
  14283. /**
  14284. * Get an externaly attached data from its key
  14285. * @param key the unique key that identifies the data
  14286. * @return the associated data, if present (can be null), or undefined if not present
  14287. */
  14288. Engine.prototype.getExternalData = function (key) {
  14289. if (!this._externalData) {
  14290. this._externalData = new BABYLON.StringDictionary();
  14291. }
  14292. return this._externalData.get(key);
  14293. };
  14294. /**
  14295. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14296. * @param key the unique key that identifies the data
  14297. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14298. * @return the associated data, can be null if the factory returned null.
  14299. */
  14300. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14301. if (!this._externalData) {
  14302. this._externalData = new BABYLON.StringDictionary();
  14303. }
  14304. return this._externalData.getOrAddWithFactory(key, factory);
  14305. };
  14306. /**
  14307. * Remove an externaly attached data from the Engine instance
  14308. * @param key the unique key that identifies the data
  14309. * @return true if the data was successfully removed, false if it doesn't exist
  14310. */
  14311. Engine.prototype.removeExternalData = function (key) {
  14312. if (!this._externalData) {
  14313. this._externalData = new BABYLON.StringDictionary();
  14314. }
  14315. return this._externalData.remove(key);
  14316. };
  14317. Engine.prototype.unbindAllAttributes = function () {
  14318. if (this._mustWipeVertexAttributes) {
  14319. this._mustWipeVertexAttributes = false;
  14320. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14321. this._gl.disableVertexAttribArray(i);
  14322. this._vertexAttribArraysEnabled[i] = false;
  14323. this._currentBufferPointers[i].active = false;
  14324. }
  14325. return;
  14326. }
  14327. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14328. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14329. continue;
  14330. }
  14331. this._gl.disableVertexAttribArray(i);
  14332. this._vertexAttribArraysEnabled[i] = false;
  14333. this._currentBufferPointers[i].active = false;
  14334. }
  14335. };
  14336. Engine.prototype.releaseEffects = function () {
  14337. for (var name in this._compiledEffects) {
  14338. this._deleteProgram(this._compiledEffects[name]._program);
  14339. }
  14340. this._compiledEffects = {};
  14341. };
  14342. // Dispose
  14343. Engine.prototype.dispose = function () {
  14344. this.hideLoadingUI();
  14345. this.stopRenderLoop();
  14346. // Release postProcesses
  14347. while (this.postProcesses.length) {
  14348. this.postProcesses[0].dispose();
  14349. }
  14350. // Empty texture
  14351. if (this._emptyTexture) {
  14352. this._releaseTexture(this._emptyTexture);
  14353. this._emptyTexture = null;
  14354. }
  14355. if (this._emptyCubeTexture) {
  14356. this._releaseTexture(this._emptyCubeTexture);
  14357. this._emptyCubeTexture = null;
  14358. }
  14359. // Rescale PP
  14360. if (this._rescalePostProcess) {
  14361. this._rescalePostProcess.dispose();
  14362. }
  14363. // Release scenes
  14364. while (this.scenes.length) {
  14365. this.scenes[0].dispose();
  14366. }
  14367. // Release audio engine
  14368. if (Engine.audioEngine) {
  14369. Engine.audioEngine.dispose();
  14370. }
  14371. // Release effects
  14372. this.releaseEffects();
  14373. // Unbind
  14374. this.unbindAllAttributes();
  14375. if (this._dummyFramebuffer) {
  14376. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14377. }
  14378. //WebVR
  14379. this.disableVR();
  14380. // Events
  14381. if (BABYLON.Tools.IsWindowObjectExist()) {
  14382. window.removeEventListener("blur", this._onBlur);
  14383. window.removeEventListener("focus", this._onFocus);
  14384. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14385. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14386. if (this._renderingCanvas) {
  14387. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14388. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14389. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14390. if (!this._doNotHandleContextLost) {
  14391. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14392. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14393. }
  14394. }
  14395. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14396. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14397. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14398. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14399. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14400. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14401. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14402. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14403. if (this._onVrDisplayConnect) {
  14404. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14405. if (this._onVrDisplayDisconnect) {
  14406. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14407. }
  14408. if (this._onVrDisplayPresentChange) {
  14409. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14410. }
  14411. this._onVrDisplayConnect = null;
  14412. this._onVrDisplayDisconnect = null;
  14413. }
  14414. }
  14415. // Remove from Instances
  14416. var index = Engine.Instances.indexOf(this);
  14417. if (index >= 0) {
  14418. Engine.Instances.splice(index, 1);
  14419. }
  14420. this._workingCanvas = null;
  14421. this._workingContext = null;
  14422. this._currentBufferPointers = [];
  14423. this._renderingCanvas = null;
  14424. this._currentProgram = null;
  14425. this.onResizeObservable.clear();
  14426. this.onCanvasBlurObservable.clear();
  14427. this.onCanvasFocusObservable.clear();
  14428. this.onCanvasPointerOutObservable.clear();
  14429. this.onBeginFrameObservable.clear();
  14430. this.onEndFrameObservable.clear();
  14431. BABYLON.Effect.ResetCache();
  14432. // Abort active requests
  14433. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14434. var request = _a[_i];
  14435. request.abort();
  14436. }
  14437. };
  14438. // Loading screen
  14439. Engine.prototype.displayLoadingUI = function () {
  14440. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14441. return;
  14442. }
  14443. var loadingScreen = this.loadingScreen;
  14444. if (loadingScreen) {
  14445. loadingScreen.displayLoadingUI();
  14446. }
  14447. };
  14448. Engine.prototype.hideLoadingUI = function () {
  14449. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14450. return;
  14451. }
  14452. var loadingScreen = this.loadingScreen;
  14453. if (loadingScreen) {
  14454. loadingScreen.hideLoadingUI();
  14455. }
  14456. };
  14457. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14458. get: function () {
  14459. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14460. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14461. return this._loadingScreen;
  14462. },
  14463. set: function (loadingScreen) {
  14464. this._loadingScreen = loadingScreen;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14470. set: function (text) {
  14471. this.loadingScreen.loadingUIText = text;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14477. set: function (color) {
  14478. this.loadingScreen.loadingUIBackgroundColor = color;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Engine.prototype.attachContextLostEvent = function (callback) {
  14484. if (this._renderingCanvas) {
  14485. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14486. }
  14487. };
  14488. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14489. if (this._renderingCanvas) {
  14490. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14491. }
  14492. };
  14493. Engine.prototype.getVertexShaderSource = function (program) {
  14494. var shaders = this._gl.getAttachedShaders(program);
  14495. if (!shaders) {
  14496. return null;
  14497. }
  14498. return this._gl.getShaderSource(shaders[0]);
  14499. };
  14500. Engine.prototype.getFragmentShaderSource = function (program) {
  14501. var shaders = this._gl.getAttachedShaders(program);
  14502. if (!shaders) {
  14503. return null;
  14504. }
  14505. return this._gl.getShaderSource(shaders[1]);
  14506. };
  14507. Engine.prototype.getError = function () {
  14508. return this._gl.getError();
  14509. };
  14510. // FPS
  14511. Engine.prototype.getFps = function () {
  14512. return this._fps;
  14513. };
  14514. Engine.prototype.getDeltaTime = function () {
  14515. return this._deltaTime;
  14516. };
  14517. Engine.prototype._measureFps = function () {
  14518. this._performanceMonitor.sampleFrame();
  14519. this._fps = this._performanceMonitor.averageFPS;
  14520. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14521. };
  14522. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14523. if (faceIndex === void 0) { faceIndex = -1; }
  14524. var gl = this._gl;
  14525. if (!this._dummyFramebuffer) {
  14526. var dummy = gl.createFramebuffer();
  14527. if (!dummy) {
  14528. throw new Error("Unable to create dummy framebuffer");
  14529. }
  14530. this._dummyFramebuffer = dummy;
  14531. }
  14532. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14533. if (faceIndex > -1) {
  14534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14535. }
  14536. else {
  14537. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14538. }
  14539. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14540. var buffer;
  14541. switch (readType) {
  14542. case gl.UNSIGNED_BYTE:
  14543. buffer = new Uint8Array(4 * width * height);
  14544. readType = gl.UNSIGNED_BYTE;
  14545. break;
  14546. default:
  14547. buffer = new Float32Array(4 * width * height);
  14548. readType = gl.FLOAT;
  14549. break;
  14550. }
  14551. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14552. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14553. return buffer;
  14554. };
  14555. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14556. if (this._webGLVersion > 1) {
  14557. return this._caps.colorBufferFloat;
  14558. }
  14559. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14560. };
  14561. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14562. if (this._webGLVersion > 1) {
  14563. return this._caps.colorBufferFloat;
  14564. }
  14565. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14566. };
  14567. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14568. Engine.prototype._canRenderToFramebuffer = function (type) {
  14569. var gl = this._gl;
  14570. //clear existing errors
  14571. while (gl.getError() !== gl.NO_ERROR) { }
  14572. var successful = true;
  14573. var texture = gl.createTexture();
  14574. gl.bindTexture(gl.TEXTURE_2D, texture);
  14575. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14578. var fb = gl.createFramebuffer();
  14579. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14581. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14582. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14583. successful = successful && (gl.getError() === gl.NO_ERROR);
  14584. //try render by clearing frame buffer's color buffer
  14585. if (successful) {
  14586. gl.clear(gl.COLOR_BUFFER_BIT);
  14587. successful = successful && (gl.getError() === gl.NO_ERROR);
  14588. }
  14589. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14590. if (successful) {
  14591. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14592. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14593. var readFormat = gl.RGBA;
  14594. var readType = gl.UNSIGNED_BYTE;
  14595. var buffer = new Uint8Array(4);
  14596. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14597. successful = successful && (gl.getError() === gl.NO_ERROR);
  14598. }
  14599. //clean up
  14600. gl.deleteTexture(texture);
  14601. gl.deleteFramebuffer(fb);
  14602. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14603. //clear accumulated errors
  14604. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14605. return successful;
  14606. };
  14607. Engine.prototype._getWebGLTextureType = function (type) {
  14608. if (type === Engine.TEXTURETYPE_FLOAT) {
  14609. return this._gl.FLOAT;
  14610. }
  14611. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14612. // Add Half Float Constant.
  14613. return this._gl.HALF_FLOAT_OES;
  14614. }
  14615. return this._gl.UNSIGNED_BYTE;
  14616. };
  14617. ;
  14618. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14619. if (this._webGLVersion === 1) {
  14620. return this._gl.RGBA;
  14621. }
  14622. if (type === Engine.TEXTURETYPE_FLOAT) {
  14623. return this._gl.RGBA32F;
  14624. }
  14625. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14626. return this._gl.RGBA16F;
  14627. }
  14628. return this._gl.RGBA;
  14629. };
  14630. ;
  14631. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14632. if (type === Engine.TEXTURETYPE_FLOAT) {
  14633. return this._gl.RGBA32F;
  14634. }
  14635. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14636. return this._gl.RGBA16F;
  14637. }
  14638. return this._gl.RGBA8;
  14639. };
  14640. ;
  14641. Engine.prototype.createQuery = function () {
  14642. return this._gl.createQuery();
  14643. };
  14644. Engine.prototype.deleteQuery = function (query) {
  14645. this._gl.deleteQuery(query);
  14646. return this;
  14647. };
  14648. Engine.prototype.isQueryResultAvailable = function (query) {
  14649. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14650. };
  14651. Engine.prototype.getQueryResult = function (query) {
  14652. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14653. };
  14654. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14655. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14656. this._gl.beginQuery(glAlgorithm, query);
  14657. return this;
  14658. };
  14659. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14660. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14661. this._gl.endQuery(glAlgorithm);
  14662. return this;
  14663. };
  14664. /* Time queries */
  14665. Engine.prototype._createTimeQuery = function () {
  14666. var timerQuery = this._caps.timerQuery;
  14667. if (timerQuery.createQueryEXT) {
  14668. return timerQuery.createQueryEXT();
  14669. }
  14670. return this.createQuery();
  14671. };
  14672. Engine.prototype._deleteTimeQuery = function (query) {
  14673. var timerQuery = this._caps.timerQuery;
  14674. if (timerQuery.deleteQueryEXT) {
  14675. timerQuery.deleteQueryEXT(query);
  14676. return;
  14677. }
  14678. this.deleteQuery(query);
  14679. };
  14680. Engine.prototype._getTimeQueryResult = function (query) {
  14681. var timerQuery = this._caps.timerQuery;
  14682. if (timerQuery.getQueryObjectEXT) {
  14683. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14684. }
  14685. return this.getQueryResult(query);
  14686. };
  14687. Engine.prototype._getTimeQueryAvailability = function (query) {
  14688. var timerQuery = this._caps.timerQuery;
  14689. if (timerQuery.getQueryObjectEXT) {
  14690. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14691. }
  14692. return this.isQueryResultAvailable(query);
  14693. };
  14694. Engine.prototype.startTimeQuery = function () {
  14695. var timerQuery = this._caps.timerQuery;
  14696. if (!timerQuery) {
  14697. return null;
  14698. }
  14699. var token = new BABYLON._TimeToken();
  14700. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14701. if (this._caps.canUseTimestampForTimerQuery) {
  14702. token._startTimeQuery = this._createTimeQuery();
  14703. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14704. }
  14705. else {
  14706. if (this._currentNonTimestampToken) {
  14707. return this._currentNonTimestampToken;
  14708. }
  14709. token._timeElapsedQuery = this._createTimeQuery();
  14710. if (timerQuery.beginQueryEXT) {
  14711. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14712. }
  14713. else {
  14714. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14715. }
  14716. this._currentNonTimestampToken = token;
  14717. }
  14718. return token;
  14719. };
  14720. Engine.prototype.endTimeQuery = function (token) {
  14721. var timerQuery = this._caps.timerQuery;
  14722. if (!timerQuery || !token) {
  14723. return -1;
  14724. }
  14725. if (this._caps.canUseTimestampForTimerQuery) {
  14726. if (!token._startTimeQuery) {
  14727. return -1;
  14728. }
  14729. if (!token._endTimeQuery) {
  14730. token._endTimeQuery = this._createTimeQuery();
  14731. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14732. }
  14733. }
  14734. else if (!token._timeElapsedQueryEnded) {
  14735. if (!token._timeElapsedQuery) {
  14736. return -1;
  14737. }
  14738. if (timerQuery.endQueryEXT) {
  14739. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14740. }
  14741. else {
  14742. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14743. }
  14744. token._timeElapsedQueryEnded = true;
  14745. }
  14746. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14747. var available = false;
  14748. if (token._endTimeQuery) {
  14749. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14750. }
  14751. else if (token._timeElapsedQuery) {
  14752. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14753. }
  14754. if (available && !disjoint) {
  14755. var result = 0;
  14756. if (this._caps.canUseTimestampForTimerQuery) {
  14757. if (!token._startTimeQuery || !token._endTimeQuery) {
  14758. return -1;
  14759. }
  14760. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14761. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14762. result = timeEnd - timeStart;
  14763. this._deleteTimeQuery(token._startTimeQuery);
  14764. this._deleteTimeQuery(token._endTimeQuery);
  14765. token._startTimeQuery = null;
  14766. token._endTimeQuery = null;
  14767. }
  14768. else {
  14769. if (!token._timeElapsedQuery) {
  14770. return -1;
  14771. }
  14772. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14773. this._deleteTimeQuery(token._timeElapsedQuery);
  14774. token._timeElapsedQuery = null;
  14775. token._timeElapsedQueryEnded = false;
  14776. this._currentNonTimestampToken = null;
  14777. }
  14778. return result;
  14779. }
  14780. return -1;
  14781. };
  14782. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14783. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14784. };
  14785. // Transform feedback
  14786. Engine.prototype.createTransformFeedback = function () {
  14787. return this._gl.createTransformFeedback();
  14788. };
  14789. Engine.prototype.deleteTransformFeedback = function (value) {
  14790. this._gl.deleteTransformFeedback(value);
  14791. };
  14792. Engine.prototype.bindTransformFeedback = function (value) {
  14793. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14794. };
  14795. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14796. if (usePoints === void 0) { usePoints = true; }
  14797. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14798. };
  14799. Engine.prototype.endTransformFeedback = function () {
  14800. this._gl.endTransformFeedback();
  14801. };
  14802. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14803. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14804. };
  14805. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14806. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14807. };
  14808. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14809. var _this = this;
  14810. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14811. this._activeRequests.push(request);
  14812. request.onCompleteObservable.add(function (request) {
  14813. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14814. });
  14815. return request;
  14816. };
  14817. /** @ignore */
  14818. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14819. var _this = this;
  14820. return new Promise(function (resolve, reject) {
  14821. _this._loadFile(url, function (data) {
  14822. resolve(data);
  14823. }, undefined, database, useArrayBuffer, function (request, exception) {
  14824. reject(exception);
  14825. });
  14826. });
  14827. };
  14828. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14829. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14830. var onload = function (data) {
  14831. loadedFiles[index] = data;
  14832. loadedFiles._internalCount++;
  14833. if (loadedFiles._internalCount === 6) {
  14834. onfinish(loadedFiles);
  14835. }
  14836. };
  14837. var onerror = function (request, exception) {
  14838. if (onErrorCallBack && request) {
  14839. onErrorCallBack(request.status + " " + request.statusText, exception);
  14840. }
  14841. };
  14842. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14843. };
  14844. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14845. if (onError === void 0) { onError = null; }
  14846. var loadedFiles = [];
  14847. loadedFiles._internalCount = 0;
  14848. for (var index = 0; index < 6; index++) {
  14849. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14850. }
  14851. };
  14852. // Statics
  14853. Engine.isSupported = function () {
  14854. try {
  14855. var tempcanvas = document.createElement("canvas");
  14856. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14857. return gl != null && !!window.WebGLRenderingContext;
  14858. }
  14859. catch (e) {
  14860. return false;
  14861. }
  14862. };
  14863. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14864. Engine.ExceptionList = [
  14865. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14866. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14867. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14868. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14869. ];
  14870. Engine.Instances = new Array();
  14871. // Const statics
  14872. Engine._ALPHA_DISABLE = 0;
  14873. Engine._ALPHA_ADD = 1;
  14874. Engine._ALPHA_COMBINE = 2;
  14875. Engine._ALPHA_SUBTRACT = 3;
  14876. Engine._ALPHA_MULTIPLY = 4;
  14877. Engine._ALPHA_MAXIMIZED = 5;
  14878. Engine._ALPHA_ONEONE = 6;
  14879. Engine._ALPHA_PREMULTIPLIED = 7;
  14880. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14881. Engine._ALPHA_INTERPOLATE = 9;
  14882. Engine._ALPHA_SCREENMODE = 10;
  14883. Engine._DELAYLOADSTATE_NONE = 0;
  14884. Engine._DELAYLOADSTATE_LOADED = 1;
  14885. Engine._DELAYLOADSTATE_LOADING = 2;
  14886. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14887. Engine._TEXTUREFORMAT_ALPHA = 0;
  14888. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14889. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14890. Engine._TEXTUREFORMAT_RGB = 4;
  14891. Engine._TEXTUREFORMAT_RGBA = 5;
  14892. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14893. Engine._TEXTURETYPE_FLOAT = 1;
  14894. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14895. // Depht or Stencil test Constants.
  14896. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14897. 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.
  14898. 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.
  14899. 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.
  14900. 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.
  14901. 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.
  14902. 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.
  14903. 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.
  14904. // Stencil Actions Constants.
  14905. Engine._KEEP = 0x1E00;
  14906. Engine._REPLACE = 0x1E01;
  14907. Engine._INCR = 0x1E02;
  14908. Engine._DECR = 0x1E03;
  14909. Engine._INVERT = 0x150A;
  14910. Engine._INCR_WRAP = 0x8507;
  14911. Engine._DECR_WRAP = 0x8508;
  14912. // Texture rescaling mode
  14913. Engine._SCALEMODE_FLOOR = 1;
  14914. Engine._SCALEMODE_NEAREST = 2;
  14915. Engine._SCALEMODE_CEILING = 3;
  14916. // Updatable statics so stick with vars here
  14917. Engine.CollisionsEpsilon = 0.001;
  14918. Engine.CodeRepository = "src/";
  14919. Engine.ShadersRepository = "src/Shaders/";
  14920. return Engine;
  14921. }());
  14922. BABYLON.Engine = Engine;
  14923. })(BABYLON || (BABYLON = {}));
  14924. //# sourceMappingURL=babylon.engine.js.map
  14925. var BABYLON;
  14926. (function (BABYLON) {
  14927. /**
  14928. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14929. */
  14930. var Node = /** @class */ (function () {
  14931. /**
  14932. * Creates a new Node
  14933. * @param {string} name - the name and id to be given to this node
  14934. * @param {BABYLON.Scene} the scene this node will be added to
  14935. */
  14936. function Node(name, scene) {
  14937. if (scene === void 0) { scene = null; }
  14938. /**
  14939. * Gets or sets a string used to store user defined state for the node
  14940. */
  14941. this.state = "";
  14942. /**
  14943. * Gets or sets an object used to store user defined information for the node
  14944. */
  14945. this.metadata = null;
  14946. /**
  14947. * Gets or sets a boolean used to define if the node must be serialized
  14948. */
  14949. this.doNotSerialize = false;
  14950. /** @ignore */
  14951. this._isDisposed = false;
  14952. /**
  14953. * Gets a list of {BABYLON.Animation} associated with the node
  14954. */
  14955. this.animations = new Array();
  14956. this._ranges = {};
  14957. this._isEnabled = true;
  14958. this._isReady = true;
  14959. /** @ignore */
  14960. this._currentRenderId = -1;
  14961. this._parentRenderId = -1;
  14962. /**
  14963. * An event triggered when the mesh is disposed
  14964. * @type {BABYLON.Observable}
  14965. */
  14966. this.onDisposeObservable = new BABYLON.Observable();
  14967. // Behaviors
  14968. this._behaviors = new Array();
  14969. this.name = name;
  14970. this.id = name;
  14971. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14972. this.uniqueId = this._scene.getUniqueId();
  14973. this._initCache();
  14974. }
  14975. /**
  14976. * Gets a boolean indicating if the node has been disposed
  14977. * @returns true if the node was disposed
  14978. */
  14979. Node.prototype.isDisposed = function () {
  14980. return this._isDisposed;
  14981. };
  14982. Object.defineProperty(Node.prototype, "parent", {
  14983. get: function () {
  14984. return this._parentNode;
  14985. },
  14986. /**
  14987. * Gets or sets the parent of the node
  14988. */
  14989. set: function (parent) {
  14990. if (this._parentNode === parent) {
  14991. return;
  14992. }
  14993. // Remove self from list of children of parent
  14994. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14995. var index = this._parentNode._children.indexOf(this);
  14996. if (index !== -1) {
  14997. this._parentNode._children.splice(index, 1);
  14998. }
  14999. }
  15000. // Store new parent
  15001. this._parentNode = parent;
  15002. // Add as child to new parent
  15003. if (this._parentNode) {
  15004. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15005. this._parentNode._children = new Array();
  15006. }
  15007. this._parentNode._children.push(this);
  15008. }
  15009. },
  15010. enumerable: true,
  15011. configurable: true
  15012. });
  15013. /**
  15014. * Gets a string idenfifying the name of the class
  15015. * @returns "Node" string
  15016. */
  15017. Node.prototype.getClassName = function () {
  15018. return "Node";
  15019. };
  15020. Object.defineProperty(Node.prototype, "onDispose", {
  15021. /**
  15022. * Sets a callback that will be raised when the node will be disposed
  15023. */
  15024. set: function (callback) {
  15025. if (this._onDisposeObserver) {
  15026. this.onDisposeObservable.remove(this._onDisposeObserver);
  15027. }
  15028. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15029. },
  15030. enumerable: true,
  15031. configurable: true
  15032. });
  15033. /**
  15034. * Gets the scene of the node
  15035. * @returns a {BABYLON.Scene}
  15036. */
  15037. Node.prototype.getScene = function () {
  15038. return this._scene;
  15039. };
  15040. /**
  15041. * Gets the engine of the node
  15042. * @returns a {BABYLON.Engine}
  15043. */
  15044. Node.prototype.getEngine = function () {
  15045. return this._scene.getEngine();
  15046. };
  15047. /**
  15048. * Attach a behavior to the node
  15049. * @see http://doc.babylonjs.com/features/behaviour
  15050. * @param behavior defines the behavior to attach
  15051. * @returns the current Node
  15052. */
  15053. Node.prototype.addBehavior = function (behavior) {
  15054. var _this = this;
  15055. var index = this._behaviors.indexOf(behavior);
  15056. if (index !== -1) {
  15057. return this;
  15058. }
  15059. behavior.init();
  15060. if (this._scene.isLoading) {
  15061. // We defer the attach when the scene will be loaded
  15062. var observer = this._scene.onDataLoadedObservable.add(function () {
  15063. behavior.attach(_this);
  15064. setTimeout(function () {
  15065. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15066. _this._scene.onDataLoadedObservable.remove(observer);
  15067. }, 0);
  15068. });
  15069. }
  15070. else {
  15071. behavior.attach(this);
  15072. }
  15073. this._behaviors.push(behavior);
  15074. return this;
  15075. };
  15076. /**
  15077. * Remove an attached behavior
  15078. * @see http://doc.babylonjs.com/features/behaviour
  15079. * @param behavior defines the behavior to attach
  15080. * @returns the current Node
  15081. */
  15082. Node.prototype.removeBehavior = function (behavior) {
  15083. var index = this._behaviors.indexOf(behavior);
  15084. if (index === -1) {
  15085. return this;
  15086. }
  15087. this._behaviors[index].detach();
  15088. this._behaviors.splice(index, 1);
  15089. return this;
  15090. };
  15091. Object.defineProperty(Node.prototype, "behaviors", {
  15092. /**
  15093. * Gets the list of attached behaviors
  15094. * @see http://doc.babylonjs.com/features/behaviour
  15095. */
  15096. get: function () {
  15097. return this._behaviors;
  15098. },
  15099. enumerable: true,
  15100. configurable: true
  15101. });
  15102. /**
  15103. * Gets an attached behavior by name
  15104. * @param name defines the name of the behavior to look for
  15105. * @see http://doc.babylonjs.com/features/behaviour
  15106. * @returns null if behavior was not found else the requested behavior
  15107. */
  15108. Node.prototype.getBehaviorByName = function (name) {
  15109. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15110. var behavior = _a[_i];
  15111. if (behavior.name === name) {
  15112. return behavior;
  15113. }
  15114. }
  15115. return null;
  15116. };
  15117. /**
  15118. * Returns the world matrix of the node
  15119. * @returns a matrix containing the node's world matrix
  15120. */
  15121. Node.prototype.getWorldMatrix = function () {
  15122. return BABYLON.Matrix.Identity();
  15123. };
  15124. // override it in derived class if you add new variables to the cache
  15125. // and call the parent class method
  15126. /** @ignore */
  15127. Node.prototype._initCache = function () {
  15128. this._cache = {};
  15129. this._cache.parent = undefined;
  15130. };
  15131. /** @ignore */
  15132. Node.prototype.updateCache = function (force) {
  15133. if (!force && this.isSynchronized())
  15134. return;
  15135. this._cache.parent = this.parent;
  15136. this._updateCache();
  15137. };
  15138. // override it in derived class if you add new variables to the cache
  15139. // and call the parent class method if !ignoreParentClass
  15140. /** @ignore */
  15141. Node.prototype._updateCache = function (ignoreParentClass) {
  15142. };
  15143. // override it in derived class if you add new variables to the cache
  15144. /** @ignore */
  15145. Node.prototype._isSynchronized = function () {
  15146. return true;
  15147. };
  15148. /** @ignore */
  15149. Node.prototype._markSyncedWithParent = function () {
  15150. if (this.parent) {
  15151. this._parentRenderId = this.parent._currentRenderId;
  15152. }
  15153. };
  15154. /** @ignore */
  15155. Node.prototype.isSynchronizedWithParent = function () {
  15156. if (!this.parent) {
  15157. return true;
  15158. }
  15159. if (this._parentRenderId !== this.parent._currentRenderId) {
  15160. return false;
  15161. }
  15162. return this.parent.isSynchronized();
  15163. };
  15164. /** @ignore */
  15165. Node.prototype.isSynchronized = function (updateCache) {
  15166. var check = this.hasNewParent();
  15167. check = check || !this.isSynchronizedWithParent();
  15168. check = check || !this._isSynchronized();
  15169. if (updateCache)
  15170. this.updateCache(true);
  15171. return !check;
  15172. };
  15173. /** @ignore */
  15174. Node.prototype.hasNewParent = function (update) {
  15175. if (this._cache.parent === this.parent)
  15176. return false;
  15177. if (update)
  15178. this._cache.parent = this.parent;
  15179. return true;
  15180. };
  15181. /**
  15182. * Is this node ready to be used/rendered
  15183. * @return true if the node is ready
  15184. */
  15185. Node.prototype.isReady = function () {
  15186. return this._isReady;
  15187. };
  15188. /**
  15189. * Is this node enabled?
  15190. * 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
  15191. * @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
  15192. * @return whether this node (and its parent) is enabled
  15193. * @see setEnabled
  15194. */
  15195. Node.prototype.isEnabled = function (checkAncestors) {
  15196. if (checkAncestors === void 0) { checkAncestors = true; }
  15197. if (checkAncestors === false) {
  15198. return this._isEnabled;
  15199. }
  15200. if (this._isEnabled === false) {
  15201. return false;
  15202. }
  15203. if (this.parent !== undefined && this.parent !== null) {
  15204. return this.parent.isEnabled(checkAncestors);
  15205. }
  15206. return true;
  15207. };
  15208. /**
  15209. * Set the enabled state of this node
  15210. * @param value defines the new enabled state
  15211. * @see isEnabled
  15212. */
  15213. Node.prototype.setEnabled = function (value) {
  15214. this._isEnabled = value;
  15215. };
  15216. /**
  15217. * Is this node a descendant of the given node?
  15218. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15219. * @param ancestor defines the parent node to inspect
  15220. * @see parent
  15221. * @returns a boolean indicating if this node is a descendant of the given node
  15222. */
  15223. Node.prototype.isDescendantOf = function (ancestor) {
  15224. if (this.parent) {
  15225. if (this.parent === ancestor) {
  15226. return true;
  15227. }
  15228. return this.parent.isDescendantOf(ancestor);
  15229. }
  15230. return false;
  15231. };
  15232. /** @ignore */
  15233. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15234. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15235. if (!this._children) {
  15236. return;
  15237. }
  15238. for (var index = 0; index < this._children.length; index++) {
  15239. var item = this._children[index];
  15240. if (!predicate || predicate(item)) {
  15241. results.push(item);
  15242. }
  15243. if (!directDescendantsOnly) {
  15244. item._getDescendants(results, false, predicate);
  15245. }
  15246. }
  15247. };
  15248. /**
  15249. * Will return all nodes that have this node as ascendant
  15250. * @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
  15251. * @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
  15252. * @return all children nodes of all types
  15253. */
  15254. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15255. var results = new Array();
  15256. this._getDescendants(results, directDescendantsOnly, predicate);
  15257. return results;
  15258. };
  15259. /**
  15260. * Get all child-meshes of this node
  15261. * @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
  15262. * @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
  15263. * @returns an array of {BABYLON.AbstractMesh}
  15264. */
  15265. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15266. var results = [];
  15267. this._getDescendants(results, directDescendantsOnly, function (node) {
  15268. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15269. });
  15270. return results;
  15271. };
  15272. /**
  15273. * Get all child-transformNodes of this node
  15274. * @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
  15275. * @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
  15276. * @returns an array of {BABYLON.TransformNode}
  15277. */
  15278. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15279. var results = [];
  15280. this._getDescendants(results, directDescendantsOnly, function (node) {
  15281. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15282. });
  15283. return results;
  15284. };
  15285. /**
  15286. * Get all direct children of this node
  15287. * @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
  15288. * @returns an array of {BABYLON.Node}
  15289. */
  15290. Node.prototype.getChildren = function (predicate) {
  15291. return this.getDescendants(true, predicate);
  15292. };
  15293. /** @ignore */
  15294. Node.prototype._setReady = function (state) {
  15295. if (state === this._isReady) {
  15296. return;
  15297. }
  15298. if (!state) {
  15299. this._isReady = false;
  15300. return;
  15301. }
  15302. this._isReady = true;
  15303. if (this.onReady) {
  15304. this.onReady(this);
  15305. }
  15306. };
  15307. /**
  15308. * Get an animation by name
  15309. * @param name defines the name of the animation to look for
  15310. * @returns null if not found else the requested animation
  15311. */
  15312. Node.prototype.getAnimationByName = function (name) {
  15313. for (var i = 0; i < this.animations.length; i++) {
  15314. var animation = this.animations[i];
  15315. if (animation.name === name) {
  15316. return animation;
  15317. }
  15318. }
  15319. return null;
  15320. };
  15321. /**
  15322. * Creates an animation range for this node
  15323. * @param name defines the name of the range
  15324. * @param from defines the starting key
  15325. * @param to defines the end key
  15326. */
  15327. Node.prototype.createAnimationRange = function (name, from, to) {
  15328. // check name not already in use
  15329. if (!this._ranges[name]) {
  15330. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15331. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15332. if (this.animations[i]) {
  15333. this.animations[i].createRange(name, from, to);
  15334. }
  15335. }
  15336. }
  15337. };
  15338. /**
  15339. * Delete a specific animation range
  15340. * @param name defines the name of the range to delete
  15341. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15342. */
  15343. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15344. if (deleteFrames === void 0) { deleteFrames = true; }
  15345. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15346. if (this.animations[i]) {
  15347. this.animations[i].deleteRange(name, deleteFrames);
  15348. }
  15349. }
  15350. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15351. };
  15352. /**
  15353. * Get an animation range by name
  15354. * @param name defines the name of the animation range to look for
  15355. * @returns null if not found else the requested animation range
  15356. */
  15357. Node.prototype.getAnimationRange = function (name) {
  15358. return this._ranges[name];
  15359. };
  15360. /**
  15361. * Will start the animation sequence
  15362. * @param name defines the range frames for animation sequence
  15363. * @param loop defines if the animation should loop (false by default)
  15364. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15365. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15366. * @returns the object created for this animation. If range does not exist, it will return null
  15367. */
  15368. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15369. var range = this.getAnimationRange(name);
  15370. if (!range) {
  15371. return null;
  15372. }
  15373. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15374. };
  15375. /**
  15376. * Serialize animation ranges into a JSON compatible object
  15377. * @returns serialization object
  15378. */
  15379. Node.prototype.serializeAnimationRanges = function () {
  15380. var serializationRanges = [];
  15381. for (var name in this._ranges) {
  15382. var localRange = this._ranges[name];
  15383. if (!localRange) {
  15384. continue;
  15385. }
  15386. var range = {};
  15387. range.name = name;
  15388. range.from = localRange.from;
  15389. range.to = localRange.to;
  15390. serializationRanges.push(range);
  15391. }
  15392. return serializationRanges;
  15393. };
  15394. /**
  15395. * Computes the world matrix of the node
  15396. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15397. * @returns the world matrix
  15398. */
  15399. Node.prototype.computeWorldMatrix = function (force) {
  15400. return BABYLON.Matrix.Identity();
  15401. };
  15402. /**
  15403. * Releases all associated resources
  15404. */
  15405. Node.prototype.dispose = function () {
  15406. this.parent = null;
  15407. // Callback
  15408. this.onDisposeObservable.notifyObservers(this);
  15409. this.onDisposeObservable.clear();
  15410. // Behaviors
  15411. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15412. var behavior = _a[_i];
  15413. behavior.detach();
  15414. }
  15415. this._behaviors = [];
  15416. this._isDisposed = true;
  15417. };
  15418. /**
  15419. * Parse animation range data from a serialization object and store them into a given node
  15420. * @param node defines where to store the animation ranges
  15421. * @param parsedNode defines the serialization object to read data from
  15422. * @param scene defines the hosting scene
  15423. */
  15424. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15425. if (parsedNode.ranges) {
  15426. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15427. var data = parsedNode.ranges[index];
  15428. node.createAnimationRange(data.name, data.from, data.to);
  15429. }
  15430. }
  15431. };
  15432. __decorate([
  15433. BABYLON.serialize()
  15434. ], Node.prototype, "name", void 0);
  15435. __decorate([
  15436. BABYLON.serialize()
  15437. ], Node.prototype, "id", void 0);
  15438. __decorate([
  15439. BABYLON.serialize()
  15440. ], Node.prototype, "uniqueId", void 0);
  15441. __decorate([
  15442. BABYLON.serialize()
  15443. ], Node.prototype, "state", void 0);
  15444. __decorate([
  15445. BABYLON.serialize()
  15446. ], Node.prototype, "metadata", void 0);
  15447. return Node;
  15448. }());
  15449. BABYLON.Node = Node;
  15450. })(BABYLON || (BABYLON = {}));
  15451. //# sourceMappingURL=babylon.node.js.map
  15452. var BABYLON;
  15453. (function (BABYLON) {
  15454. var BoundingSphere = /** @class */ (function () {
  15455. function BoundingSphere(minimum, maximum) {
  15456. this.minimum = minimum;
  15457. this.maximum = maximum;
  15458. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15459. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15460. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15461. this.radius = distance * 0.5;
  15462. this.centerWorld = BABYLON.Vector3.Zero();
  15463. this._update(BABYLON.Matrix.Identity());
  15464. }
  15465. // Methods
  15466. BoundingSphere.prototype._update = function (world) {
  15467. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15468. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15469. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15470. };
  15471. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15472. for (var i = 0; i < 6; i++) {
  15473. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15474. return false;
  15475. }
  15476. return true;
  15477. };
  15478. BoundingSphere.prototype.intersectsPoint = function (point) {
  15479. var x = this.centerWorld.x - point.x;
  15480. var y = this.centerWorld.y - point.y;
  15481. var z = this.centerWorld.z - point.z;
  15482. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15483. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15484. return false;
  15485. return true;
  15486. };
  15487. // Statics
  15488. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15489. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15490. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15491. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15492. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15493. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15494. return false;
  15495. return true;
  15496. };
  15497. return BoundingSphere;
  15498. }());
  15499. BABYLON.BoundingSphere = BoundingSphere;
  15500. })(BABYLON || (BABYLON = {}));
  15501. //# sourceMappingURL=babylon.boundingSphere.js.map
  15502. var BABYLON;
  15503. (function (BABYLON) {
  15504. var BoundingBox = /** @class */ (function () {
  15505. function BoundingBox(minimum, maximum) {
  15506. this.minimum = minimum;
  15507. this.maximum = maximum;
  15508. this.vectors = new Array();
  15509. this.vectorsWorld = new Array();
  15510. // Bounding vectors
  15511. this.vectors.push(this.minimum.clone());
  15512. this.vectors.push(this.maximum.clone());
  15513. this.vectors.push(this.minimum.clone());
  15514. this.vectors[2].x = this.maximum.x;
  15515. this.vectors.push(this.minimum.clone());
  15516. this.vectors[3].y = this.maximum.y;
  15517. this.vectors.push(this.minimum.clone());
  15518. this.vectors[4].z = this.maximum.z;
  15519. this.vectors.push(this.maximum.clone());
  15520. this.vectors[5].z = this.minimum.z;
  15521. this.vectors.push(this.maximum.clone());
  15522. this.vectors[6].x = this.minimum.x;
  15523. this.vectors.push(this.maximum.clone());
  15524. this.vectors[7].y = this.minimum.y;
  15525. // OBB
  15526. this.center = this.maximum.add(this.minimum).scale(0.5);
  15527. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15528. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15529. // World
  15530. for (var index = 0; index < this.vectors.length; index++) {
  15531. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15532. }
  15533. this.minimumWorld = BABYLON.Vector3.Zero();
  15534. this.maximumWorld = BABYLON.Vector3.Zero();
  15535. this.centerWorld = BABYLON.Vector3.Zero();
  15536. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15537. this._update(BABYLON.Matrix.Identity());
  15538. }
  15539. // Methods
  15540. BoundingBox.prototype.getWorldMatrix = function () {
  15541. return this._worldMatrix;
  15542. };
  15543. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15544. this._worldMatrix.copyFrom(matrix);
  15545. return this;
  15546. };
  15547. BoundingBox.prototype._update = function (world) {
  15548. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15549. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15550. for (var index = 0; index < this.vectors.length; index++) {
  15551. var v = this.vectorsWorld[index];
  15552. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15553. if (v.x < this.minimumWorld.x)
  15554. this.minimumWorld.x = v.x;
  15555. if (v.y < this.minimumWorld.y)
  15556. this.minimumWorld.y = v.y;
  15557. if (v.z < this.minimumWorld.z)
  15558. this.minimumWorld.z = v.z;
  15559. if (v.x > this.maximumWorld.x)
  15560. this.maximumWorld.x = v.x;
  15561. if (v.y > this.maximumWorld.y)
  15562. this.maximumWorld.y = v.y;
  15563. if (v.z > this.maximumWorld.z)
  15564. this.maximumWorld.z = v.z;
  15565. }
  15566. // Extend
  15567. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15568. this.extendSizeWorld.scaleInPlace(0.5);
  15569. // OBB
  15570. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15571. this.centerWorld.scaleInPlace(0.5);
  15572. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15573. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15574. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15575. this._worldMatrix = world;
  15576. };
  15577. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15578. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15579. };
  15580. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15581. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15582. };
  15583. BoundingBox.prototype.intersectsPoint = function (point) {
  15584. var delta = -BABYLON.Epsilon;
  15585. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15586. return false;
  15587. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15588. return false;
  15589. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15590. return false;
  15591. return true;
  15592. };
  15593. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15594. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15595. };
  15596. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15597. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15598. return false;
  15599. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15600. return false;
  15601. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15602. return false;
  15603. return true;
  15604. };
  15605. // Statics
  15606. BoundingBox.Intersects = function (box0, box1) {
  15607. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15608. return false;
  15609. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15610. return false;
  15611. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15612. return false;
  15613. return true;
  15614. };
  15615. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15616. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15617. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15618. return (num <= (sphereRadius * sphereRadius));
  15619. };
  15620. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15621. for (var p = 0; p < 6; p++) {
  15622. for (var i = 0; i < 8; i++) {
  15623. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15624. return false;
  15625. }
  15626. }
  15627. }
  15628. return true;
  15629. };
  15630. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15631. for (var p = 0; p < 6; p++) {
  15632. var inCount = 8;
  15633. for (var i = 0; i < 8; i++) {
  15634. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15635. --inCount;
  15636. }
  15637. else {
  15638. break;
  15639. }
  15640. }
  15641. if (inCount === 0)
  15642. return false;
  15643. }
  15644. return true;
  15645. };
  15646. return BoundingBox;
  15647. }());
  15648. BABYLON.BoundingBox = BoundingBox;
  15649. })(BABYLON || (BABYLON = {}));
  15650. //# sourceMappingURL=babylon.boundingBox.js.map
  15651. var BABYLON;
  15652. (function (BABYLON) {
  15653. var computeBoxExtents = function (axis, box) {
  15654. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15655. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15656. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15657. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15658. var r = r0 + r1 + r2;
  15659. return {
  15660. min: p - r,
  15661. max: p + r
  15662. };
  15663. };
  15664. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15665. var axisOverlap = function (axis, box0, box1) {
  15666. var result0 = computeBoxExtents(axis, box0);
  15667. var result1 = computeBoxExtents(axis, box1);
  15668. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15669. };
  15670. var BoundingInfo = /** @class */ (function () {
  15671. function BoundingInfo(minimum, maximum) {
  15672. this.minimum = minimum;
  15673. this.maximum = maximum;
  15674. this._isLocked = false;
  15675. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15676. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15677. }
  15678. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15679. get: function () {
  15680. return this._isLocked;
  15681. },
  15682. set: function (value) {
  15683. this._isLocked = value;
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. // Methods
  15689. BoundingInfo.prototype.update = function (world) {
  15690. if (this._isLocked) {
  15691. return;
  15692. }
  15693. this.boundingBox._update(world);
  15694. this.boundingSphere._update(world);
  15695. };
  15696. /**
  15697. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15698. * @param center New center of the bounding info
  15699. * @param extend New extend of the bounding info
  15700. */
  15701. BoundingInfo.prototype.centerOn = function (center, extend) {
  15702. this.minimum = center.subtract(extend);
  15703. this.maximum = center.add(extend);
  15704. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15705. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15706. return this;
  15707. };
  15708. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15709. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15710. return false;
  15711. return this.boundingBox.isInFrustum(frustumPlanes);
  15712. };
  15713. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15714. /**
  15715. * Gets the world distance between the min and max points of the bounding box
  15716. */
  15717. get: function () {
  15718. var boundingBox = this.boundingBox;
  15719. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15720. return size.length();
  15721. },
  15722. enumerable: true,
  15723. configurable: true
  15724. });
  15725. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15726. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15727. };
  15728. BoundingInfo.prototype._checkCollision = function (collider) {
  15729. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15730. };
  15731. BoundingInfo.prototype.intersectsPoint = function (point) {
  15732. if (!this.boundingSphere.centerWorld) {
  15733. return false;
  15734. }
  15735. if (!this.boundingSphere.intersectsPoint(point)) {
  15736. return false;
  15737. }
  15738. if (!this.boundingBox.intersectsPoint(point)) {
  15739. return false;
  15740. }
  15741. return true;
  15742. };
  15743. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15744. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15745. return false;
  15746. }
  15747. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15748. return false;
  15749. }
  15750. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15751. return false;
  15752. }
  15753. if (!precise) {
  15754. return true;
  15755. }
  15756. var box0 = this.boundingBox;
  15757. var box1 = boundingInfo.boundingBox;
  15758. if (!axisOverlap(box0.directions[0], box0, box1))
  15759. return false;
  15760. if (!axisOverlap(box0.directions[1], box0, box1))
  15761. return false;
  15762. if (!axisOverlap(box0.directions[2], box0, box1))
  15763. return false;
  15764. if (!axisOverlap(box1.directions[0], box0, box1))
  15765. return false;
  15766. if (!axisOverlap(box1.directions[1], box0, box1))
  15767. return false;
  15768. if (!axisOverlap(box1.directions[2], box0, box1))
  15769. return false;
  15770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15771. return false;
  15772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15773. return false;
  15774. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15775. return false;
  15776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15777. return false;
  15778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15779. return false;
  15780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15781. return false;
  15782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15783. return false;
  15784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15785. return false;
  15786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15787. return false;
  15788. return true;
  15789. };
  15790. return BoundingInfo;
  15791. }());
  15792. BABYLON.BoundingInfo = BoundingInfo;
  15793. })(BABYLON || (BABYLON = {}));
  15794. //# sourceMappingURL=babylon.boundingInfo.js.map
  15795. var BABYLON;
  15796. (function (BABYLON) {
  15797. var TransformNode = /** @class */ (function (_super) {
  15798. __extends(TransformNode, _super);
  15799. function TransformNode(name, scene, isPure) {
  15800. if (scene === void 0) { scene = null; }
  15801. if (isPure === void 0) { isPure = true; }
  15802. var _this = _super.call(this, name, scene) || this;
  15803. // Properties
  15804. _this._rotation = BABYLON.Vector3.Zero();
  15805. _this._scaling = BABYLON.Vector3.One();
  15806. _this._isDirty = false;
  15807. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15808. _this.scalingDeterminant = 1;
  15809. _this.infiniteDistance = false;
  15810. _this.position = BABYLON.Vector3.Zero();
  15811. _this._localWorld = BABYLON.Matrix.Zero();
  15812. _this._worldMatrix = BABYLON.Matrix.Zero();
  15813. _this._worldMatrixDeterminant = 0;
  15814. _this._absolutePosition = BABYLON.Vector3.Zero();
  15815. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15816. _this._postMultiplyPivotMatrix = false;
  15817. _this._isWorldMatrixFrozen = false;
  15818. /**
  15819. * An event triggered after the world matrix is updated
  15820. * @type {BABYLON.Observable}
  15821. */
  15822. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15823. _this._nonUniformScaling = false;
  15824. if (isPure) {
  15825. _this.getScene().addTransformNode(_this);
  15826. }
  15827. return _this;
  15828. }
  15829. Object.defineProperty(TransformNode.prototype, "rotation", {
  15830. /**
  15831. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15832. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15833. * Default : (0.0, 0.0, 0.0)
  15834. */
  15835. get: function () {
  15836. return this._rotation;
  15837. },
  15838. set: function (newRotation) {
  15839. this._rotation = newRotation;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(TransformNode.prototype, "scaling", {
  15845. /**
  15846. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15847. * Default : (1.0, 1.0, 1.0)
  15848. */
  15849. get: function () {
  15850. return this._scaling;
  15851. },
  15852. /**
  15853. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15854. * Default : (1.0, 1.0, 1.0)
  15855. */
  15856. set: function (newScaling) {
  15857. this._scaling = newScaling;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15863. /**
  15864. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15865. * It's null by default.
  15866. * 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)
  15867. */
  15868. get: function () {
  15869. return this._rotationQuaternion;
  15870. },
  15871. set: function (quaternion) {
  15872. this._rotationQuaternion = quaternion;
  15873. //reset the rotation vector.
  15874. if (quaternion && this.rotation.length()) {
  15875. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15876. }
  15877. },
  15878. enumerable: true,
  15879. configurable: true
  15880. });
  15881. /**
  15882. * Returns the latest update of the World matrix
  15883. * Returns a Matrix.
  15884. */
  15885. TransformNode.prototype.getWorldMatrix = function () {
  15886. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15887. this.computeWorldMatrix();
  15888. }
  15889. return this._worldMatrix;
  15890. };
  15891. /**
  15892. * Returns the latest update of the World matrix determinant.
  15893. */
  15894. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15895. return this._worldMatrixDeterminant;
  15896. };
  15897. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15898. /**
  15899. * Returns directly the latest state of the mesh World matrix.
  15900. * A Matrix is returned.
  15901. */
  15902. get: function () {
  15903. return this._worldMatrix;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. /**
  15909. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15910. * Returns the AbstractMesh.
  15911. */
  15912. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15913. this._poseMatrix.copyFrom(matrix);
  15914. return this;
  15915. };
  15916. /**
  15917. * Returns the mesh Pose matrix.
  15918. * Returned object : Matrix
  15919. */
  15920. TransformNode.prototype.getPoseMatrix = function () {
  15921. return this._poseMatrix;
  15922. };
  15923. TransformNode.prototype._isSynchronized = function () {
  15924. if (this._isDirty) {
  15925. return false;
  15926. }
  15927. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15928. return false;
  15929. if (this._cache.pivotMatrixUpdated) {
  15930. return false;
  15931. }
  15932. if (this.infiniteDistance) {
  15933. return false;
  15934. }
  15935. if (!this._cache.position.equals(this.position))
  15936. return false;
  15937. if (this.rotationQuaternion) {
  15938. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15939. return false;
  15940. }
  15941. if (!this._cache.rotation.equals(this.rotation))
  15942. return false;
  15943. if (!this._cache.scaling.equals(this.scaling))
  15944. return false;
  15945. return true;
  15946. };
  15947. TransformNode.prototype._initCache = function () {
  15948. _super.prototype._initCache.call(this);
  15949. this._cache.localMatrixUpdated = false;
  15950. this._cache.position = BABYLON.Vector3.Zero();
  15951. this._cache.scaling = BABYLON.Vector3.Zero();
  15952. this._cache.rotation = BABYLON.Vector3.Zero();
  15953. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15954. this._cache.billboardMode = -1;
  15955. };
  15956. TransformNode.prototype.markAsDirty = function (property) {
  15957. if (property === "rotation") {
  15958. this.rotationQuaternion = null;
  15959. }
  15960. this._currentRenderId = Number.MAX_VALUE;
  15961. this._isDirty = true;
  15962. return this;
  15963. };
  15964. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15965. /**
  15966. * Returns the current mesh absolute position.
  15967. * Retuns a Vector3.
  15968. */
  15969. get: function () {
  15970. return this._absolutePosition;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. /**
  15976. * Sets a new matrix to apply before all other transformation
  15977. * @param matrix defines the transform matrix
  15978. * @returns the current TransformNode
  15979. */
  15980. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15981. return this.setPivotMatrix(matrix, false);
  15982. };
  15983. /**
  15984. * Sets a new pivot matrix to the current node
  15985. * @param matrix defines the new pivot matrix to use
  15986. * @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
  15987. * @returns the current TransformNode
  15988. */
  15989. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15990. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15991. this._pivotMatrix = matrix.clone();
  15992. this._cache.pivotMatrixUpdated = true;
  15993. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15994. if (this._postMultiplyPivotMatrix) {
  15995. if (!this._pivotMatrixInverse) {
  15996. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15997. }
  15998. else {
  15999. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16000. }
  16001. }
  16002. return this;
  16003. };
  16004. /**
  16005. * Returns the mesh pivot matrix.
  16006. * Default : Identity.
  16007. * A Matrix is returned.
  16008. */
  16009. TransformNode.prototype.getPivotMatrix = function () {
  16010. return this._pivotMatrix;
  16011. };
  16012. /**
  16013. * Prevents the World matrix to be computed any longer.
  16014. * Returns the AbstractMesh.
  16015. */
  16016. TransformNode.prototype.freezeWorldMatrix = function () {
  16017. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16018. this.computeWorldMatrix(true);
  16019. this._isWorldMatrixFrozen = true;
  16020. return this;
  16021. };
  16022. /**
  16023. * Allows back the World matrix computation.
  16024. * Returns the AbstractMesh.
  16025. */
  16026. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16027. this._isWorldMatrixFrozen = false;
  16028. this.computeWorldMatrix(true);
  16029. return this;
  16030. };
  16031. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16032. /**
  16033. * True if the World matrix has been frozen.
  16034. * Returns a boolean.
  16035. */
  16036. get: function () {
  16037. return this._isWorldMatrixFrozen;
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. /**
  16043. * Retuns the mesh absolute position in the World.
  16044. * Returns a Vector3.
  16045. */
  16046. TransformNode.prototype.getAbsolutePosition = function () {
  16047. this.computeWorldMatrix();
  16048. return this._absolutePosition;
  16049. };
  16050. /**
  16051. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16052. * Returns the AbstractMesh.
  16053. */
  16054. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16055. if (!absolutePosition) {
  16056. return this;
  16057. }
  16058. var absolutePositionX;
  16059. var absolutePositionY;
  16060. var absolutePositionZ;
  16061. if (absolutePosition.x === undefined) {
  16062. if (arguments.length < 3) {
  16063. return this;
  16064. }
  16065. absolutePositionX = arguments[0];
  16066. absolutePositionY = arguments[1];
  16067. absolutePositionZ = arguments[2];
  16068. }
  16069. else {
  16070. absolutePositionX = absolutePosition.x;
  16071. absolutePositionY = absolutePosition.y;
  16072. absolutePositionZ = absolutePosition.z;
  16073. }
  16074. if (this.parent) {
  16075. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16076. invertParentWorldMatrix.invert();
  16077. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16078. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16079. }
  16080. else {
  16081. this.position.x = absolutePositionX;
  16082. this.position.y = absolutePositionY;
  16083. this.position.z = absolutePositionZ;
  16084. }
  16085. return this;
  16086. };
  16087. /**
  16088. * Sets the mesh position in its local space.
  16089. * Returns the AbstractMesh.
  16090. */
  16091. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16092. this.computeWorldMatrix();
  16093. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16094. return this;
  16095. };
  16096. /**
  16097. * Returns the mesh position in the local space from the current World matrix values.
  16098. * Returns a new Vector3.
  16099. */
  16100. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16101. this.computeWorldMatrix();
  16102. var invLocalWorldMatrix = this._localWorld.clone();
  16103. invLocalWorldMatrix.invert();
  16104. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16105. };
  16106. /**
  16107. * Translates the mesh along the passed Vector3 in its local space.
  16108. * Returns the AbstractMesh.
  16109. */
  16110. TransformNode.prototype.locallyTranslate = function (vector3) {
  16111. this.computeWorldMatrix(true);
  16112. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16113. return this;
  16114. };
  16115. /**
  16116. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16117. * @param targetPoint the position (must be in same space as current mesh) to look at
  16118. * @param yawCor optional yaw (y-axis) correction in radians
  16119. * @param pitchCor optional pitch (x-axis) correction in radians
  16120. * @param rollCor optional roll (z-axis) correction in radians
  16121. * @param space the choosen space of the target
  16122. * @returns the TransformNode.
  16123. */
  16124. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16125. if (yawCor === void 0) { yawCor = 0; }
  16126. if (pitchCor === void 0) { pitchCor = 0; }
  16127. if (rollCor === void 0) { rollCor = 0; }
  16128. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16129. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16130. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16131. targetPoint.subtractToRef(pos, dv);
  16132. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16133. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16134. var pitch = Math.atan2(dv.y, len);
  16135. if (this.rotationQuaternion) {
  16136. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16137. }
  16138. else {
  16139. this.rotation.x = pitch + pitchCor;
  16140. this.rotation.y = yaw + yawCor;
  16141. this.rotation.z = rollCor;
  16142. }
  16143. return this;
  16144. };
  16145. /**
  16146. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16147. * This Vector3 is expressed in the World space.
  16148. */
  16149. TransformNode.prototype.getDirection = function (localAxis) {
  16150. var result = BABYLON.Vector3.Zero();
  16151. this.getDirectionToRef(localAxis, result);
  16152. return result;
  16153. };
  16154. /**
  16155. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16156. * localAxis is expressed in the mesh local space.
  16157. * result is computed in the Wordl space from the mesh World matrix.
  16158. * Returns the AbstractMesh.
  16159. */
  16160. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16161. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16162. return this;
  16163. };
  16164. /**
  16165. * Sets a new pivot point to the current node
  16166. * @param point defines the new pivot point to use
  16167. * @param space defines if the point is in world or local space (local by default)
  16168. * @returns the current TransformNode
  16169. */
  16170. TransformNode.prototype.setPivotPoint = function (point, space) {
  16171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16172. if (this.getScene().getRenderId() == 0) {
  16173. this.computeWorldMatrix(true);
  16174. }
  16175. var wm = this.getWorldMatrix();
  16176. if (space == BABYLON.Space.WORLD) {
  16177. var tmat = BABYLON.Tmp.Matrix[0];
  16178. wm.invertToRef(tmat);
  16179. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16180. }
  16181. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16182. };
  16183. /**
  16184. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16185. */
  16186. TransformNode.prototype.getPivotPoint = function () {
  16187. var point = BABYLON.Vector3.Zero();
  16188. this.getPivotPointToRef(point);
  16189. return point;
  16190. };
  16191. /**
  16192. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16193. * Returns the AbstractMesh.
  16194. */
  16195. TransformNode.prototype.getPivotPointToRef = function (result) {
  16196. result.x = -this._pivotMatrix.m[12];
  16197. result.y = -this._pivotMatrix.m[13];
  16198. result.z = -this._pivotMatrix.m[14];
  16199. return this;
  16200. };
  16201. /**
  16202. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16203. */
  16204. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16205. var point = BABYLON.Vector3.Zero();
  16206. this.getAbsolutePivotPointToRef(point);
  16207. return point;
  16208. };
  16209. /**
  16210. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16211. * Returns the AbstractMesh.
  16212. */
  16213. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16214. result.x = this._pivotMatrix.m[12];
  16215. result.y = this._pivotMatrix.m[13];
  16216. result.z = this._pivotMatrix.m[14];
  16217. this.getPivotPointToRef(result);
  16218. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16219. return this;
  16220. };
  16221. /**
  16222. * Defines the passed node as the parent of the current node.
  16223. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16224. * Returns the TransformNode.
  16225. */
  16226. TransformNode.prototype.setParent = function (node) {
  16227. if (node === null) {
  16228. var rotation = BABYLON.Tmp.Quaternion[0];
  16229. var position = BABYLON.Tmp.Vector3[0];
  16230. var scale = BABYLON.Tmp.Vector3[1];
  16231. if (this.parent && this.parent.computeWorldMatrix) {
  16232. this.parent.computeWorldMatrix(true);
  16233. }
  16234. this.computeWorldMatrix(true);
  16235. this.getWorldMatrix().decompose(scale, rotation, position);
  16236. if (this.rotationQuaternion) {
  16237. this.rotationQuaternion.copyFrom(rotation);
  16238. }
  16239. else {
  16240. rotation.toEulerAnglesToRef(this.rotation);
  16241. }
  16242. this.scaling.x = scale.x;
  16243. this.scaling.y = scale.y;
  16244. this.scaling.z = scale.z;
  16245. this.position.x = position.x;
  16246. this.position.y = position.y;
  16247. this.position.z = position.z;
  16248. }
  16249. else {
  16250. var rotation = BABYLON.Tmp.Quaternion[0];
  16251. var position = BABYLON.Tmp.Vector3[0];
  16252. var scale = BABYLON.Tmp.Vector3[1];
  16253. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16254. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16255. this.computeWorldMatrix(true);
  16256. node.computeWorldMatrix(true);
  16257. node.getWorldMatrix().invertToRef(invParentMatrix);
  16258. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16259. diffMatrix.decompose(scale, rotation, position);
  16260. if (this.rotationQuaternion) {
  16261. this.rotationQuaternion.copyFrom(rotation);
  16262. }
  16263. else {
  16264. rotation.toEulerAnglesToRef(this.rotation);
  16265. }
  16266. this.position.x = position.x;
  16267. this.position.y = position.y;
  16268. this.position.z = position.z;
  16269. this.scaling.x = scale.x;
  16270. this.scaling.y = scale.y;
  16271. this.scaling.z = scale.z;
  16272. }
  16273. this.parent = node;
  16274. return this;
  16275. };
  16276. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16277. get: function () {
  16278. return this._nonUniformScaling;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16284. if (this._nonUniformScaling === value) {
  16285. return false;
  16286. }
  16287. this._nonUniformScaling = true;
  16288. return true;
  16289. };
  16290. /**
  16291. * Attach the current TransformNode to another TransformNode associated with a bone
  16292. * @param bone Bone affecting the TransformNode
  16293. * @param affectedTransformNode TransformNode associated with the bone
  16294. */
  16295. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16296. this._transformToBoneReferal = affectedTransformNode;
  16297. this.parent = bone;
  16298. if (bone.getWorldMatrix().determinant() < 0) {
  16299. this.scalingDeterminant *= -1;
  16300. }
  16301. return this;
  16302. };
  16303. TransformNode.prototype.detachFromBone = function () {
  16304. if (!this.parent) {
  16305. return this;
  16306. }
  16307. if (this.parent.getWorldMatrix().determinant() < 0) {
  16308. this.scalingDeterminant *= -1;
  16309. }
  16310. this._transformToBoneReferal = null;
  16311. this.parent = null;
  16312. return this;
  16313. };
  16314. /**
  16315. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16316. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16317. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16318. * The passed axis is also normalized.
  16319. * Returns the AbstractMesh.
  16320. */
  16321. TransformNode.prototype.rotate = function (axis, amount, space) {
  16322. axis.normalize();
  16323. if (!this.rotationQuaternion) {
  16324. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16325. this.rotation = BABYLON.Vector3.Zero();
  16326. }
  16327. var rotationQuaternion;
  16328. if (!space || space === BABYLON.Space.LOCAL) {
  16329. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16330. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16331. }
  16332. else {
  16333. if (this.parent) {
  16334. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16335. invertParentWorldMatrix.invert();
  16336. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16337. }
  16338. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16339. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16340. }
  16341. return this;
  16342. };
  16343. /**
  16344. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16345. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16346. * The passed axis is also normalized.
  16347. * Returns the AbstractMesh.
  16348. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16349. */
  16350. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16351. axis.normalize();
  16352. if (!this.rotationQuaternion) {
  16353. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16354. this.rotation.copyFromFloats(0, 0, 0);
  16355. }
  16356. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16357. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16358. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16359. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16360. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16361. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16362. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16363. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16364. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16365. return this;
  16366. };
  16367. /**
  16368. * Translates the mesh along the axis vector for the passed distance in the given space.
  16369. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16370. * Returns the AbstractMesh.
  16371. */
  16372. TransformNode.prototype.translate = function (axis, distance, space) {
  16373. var displacementVector = axis.scale(distance);
  16374. if (!space || space === BABYLON.Space.LOCAL) {
  16375. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16376. this.setPositionWithLocalVector(tempV3);
  16377. }
  16378. else {
  16379. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16380. }
  16381. return this;
  16382. };
  16383. /**
  16384. * Adds a rotation step to the mesh current rotation.
  16385. * x, y, z are Euler angles expressed in radians.
  16386. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16387. * This means this rotation is made in the mesh local space only.
  16388. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16389. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16390. * ```javascript
  16391. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16392. * ```
  16393. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16394. * 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.
  16395. * Returns the AbstractMesh.
  16396. */
  16397. TransformNode.prototype.addRotation = function (x, y, z) {
  16398. var rotationQuaternion;
  16399. if (this.rotationQuaternion) {
  16400. rotationQuaternion = this.rotationQuaternion;
  16401. }
  16402. else {
  16403. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16404. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16405. }
  16406. var accumulation = BABYLON.Tmp.Quaternion[0];
  16407. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16408. rotationQuaternion.multiplyInPlace(accumulation);
  16409. if (!this.rotationQuaternion) {
  16410. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16411. }
  16412. return this;
  16413. };
  16414. /**
  16415. * Computes the mesh World matrix and returns it.
  16416. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16417. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16418. * If the parameter `force`is set to `true`, the actual computation is done.
  16419. * Returns the mesh World Matrix.
  16420. */
  16421. TransformNode.prototype.computeWorldMatrix = function (force) {
  16422. if (this._isWorldMatrixFrozen) {
  16423. return this._worldMatrix;
  16424. }
  16425. if (!force && this.isSynchronized(true)) {
  16426. return this._worldMatrix;
  16427. }
  16428. this._cache.position.copyFrom(this.position);
  16429. this._cache.scaling.copyFrom(this.scaling);
  16430. this._cache.pivotMatrixUpdated = false;
  16431. this._cache.billboardMode = this.billboardMode;
  16432. this._currentRenderId = this.getScene().getRenderId();
  16433. this._isDirty = false;
  16434. // Scaling
  16435. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16436. // Rotation
  16437. //rotate, if quaternion is set and rotation was used
  16438. if (this.rotationQuaternion) {
  16439. var len = this.rotation.length();
  16440. if (len) {
  16441. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16442. this.rotation.copyFromFloats(0, 0, 0);
  16443. }
  16444. }
  16445. if (this.rotationQuaternion) {
  16446. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16447. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16448. }
  16449. else {
  16450. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16451. this._cache.rotation.copyFrom(this.rotation);
  16452. }
  16453. // Translation
  16454. var camera = this.getScene().activeCamera;
  16455. if (this.infiniteDistance && !this.parent && camera) {
  16456. var cameraWorldMatrix = camera.getWorldMatrix();
  16457. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16458. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16459. }
  16460. else {
  16461. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16462. }
  16463. // Composing transformations
  16464. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16465. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16466. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16467. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16468. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16469. // Need to decompose each rotation here
  16470. var currentPosition = BABYLON.Tmp.Vector3[3];
  16471. if (this.parent && this.parent.getWorldMatrix) {
  16472. if (this._transformToBoneReferal) {
  16473. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16474. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16475. }
  16476. else {
  16477. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16478. }
  16479. }
  16480. else {
  16481. currentPosition.copyFrom(this.position);
  16482. }
  16483. currentPosition.subtractInPlace(camera.globalPosition);
  16484. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16485. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16486. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16487. }
  16488. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16489. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16490. }
  16491. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16492. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16493. }
  16494. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16495. }
  16496. else {
  16497. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16498. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16499. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16500. }
  16501. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16502. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16503. }
  16504. // Local world
  16505. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16506. // Parent
  16507. if (this.parent && this.parent.getWorldMatrix) {
  16508. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16509. if (this._transformToBoneReferal) {
  16510. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16511. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16512. }
  16513. else {
  16514. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16515. }
  16516. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16517. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16518. this._worldMatrix.copyFrom(this._localWorld);
  16519. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16520. }
  16521. else {
  16522. if (this._transformToBoneReferal) {
  16523. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16524. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16525. }
  16526. else {
  16527. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16528. }
  16529. }
  16530. this._markSyncedWithParent();
  16531. }
  16532. else {
  16533. this._worldMatrix.copyFrom(this._localWorld);
  16534. }
  16535. // Post multiply inverse of pivotMatrix
  16536. if (this._postMultiplyPivotMatrix) {
  16537. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16538. }
  16539. // Normal matrix
  16540. if (this.scaling.isNonUniform) {
  16541. this._updateNonUniformScalingState(true);
  16542. }
  16543. else if (this.parent && this.parent._nonUniformScaling) {
  16544. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16545. }
  16546. else {
  16547. this._updateNonUniformScalingState(false);
  16548. }
  16549. this._afterComputeWorldMatrix();
  16550. // Absolute position
  16551. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16552. // Callbacks
  16553. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16554. if (!this._poseMatrix) {
  16555. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16556. }
  16557. // Cache the determinant
  16558. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16559. return this._worldMatrix;
  16560. };
  16561. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16562. };
  16563. /**
  16564. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16565. * @param func: callback function to add
  16566. *
  16567. * Returns the TransformNode.
  16568. */
  16569. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16570. this.onAfterWorldMatrixUpdateObservable.add(func);
  16571. return this;
  16572. };
  16573. /**
  16574. * Removes a registered callback function.
  16575. * Returns the TransformNode.
  16576. */
  16577. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16578. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16579. return this;
  16580. };
  16581. /**
  16582. * Clone the current transform node
  16583. * Returns the new transform node
  16584. * @param name Name of the new clone
  16585. * @param newParent New parent for the clone
  16586. * @param doNotCloneChildren Do not clone children hierarchy
  16587. */
  16588. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16589. var _this = this;
  16590. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16591. result.name = name;
  16592. result.id = name;
  16593. if (newParent) {
  16594. result.parent = newParent;
  16595. }
  16596. if (!doNotCloneChildren) {
  16597. // Children
  16598. var directDescendants = this.getDescendants(true);
  16599. for (var index = 0; index < directDescendants.length; index++) {
  16600. var child = directDescendants[index];
  16601. if (child.clone) {
  16602. child.clone(name + "." + child.name, result);
  16603. }
  16604. }
  16605. }
  16606. return result;
  16607. };
  16608. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16609. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16610. serializationObject.type = this.getClassName();
  16611. // Parent
  16612. if (this.parent) {
  16613. serializationObject.parentId = this.parent.id;
  16614. }
  16615. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16616. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16617. }
  16618. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16619. serializationObject.isEnabled = this.isEnabled();
  16620. // Parent
  16621. if (this.parent) {
  16622. serializationObject.parentId = this.parent.id;
  16623. }
  16624. return serializationObject;
  16625. };
  16626. // Statics
  16627. /**
  16628. * Returns a new TransformNode object parsed from the source provided.
  16629. * The parameter `parsedMesh` is the source.
  16630. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16631. */
  16632. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16633. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16634. if (BABYLON.Tags) {
  16635. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16636. }
  16637. if (parsedTransformNode.localMatrix) {
  16638. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16639. }
  16640. else if (parsedTransformNode.pivotMatrix) {
  16641. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16642. }
  16643. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16644. // Parent
  16645. if (parsedTransformNode.parentId) {
  16646. transformNode._waitingParentId = parsedTransformNode.parentId;
  16647. }
  16648. return transformNode;
  16649. };
  16650. /**
  16651. * Disposes the TransformNode.
  16652. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16653. * Returns nothing.
  16654. */
  16655. TransformNode.prototype.dispose = function (doNotRecurse) {
  16656. // Animations
  16657. this.getScene().stopAnimation(this);
  16658. // Remove from scene
  16659. this.getScene().removeTransformNode(this);
  16660. if (!doNotRecurse) {
  16661. // Children
  16662. var objects = this.getDescendants(true);
  16663. for (var index = 0; index < objects.length; index++) {
  16664. objects[index].dispose();
  16665. }
  16666. }
  16667. else {
  16668. var childMeshes = this.getChildMeshes(true);
  16669. for (index = 0; index < childMeshes.length; index++) {
  16670. var child = childMeshes[index];
  16671. child.parent = null;
  16672. child.computeWorldMatrix(true);
  16673. }
  16674. }
  16675. this.onAfterWorldMatrixUpdateObservable.clear();
  16676. _super.prototype.dispose.call(this);
  16677. };
  16678. // Statics
  16679. TransformNode.BILLBOARDMODE_NONE = 0;
  16680. TransformNode.BILLBOARDMODE_X = 1;
  16681. TransformNode.BILLBOARDMODE_Y = 2;
  16682. TransformNode.BILLBOARDMODE_Z = 4;
  16683. TransformNode.BILLBOARDMODE_ALL = 7;
  16684. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16685. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16686. __decorate([
  16687. BABYLON.serializeAsVector3()
  16688. ], TransformNode.prototype, "_rotation", void 0);
  16689. __decorate([
  16690. BABYLON.serializeAsQuaternion()
  16691. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16692. __decorate([
  16693. BABYLON.serializeAsVector3()
  16694. ], TransformNode.prototype, "_scaling", void 0);
  16695. __decorate([
  16696. BABYLON.serialize()
  16697. ], TransformNode.prototype, "billboardMode", void 0);
  16698. __decorate([
  16699. BABYLON.serialize()
  16700. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16701. __decorate([
  16702. BABYLON.serialize()
  16703. ], TransformNode.prototype, "infiniteDistance", void 0);
  16704. __decorate([
  16705. BABYLON.serializeAsVector3()
  16706. ], TransformNode.prototype, "position", void 0);
  16707. return TransformNode;
  16708. }(BABYLON.Node));
  16709. BABYLON.TransformNode = TransformNode;
  16710. })(BABYLON || (BABYLON = {}));
  16711. //# sourceMappingURL=babylon.transformNode.js.map
  16712. var BABYLON;
  16713. (function (BABYLON) {
  16714. var AbstractMesh = /** @class */ (function (_super) {
  16715. __extends(AbstractMesh, _super);
  16716. // Constructor
  16717. function AbstractMesh(name, scene) {
  16718. if (scene === void 0) { scene = null; }
  16719. var _this = _super.call(this, name, scene, false) || this;
  16720. _this._facetNb = 0; // facet number
  16721. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16722. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16723. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16724. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16725. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16726. _this._subDiv = {
  16727. max: 1,
  16728. X: 1,
  16729. Y: 1,
  16730. Z: 1
  16731. };
  16732. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16733. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16734. // Events
  16735. /**
  16736. * An event triggered when this mesh collides with another one
  16737. * @type {BABYLON.Observable}
  16738. */
  16739. _this.onCollideObservable = new BABYLON.Observable();
  16740. /**
  16741. * An event triggered when the collision's position changes
  16742. * @type {BABYLON.Observable}
  16743. */
  16744. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16745. /**
  16746. * An event triggered when material is changed
  16747. * @type {BABYLON.Observable}
  16748. */
  16749. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16750. // Properties
  16751. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16752. /**
  16753. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16754. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16755. * or
  16756. * 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.
  16757. * for more info check WebGl documentations
  16758. */
  16759. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16760. /**
  16761. * 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:
  16762. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16763. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16764. * 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.
  16765. */
  16766. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16767. /**
  16768. * 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.
  16769. * The default value is -1 which means don't break the query and wait till the result.
  16770. */
  16771. _this.occlusionRetryCount = -1;
  16772. _this._occlusionInternalRetryCounter = 0;
  16773. _this._isOccluded = false;
  16774. _this._isOcclusionQueryInProgress = false;
  16775. _this._visibility = 1.0;
  16776. _this.alphaIndex = Number.MAX_VALUE;
  16777. _this.isVisible = true;
  16778. _this.isPickable = true;
  16779. _this.showBoundingBox = false;
  16780. _this.showSubMeshesBoundingBox = false;
  16781. _this.isBlocker = false;
  16782. _this.enablePointerMoveEvents = false;
  16783. _this.renderingGroupId = 0;
  16784. _this._receiveShadows = false;
  16785. _this.renderOutline = false;
  16786. _this.outlineColor = BABYLON.Color3.Red();
  16787. _this.outlineWidth = 0.02;
  16788. _this.renderOverlay = false;
  16789. _this.overlayColor = BABYLON.Color3.Red();
  16790. _this.overlayAlpha = 0.5;
  16791. _this._hasVertexAlpha = false;
  16792. _this._useVertexColors = true;
  16793. _this._computeBonesUsingShaders = true;
  16794. _this._numBoneInfluencers = 4;
  16795. _this._applyFog = true;
  16796. _this.useOctreeForRenderingSelection = true;
  16797. _this.useOctreeForPicking = true;
  16798. _this.useOctreeForCollisions = true;
  16799. _this._layerMask = 0x0FFFFFFF;
  16800. /**
  16801. * True if the mesh must be rendered in any case.
  16802. */
  16803. _this.alwaysSelectAsActiveMesh = false;
  16804. /**
  16805. * This scene's action manager
  16806. * @type {BABYLON.ActionManager}
  16807. */
  16808. _this.actionManager = null;
  16809. // Physics
  16810. _this.physicsImpostor = null;
  16811. // Collisions
  16812. _this._checkCollisions = false;
  16813. _this._collisionMask = -1;
  16814. _this._collisionGroup = -1;
  16815. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16816. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16817. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16818. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16819. // Edges
  16820. _this.edgesWidth = 1;
  16821. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16822. // Cache
  16823. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16824. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16825. _this._renderId = 0;
  16826. _this._intersectionsInProgress = new Array();
  16827. _this._unIndexed = false;
  16828. _this._lightSources = new Array();
  16829. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16830. if (collidedMesh === void 0) { collidedMesh = null; }
  16831. //TODO move this to the collision coordinator!
  16832. if (_this.getScene().workerCollisions)
  16833. newPosition.multiplyInPlace(_this._collider._radius);
  16834. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16835. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16836. _this.position.addInPlace(_this._diffPositionForCollisions);
  16837. }
  16838. if (collidedMesh) {
  16839. _this.onCollideObservable.notifyObservers(collidedMesh);
  16840. }
  16841. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16842. };
  16843. _this.getScene().addMesh(_this);
  16844. _this._resyncLightSources();
  16845. return _this;
  16846. }
  16847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16848. get: function () {
  16849. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16855. get: function () {
  16856. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16862. get: function () {
  16863. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16869. get: function () {
  16870. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16876. get: function () {
  16877. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16883. /**
  16884. * Read-only : the number of facets in the mesh
  16885. */
  16886. get: function () {
  16887. return this._facetNb;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16893. /**
  16894. * The number (integer) of subdivisions per axis in the partioning space
  16895. */
  16896. get: function () {
  16897. return this._partitioningSubdivisions;
  16898. },
  16899. set: function (nb) {
  16900. this._partitioningSubdivisions = nb;
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16906. /**
  16907. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16908. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16909. */
  16910. get: function () {
  16911. return this._partitioningBBoxRatio;
  16912. },
  16913. set: function (ratio) {
  16914. this._partitioningBBoxRatio = ratio;
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16920. /**
  16921. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16922. * Works only for updatable meshes.
  16923. * Doesn't work with multi-materials.
  16924. */
  16925. get: function () {
  16926. return this._facetDepthSort;
  16927. },
  16928. set: function (sort) {
  16929. this._facetDepthSort = sort;
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16935. /**
  16936. * The location (Vector3) where the facet depth sort must be computed from.
  16937. * By default, the active camera position.
  16938. * Used only when facet depth sort is enabled.
  16939. */
  16940. get: function () {
  16941. return this._facetDepthSortFrom;
  16942. },
  16943. set: function (location) {
  16944. this._facetDepthSortFrom = location;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16950. /**
  16951. * Read-only boolean : is the feature facetData enabled ?
  16952. */
  16953. get: function () {
  16954. return this._facetDataEnabled;
  16955. },
  16956. enumerable: true,
  16957. configurable: true
  16958. });
  16959. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16960. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16961. return false;
  16962. }
  16963. this._markSubMeshesAsMiscDirty();
  16964. return true;
  16965. };
  16966. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16967. set: function (callback) {
  16968. if (this._onCollideObserver) {
  16969. this.onCollideObservable.remove(this._onCollideObserver);
  16970. }
  16971. this._onCollideObserver = this.onCollideObservable.add(callback);
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16977. set: function (callback) {
  16978. if (this._onCollisionPositionChangeObserver) {
  16979. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16980. }
  16981. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16987. /**
  16988. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  16989. */
  16990. get: function () {
  16991. return this._isOccluded;
  16992. },
  16993. set: function (value) {
  16994. this._isOccluded = value;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17000. /**
  17001. * Flag to check the progress status of the query
  17002. */
  17003. get: function () {
  17004. return this._isOcclusionQueryInProgress;
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17010. /**
  17011. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17012. */
  17013. get: function () {
  17014. return this._visibility;
  17015. },
  17016. /**
  17017. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17018. */
  17019. set: function (value) {
  17020. if (this._visibility === value) {
  17021. return;
  17022. }
  17023. this._visibility = value;
  17024. this._markSubMeshesAsMiscDirty();
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(AbstractMesh.prototype, "material", {
  17030. get: function () {
  17031. return this._material;
  17032. },
  17033. set: function (value) {
  17034. if (this._material === value) {
  17035. return;
  17036. }
  17037. this._material = value;
  17038. if (this.onMaterialChangedObservable.hasObservers) {
  17039. this.onMaterialChangedObservable.notifyObservers(this);
  17040. }
  17041. if (!this.subMeshes) {
  17042. return;
  17043. }
  17044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17045. var subMesh = _a[_i];
  17046. subMesh.setEffect(null);
  17047. }
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17053. get: function () {
  17054. return this._receiveShadows;
  17055. },
  17056. set: function (value) {
  17057. if (this._receiveShadows === value) {
  17058. return;
  17059. }
  17060. this._receiveShadows = value;
  17061. this._markSubMeshesAsLightDirty();
  17062. },
  17063. enumerable: true,
  17064. configurable: true
  17065. });
  17066. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17067. get: function () {
  17068. return this._hasVertexAlpha;
  17069. },
  17070. set: function (value) {
  17071. if (this._hasVertexAlpha === value) {
  17072. return;
  17073. }
  17074. this._hasVertexAlpha = value;
  17075. this._markSubMeshesAsAttributesDirty();
  17076. this._markSubMeshesAsMiscDirty();
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17082. get: function () {
  17083. return this._useVertexColors;
  17084. },
  17085. set: function (value) {
  17086. if (this._useVertexColors === value) {
  17087. return;
  17088. }
  17089. this._useVertexColors = value;
  17090. this._markSubMeshesAsAttributesDirty();
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17096. get: function () {
  17097. return this._computeBonesUsingShaders;
  17098. },
  17099. set: function (value) {
  17100. if (this._computeBonesUsingShaders === value) {
  17101. return;
  17102. }
  17103. this._computeBonesUsingShaders = value;
  17104. this._markSubMeshesAsAttributesDirty();
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17110. get: function () {
  17111. return this._numBoneInfluencers;
  17112. },
  17113. set: function (value) {
  17114. if (this._numBoneInfluencers === value) {
  17115. return;
  17116. }
  17117. this._numBoneInfluencers = value;
  17118. this._markSubMeshesAsAttributesDirty();
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17124. get: function () {
  17125. return this._applyFog;
  17126. },
  17127. set: function (value) {
  17128. if (this._applyFog === value) {
  17129. return;
  17130. }
  17131. this._applyFog = value;
  17132. this._markSubMeshesAsMiscDirty();
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17138. get: function () {
  17139. return this._layerMask;
  17140. },
  17141. set: function (value) {
  17142. if (value === this._layerMask) {
  17143. return;
  17144. }
  17145. this._layerMask = value;
  17146. this._resyncLightSources();
  17147. },
  17148. enumerable: true,
  17149. configurable: true
  17150. });
  17151. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17152. get: function () {
  17153. return this._collisionMask;
  17154. },
  17155. set: function (mask) {
  17156. this._collisionMask = !isNaN(mask) ? mask : -1;
  17157. },
  17158. enumerable: true,
  17159. configurable: true
  17160. });
  17161. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17162. get: function () {
  17163. return this._collisionGroup;
  17164. },
  17165. set: function (mask) {
  17166. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17172. get: function () {
  17173. return null;
  17174. },
  17175. enumerable: true,
  17176. configurable: true
  17177. });
  17178. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17179. get: function () {
  17180. return this._skeleton;
  17181. },
  17182. set: function (value) {
  17183. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17184. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17185. }
  17186. if (value && value.needInitialSkinMatrix) {
  17187. value._registerMeshWithPoseMatrix(this);
  17188. }
  17189. this._skeleton = value;
  17190. if (!this._skeleton) {
  17191. this._bonesTransformMatrices = null;
  17192. }
  17193. this._markSubMeshesAsAttributesDirty();
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. /**
  17199. * Returns the string "AbstractMesh"
  17200. */
  17201. AbstractMesh.prototype.getClassName = function () {
  17202. return "AbstractMesh";
  17203. };
  17204. /**
  17205. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17206. */
  17207. AbstractMesh.prototype.toString = function (fullDetails) {
  17208. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17209. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17210. if (this._skeleton) {
  17211. ret += ", skeleton: " + this._skeleton.name;
  17212. }
  17213. if (fullDetails) {
  17214. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17215. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17216. }
  17217. return ret;
  17218. };
  17219. AbstractMesh.prototype._rebuild = function () {
  17220. if (this._occlusionQuery) {
  17221. this._occlusionQuery = null;
  17222. }
  17223. if (this._edgesRenderer) {
  17224. this._edgesRenderer._rebuild();
  17225. }
  17226. if (!this.subMeshes) {
  17227. return;
  17228. }
  17229. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17230. var subMesh = _a[_i];
  17231. subMesh._rebuild();
  17232. }
  17233. };
  17234. AbstractMesh.prototype._resyncLightSources = function () {
  17235. this._lightSources.length = 0;
  17236. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17237. var light = _a[_i];
  17238. if (!light.isEnabled()) {
  17239. continue;
  17240. }
  17241. if (light.canAffectMesh(this)) {
  17242. this._lightSources.push(light);
  17243. }
  17244. }
  17245. this._markSubMeshesAsLightDirty();
  17246. };
  17247. AbstractMesh.prototype._resyncLighSource = function (light) {
  17248. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17249. var index = this._lightSources.indexOf(light);
  17250. if (index === -1) {
  17251. if (!isIn) {
  17252. return;
  17253. }
  17254. this._lightSources.push(light);
  17255. }
  17256. else {
  17257. if (isIn) {
  17258. return;
  17259. }
  17260. this._lightSources.splice(index, 1);
  17261. }
  17262. this._markSubMeshesAsLightDirty();
  17263. };
  17264. AbstractMesh.prototype._removeLightSource = function (light) {
  17265. var index = this._lightSources.indexOf(light);
  17266. if (index === -1) {
  17267. return;
  17268. }
  17269. this._lightSources.splice(index, 1);
  17270. this._markSubMeshesAsLightDirty();
  17271. };
  17272. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17273. if (!this.subMeshes) {
  17274. return;
  17275. }
  17276. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17277. var subMesh = _a[_i];
  17278. if (subMesh._materialDefines) {
  17279. func(subMesh._materialDefines);
  17280. }
  17281. }
  17282. };
  17283. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17284. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17285. };
  17286. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17287. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17288. };
  17289. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17290. if (!this.subMeshes) {
  17291. return;
  17292. }
  17293. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17294. var subMesh = _a[_i];
  17295. var material = subMesh.getMaterial();
  17296. if (material) {
  17297. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17298. }
  17299. }
  17300. };
  17301. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17302. /**
  17303. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17304. * Default : (1.0, 1.0, 1.0)
  17305. */
  17306. get: function () {
  17307. return this._scaling;
  17308. },
  17309. /**
  17310. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17311. * Default : (1.0, 1.0, 1.0)
  17312. */
  17313. set: function (newScaling) {
  17314. this._scaling = newScaling;
  17315. if (this.physicsImpostor) {
  17316. this.physicsImpostor.forceUpdate();
  17317. }
  17318. },
  17319. enumerable: true,
  17320. configurable: true
  17321. });
  17322. // Methods
  17323. /**
  17324. * Disables the mesh edger rendering mode.
  17325. * Returns the AbstractMesh.
  17326. */
  17327. AbstractMesh.prototype.disableEdgesRendering = function () {
  17328. if (this._edgesRenderer) {
  17329. this._edgesRenderer.dispose();
  17330. this._edgesRenderer = null;
  17331. }
  17332. return this;
  17333. };
  17334. /**
  17335. * Enables the edge rendering mode on the mesh.
  17336. * This mode makes the mesh edges visible.
  17337. * Returns the AbstractMesh.
  17338. */
  17339. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17340. if (epsilon === void 0) { epsilon = 0.95; }
  17341. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17342. this.disableEdgesRendering();
  17343. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17344. return this;
  17345. };
  17346. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17347. /**
  17348. * Returns true if the mesh is blocked. Used by the class Mesh.
  17349. * Returns the boolean `false` by default.
  17350. */
  17351. get: function () {
  17352. return false;
  17353. },
  17354. enumerable: true,
  17355. configurable: true
  17356. });
  17357. /**
  17358. * Returns the mesh itself by default, used by the class Mesh.
  17359. * Returned type : AbstractMesh
  17360. */
  17361. AbstractMesh.prototype.getLOD = function (camera) {
  17362. return this;
  17363. };
  17364. /**
  17365. * Returns 0 by default, used by the class Mesh.
  17366. * Returns an integer.
  17367. */
  17368. AbstractMesh.prototype.getTotalVertices = function () {
  17369. return 0;
  17370. };
  17371. /**
  17372. * Returns null by default, used by the class Mesh.
  17373. * Returned type : integer array
  17374. */
  17375. AbstractMesh.prototype.getIndices = function () {
  17376. return null;
  17377. };
  17378. /**
  17379. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17380. * Returned type : float array or Float32Array
  17381. */
  17382. AbstractMesh.prototype.getVerticesData = function (kind) {
  17383. return null;
  17384. };
  17385. /**
  17386. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17387. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17388. * The `data` are either a numeric array either a Float32Array.
  17389. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17390. * 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).
  17391. * Note that a new underlying VertexBuffer object is created each call.
  17392. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17393. *
  17394. * Possible `kind` values :
  17395. * - BABYLON.VertexBuffer.PositionKind
  17396. * - BABYLON.VertexBuffer.UVKind
  17397. * - BABYLON.VertexBuffer.UV2Kind
  17398. * - BABYLON.VertexBuffer.UV3Kind
  17399. * - BABYLON.VertexBuffer.UV4Kind
  17400. * - BABYLON.VertexBuffer.UV5Kind
  17401. * - BABYLON.VertexBuffer.UV6Kind
  17402. * - BABYLON.VertexBuffer.ColorKind
  17403. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17404. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17405. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17406. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17407. *
  17408. * Returns the Mesh.
  17409. */
  17410. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17411. return this;
  17412. };
  17413. /**
  17414. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17415. * If the mesh has no geometry, it is simply returned as it is.
  17416. * The `data` are either a numeric array either a Float32Array.
  17417. * No new underlying VertexBuffer object is created.
  17418. * 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.
  17419. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17420. *
  17421. * Possible `kind` values :
  17422. * - BABYLON.VertexBuffer.PositionKind
  17423. * - BABYLON.VertexBuffer.UVKind
  17424. * - BABYLON.VertexBuffer.UV2Kind
  17425. * - BABYLON.VertexBuffer.UV3Kind
  17426. * - BABYLON.VertexBuffer.UV4Kind
  17427. * - BABYLON.VertexBuffer.UV5Kind
  17428. * - BABYLON.VertexBuffer.UV6Kind
  17429. * - BABYLON.VertexBuffer.ColorKind
  17430. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17431. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17432. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17433. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17434. *
  17435. * Returns the Mesh.
  17436. */
  17437. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17438. return this;
  17439. };
  17440. /**
  17441. * Sets the mesh indices.
  17442. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17443. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17444. * This method creates a new index buffer each call.
  17445. * Returns the Mesh.
  17446. */
  17447. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17448. return this;
  17449. };
  17450. /** Returns false by default, used by the class Mesh.
  17451. * Returns a boolean
  17452. */
  17453. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17454. return false;
  17455. };
  17456. /**
  17457. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17458. * Returns a BoundingInfo
  17459. */
  17460. AbstractMesh.prototype.getBoundingInfo = function () {
  17461. if (this._masterMesh) {
  17462. return this._masterMesh.getBoundingInfo();
  17463. }
  17464. if (!this._boundingInfo) {
  17465. // this._boundingInfo is being created here
  17466. this._updateBoundingInfo();
  17467. }
  17468. // cannot be null.
  17469. return this._boundingInfo;
  17470. };
  17471. /**
  17472. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17473. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17474. */
  17475. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17476. if (includeDescendants === void 0) { includeDescendants = true; }
  17477. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17478. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17479. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17480. if (maxDimension === 0) {
  17481. return this;
  17482. }
  17483. var scale = 1 / maxDimension;
  17484. this.scaling.scaleInPlace(scale);
  17485. return this;
  17486. };
  17487. /**
  17488. * Sets a mesh new object BoundingInfo.
  17489. * Returns the AbstractMesh.
  17490. */
  17491. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17492. this._boundingInfo = boundingInfo;
  17493. return this;
  17494. };
  17495. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17496. get: function () {
  17497. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. AbstractMesh.prototype._preActivate = function () {
  17503. };
  17504. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17505. };
  17506. AbstractMesh.prototype._activate = function (renderId) {
  17507. this._renderId = renderId;
  17508. };
  17509. /**
  17510. * Returns the latest update of the World matrix
  17511. * Returns a Matrix.
  17512. */
  17513. AbstractMesh.prototype.getWorldMatrix = function () {
  17514. if (this._masterMesh) {
  17515. return this._masterMesh.getWorldMatrix();
  17516. }
  17517. return _super.prototype.getWorldMatrix.call(this);
  17518. };
  17519. /**
  17520. * Returns the latest update of the World matrix determinant.
  17521. */
  17522. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17523. if (this._masterMesh) {
  17524. return this._masterMesh._getWorldMatrixDeterminant();
  17525. }
  17526. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17527. };
  17528. // ================================== Point of View Movement =================================
  17529. /**
  17530. * Perform relative position change from the point of view of behind the front of the mesh.
  17531. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17532. * Supports definition of mesh facing forward or backward.
  17533. * @param {number} amountRight
  17534. * @param {number} amountUp
  17535. * @param {number} amountForward
  17536. *
  17537. * Returns the AbstractMesh.
  17538. */
  17539. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17540. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17541. return this;
  17542. };
  17543. /**
  17544. * Calculate relative position change from the point of view of behind the front of the mesh.
  17545. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17546. * Supports definition of mesh facing forward or backward.
  17547. * @param {number} amountRight
  17548. * @param {number} amountUp
  17549. * @param {number} amountForward
  17550. *
  17551. * Returns a new Vector3.
  17552. */
  17553. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17554. var rotMatrix = new BABYLON.Matrix();
  17555. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17556. rotQuaternion.toRotationMatrix(rotMatrix);
  17557. var translationDelta = BABYLON.Vector3.Zero();
  17558. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17559. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17560. return translationDelta;
  17561. };
  17562. // ================================== Point of View Rotation =================================
  17563. /**
  17564. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17565. * Supports definition of mesh facing forward or backward.
  17566. * @param {number} flipBack
  17567. * @param {number} twirlClockwise
  17568. * @param {number} tiltRight
  17569. *
  17570. * Returns the AbstractMesh.
  17571. */
  17572. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17573. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17574. return this;
  17575. };
  17576. /**
  17577. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17578. * Supports definition of mesh facing forward or backward.
  17579. * @param {number} flipBack
  17580. * @param {number} twirlClockwise
  17581. * @param {number} tiltRight
  17582. *
  17583. * Returns a new Vector3.
  17584. */
  17585. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17586. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17587. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17588. };
  17589. /**
  17590. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17591. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17592. */
  17593. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17594. if (includeDescendants === void 0) { includeDescendants = true; }
  17595. this.computeWorldMatrix(true);
  17596. var min;
  17597. var max;
  17598. var boundingInfo = this.getBoundingInfo();
  17599. if (!this.subMeshes) {
  17600. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17601. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17602. }
  17603. else {
  17604. min = boundingInfo.boundingBox.minimumWorld;
  17605. max = boundingInfo.boundingBox.maximumWorld;
  17606. }
  17607. if (includeDescendants) {
  17608. var descendants = this.getDescendants(false);
  17609. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17610. var descendant = descendants_1[_i];
  17611. var childMesh = descendant;
  17612. childMesh.computeWorldMatrix(true);
  17613. //make sure we have the needed params to get mix and max
  17614. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17615. continue;
  17616. }
  17617. var childBoundingInfo = childMesh.getBoundingInfo();
  17618. var boundingBox = childBoundingInfo.boundingBox;
  17619. var minBox = boundingBox.minimumWorld;
  17620. var maxBox = boundingBox.maximumWorld;
  17621. BABYLON.Tools.CheckExtends(minBox, min, max);
  17622. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17623. }
  17624. }
  17625. return {
  17626. min: min,
  17627. max: max
  17628. };
  17629. };
  17630. /**
  17631. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17632. * Returns the AbstractMesh.
  17633. */
  17634. AbstractMesh.prototype._updateBoundingInfo = function () {
  17635. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17636. this._boundingInfo.update(this.worldMatrixFromCache);
  17637. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17638. return this;
  17639. };
  17640. /**
  17641. * Update a mesh's children BoundingInfo objects only.
  17642. * Returns the AbstractMesh.
  17643. */
  17644. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17645. if (!this.subMeshes) {
  17646. return this;
  17647. }
  17648. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17649. var subMesh = this.subMeshes[subIndex];
  17650. if (!subMesh.IsGlobal) {
  17651. subMesh.updateBoundingInfo(matrix);
  17652. }
  17653. }
  17654. return this;
  17655. };
  17656. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17657. // Bounding info
  17658. this._updateBoundingInfo();
  17659. };
  17660. /**
  17661. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17662. * A mesh is in the frustum if its bounding box intersects the frustum.
  17663. * Boolean returned.
  17664. */
  17665. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17666. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17667. };
  17668. /**
  17669. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17670. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17671. * Boolean returned.
  17672. */
  17673. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17674. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17675. ;
  17676. };
  17677. /**
  17678. * True if the mesh intersects another mesh or a SolidParticle object.
  17679. * 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)
  17680. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17681. * Returns a boolean.
  17682. */
  17683. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17684. if (precise === void 0) { precise = false; }
  17685. if (!this._boundingInfo || !mesh._boundingInfo) {
  17686. return false;
  17687. }
  17688. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17689. return true;
  17690. }
  17691. if (includeDescendants) {
  17692. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17693. var child = _a[_i];
  17694. if (child.intersectsMesh(mesh, precise, true)) {
  17695. return true;
  17696. }
  17697. }
  17698. }
  17699. return false;
  17700. };
  17701. /**
  17702. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17703. * Returns a boolean.
  17704. */
  17705. AbstractMesh.prototype.intersectsPoint = function (point) {
  17706. if (!this._boundingInfo) {
  17707. return false;
  17708. }
  17709. return this._boundingInfo.intersectsPoint(point);
  17710. };
  17711. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17712. return this.physicsImpostor;
  17713. };
  17714. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17715. if (camera === void 0) { camera = null; }
  17716. if (!camera) {
  17717. camera = this.getScene().activeCamera;
  17718. }
  17719. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17720. };
  17721. /**
  17722. * Returns the distance from the mesh to the active camera.
  17723. * Returns a float.
  17724. */
  17725. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17726. if (camera === void 0) { camera = null; }
  17727. if (!camera) {
  17728. camera = this.getScene().activeCamera;
  17729. }
  17730. return this.absolutePosition.subtract(camera.position).length();
  17731. };
  17732. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17733. if (!this.physicsImpostor) {
  17734. return this;
  17735. }
  17736. this.physicsImpostor.applyImpulse(force, contactPoint);
  17737. return this;
  17738. };
  17739. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17740. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17741. return this;
  17742. }
  17743. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17744. mainPivot: pivot1,
  17745. connectedPivot: pivot2,
  17746. nativeParams: options
  17747. });
  17748. return this;
  17749. };
  17750. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17751. // Collisions
  17752. /**
  17753. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17754. * Default `false`.
  17755. */
  17756. get: function () {
  17757. return this._checkCollisions;
  17758. },
  17759. set: function (collisionEnabled) {
  17760. this._checkCollisions = collisionEnabled;
  17761. if (this.getScene().workerCollisions) {
  17762. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17763. }
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17769. /**
  17770. * Gets Collider object used to compute collisions (not physics)
  17771. */
  17772. get: function () {
  17773. return this._collider;
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17779. var globalPosition = this.getAbsolutePosition();
  17780. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17781. if (!this._collider) {
  17782. this._collider = new BABYLON.Collider();
  17783. }
  17784. this._collider._radius = this.ellipsoid;
  17785. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17786. return this;
  17787. };
  17788. // Submeshes octree
  17789. /**
  17790. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17791. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17792. * Returns an Octree of submeshes.
  17793. */
  17794. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17795. if (maxCapacity === void 0) { maxCapacity = 64; }
  17796. if (maxDepth === void 0) { maxDepth = 2; }
  17797. if (!this._submeshesOctree) {
  17798. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17799. }
  17800. this.computeWorldMatrix(true);
  17801. var boundingInfo = this.getBoundingInfo();
  17802. // Update octree
  17803. var bbox = boundingInfo.boundingBox;
  17804. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17805. return this._submeshesOctree;
  17806. };
  17807. // Collisions
  17808. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17809. this._generatePointsArray();
  17810. if (!this._positions) {
  17811. return this;
  17812. }
  17813. // Transformation
  17814. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17815. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17816. subMesh._lastColliderWorldVertices = [];
  17817. subMesh._trianglePlanes = [];
  17818. var start = subMesh.verticesStart;
  17819. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17820. for (var i = start; i < end; i++) {
  17821. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17822. }
  17823. }
  17824. // Collide
  17825. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17826. if (collider.collisionFound) {
  17827. collider.collidedMesh = this;
  17828. }
  17829. return this;
  17830. };
  17831. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17832. var subMeshes;
  17833. var len;
  17834. // Octrees
  17835. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17836. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17837. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17838. len = intersections.length;
  17839. subMeshes = intersections.data;
  17840. }
  17841. else {
  17842. subMeshes = this.subMeshes;
  17843. len = subMeshes.length;
  17844. }
  17845. for (var index = 0; index < len; index++) {
  17846. var subMesh = subMeshes[index];
  17847. // Bounding test
  17848. if (len > 1 && !subMesh._checkCollision(collider))
  17849. continue;
  17850. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17851. }
  17852. return this;
  17853. };
  17854. AbstractMesh.prototype._checkCollision = function (collider) {
  17855. // Bounding box test
  17856. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17857. return this;
  17858. // Transformation matrix
  17859. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17860. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17861. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17862. return this;
  17863. };
  17864. // Picking
  17865. AbstractMesh.prototype._generatePointsArray = function () {
  17866. return false;
  17867. };
  17868. /**
  17869. * Checks if the passed Ray intersects with the mesh.
  17870. * Returns an object PickingInfo.
  17871. */
  17872. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17873. var pickingInfo = new BABYLON.PickingInfo();
  17874. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17875. return pickingInfo;
  17876. }
  17877. if (!this._generatePointsArray()) {
  17878. return pickingInfo;
  17879. }
  17880. var intersectInfo = null;
  17881. // Octrees
  17882. var subMeshes;
  17883. var len;
  17884. if (this._submeshesOctree && this.useOctreeForPicking) {
  17885. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17886. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17887. len = intersections.length;
  17888. subMeshes = intersections.data;
  17889. }
  17890. else {
  17891. subMeshes = this.subMeshes;
  17892. len = subMeshes.length;
  17893. }
  17894. for (var index = 0; index < len; index++) {
  17895. var subMesh = subMeshes[index];
  17896. // Bounding test
  17897. if (len > 1 && !subMesh.canIntersects(ray))
  17898. continue;
  17899. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17900. if (currentIntersectInfo) {
  17901. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17902. intersectInfo = currentIntersectInfo;
  17903. intersectInfo.subMeshId = index;
  17904. if (fastCheck) {
  17905. break;
  17906. }
  17907. }
  17908. }
  17909. }
  17910. if (intersectInfo) {
  17911. // Get picked point
  17912. var world = this.getWorldMatrix();
  17913. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17914. var direction = ray.direction.clone();
  17915. direction = direction.scale(intersectInfo.distance);
  17916. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17917. var pickedPoint = worldOrigin.add(worldDirection);
  17918. // Return result
  17919. pickingInfo.hit = true;
  17920. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17921. pickingInfo.pickedPoint = pickedPoint;
  17922. pickingInfo.pickedMesh = this;
  17923. pickingInfo.bu = intersectInfo.bu || 0;
  17924. pickingInfo.bv = intersectInfo.bv || 0;
  17925. pickingInfo.faceId = intersectInfo.faceId;
  17926. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17927. return pickingInfo;
  17928. }
  17929. return pickingInfo;
  17930. };
  17931. /**
  17932. * Clones the mesh, used by the class Mesh.
  17933. * Just returns `null` for an AbstractMesh.
  17934. */
  17935. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17936. return null;
  17937. };
  17938. /**
  17939. * Disposes all the mesh submeshes.
  17940. * Returns the AbstractMesh.
  17941. */
  17942. AbstractMesh.prototype.releaseSubMeshes = function () {
  17943. if (this.subMeshes) {
  17944. while (this.subMeshes.length) {
  17945. this.subMeshes[0].dispose();
  17946. }
  17947. }
  17948. else {
  17949. this.subMeshes = new Array();
  17950. }
  17951. return this;
  17952. };
  17953. /**
  17954. * Disposes the AbstractMesh.
  17955. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17956. * Returns nothing.
  17957. */
  17958. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17959. var _this = this;
  17960. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17961. var index;
  17962. // Action manager
  17963. if (this.actionManager !== undefined && this.actionManager !== null) {
  17964. this.actionManager.dispose();
  17965. this.actionManager = null;
  17966. }
  17967. // Skeleton
  17968. this.skeleton = null;
  17969. // Physics
  17970. if (this.physicsImpostor) {
  17971. this.physicsImpostor.dispose();
  17972. }
  17973. // Intersections in progress
  17974. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17975. var other = this._intersectionsInProgress[index];
  17976. var pos = other._intersectionsInProgress.indexOf(this);
  17977. other._intersectionsInProgress.splice(pos, 1);
  17978. }
  17979. this._intersectionsInProgress = [];
  17980. // Lights
  17981. var lights = this.getScene().lights;
  17982. lights.forEach(function (light) {
  17983. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17984. if (meshIndex !== -1) {
  17985. light.includedOnlyMeshes.splice(meshIndex, 1);
  17986. }
  17987. meshIndex = light.excludedMeshes.indexOf(_this);
  17988. if (meshIndex !== -1) {
  17989. light.excludedMeshes.splice(meshIndex, 1);
  17990. }
  17991. // Shadow generators
  17992. var generator = light.getShadowGenerator();
  17993. if (generator) {
  17994. var shadowMap = generator.getShadowMap();
  17995. if (shadowMap && shadowMap.renderList) {
  17996. meshIndex = shadowMap.renderList.indexOf(_this);
  17997. if (meshIndex !== -1) {
  17998. shadowMap.renderList.splice(meshIndex, 1);
  17999. }
  18000. }
  18001. }
  18002. });
  18003. // Edges
  18004. if (this._edgesRenderer) {
  18005. this._edgesRenderer.dispose();
  18006. this._edgesRenderer = null;
  18007. }
  18008. // SubMeshes
  18009. if (this.getClassName() !== "InstancedMesh") {
  18010. this.releaseSubMeshes();
  18011. }
  18012. // Octree
  18013. var sceneOctree = this.getScene().selectionOctree;
  18014. if (sceneOctree !== undefined && sceneOctree !== null) {
  18015. var index = sceneOctree.dynamicContent.indexOf(this);
  18016. if (index !== -1) {
  18017. sceneOctree.dynamicContent.splice(index, 1);
  18018. }
  18019. }
  18020. // Query
  18021. var engine = this.getScene().getEngine();
  18022. if (this._occlusionQuery) {
  18023. this._isOcclusionQueryInProgress = false;
  18024. engine.deleteQuery(this._occlusionQuery);
  18025. this._occlusionQuery = null;
  18026. }
  18027. // Engine
  18028. engine.wipeCaches();
  18029. // Remove from scene
  18030. this.getScene().removeMesh(this);
  18031. if (disposeMaterialAndTextures) {
  18032. if (this.material) {
  18033. this.material.dispose(false, true);
  18034. }
  18035. }
  18036. if (!doNotRecurse) {
  18037. // Particles
  18038. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18039. if (this.getScene().particleSystems[index].emitter === this) {
  18040. this.getScene().particleSystems[index].dispose();
  18041. index--;
  18042. }
  18043. }
  18044. }
  18045. // facet data
  18046. if (this._facetDataEnabled) {
  18047. this.disableFacetData();
  18048. }
  18049. this.onAfterWorldMatrixUpdateObservable.clear();
  18050. this.onCollideObservable.clear();
  18051. this.onCollisionPositionChangeObservable.clear();
  18052. _super.prototype.dispose.call(this, doNotRecurse);
  18053. };
  18054. /**
  18055. * Adds the passed mesh as a child to the current mesh.
  18056. * Returns the AbstractMesh.
  18057. */
  18058. AbstractMesh.prototype.addChild = function (mesh) {
  18059. mesh.setParent(this);
  18060. return this;
  18061. };
  18062. /**
  18063. * Removes the passed mesh from the current mesh children list.
  18064. * Returns the AbstractMesh.
  18065. */
  18066. AbstractMesh.prototype.removeChild = function (mesh) {
  18067. mesh.setParent(null);
  18068. return this;
  18069. };
  18070. // Facet data
  18071. /**
  18072. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18073. * Returns the AbstractMesh.
  18074. */
  18075. AbstractMesh.prototype._initFacetData = function () {
  18076. if (!this._facetNormals) {
  18077. this._facetNormals = new Array();
  18078. }
  18079. if (!this._facetPositions) {
  18080. this._facetPositions = new Array();
  18081. }
  18082. if (!this._facetPartitioning) {
  18083. this._facetPartitioning = new Array();
  18084. }
  18085. this._facetNb = (this.getIndices().length / 3) | 0;
  18086. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18087. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18088. for (var f = 0; f < this._facetNb; f++) {
  18089. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18090. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18091. }
  18092. this._facetDataEnabled = true;
  18093. return this;
  18094. };
  18095. /**
  18096. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18097. * This method can be called within the render loop.
  18098. * 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.
  18099. * Returns the AbstractMesh.
  18100. */
  18101. AbstractMesh.prototype.updateFacetData = function () {
  18102. if (!this._facetDataEnabled) {
  18103. this._initFacetData();
  18104. }
  18105. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18106. var indices = this.getIndices();
  18107. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18108. var bInfo = this.getBoundingInfo();
  18109. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18110. // init arrays, matrix and sort function on first call
  18111. this._facetDepthSortEnabled = true;
  18112. if (indices instanceof Uint16Array) {
  18113. this._depthSortedIndices = new Uint16Array(indices);
  18114. }
  18115. else if (indices instanceof Uint32Array) {
  18116. this._depthSortedIndices = new Uint32Array(indices);
  18117. }
  18118. else {
  18119. var needs32bits = false;
  18120. for (var i = 0; i < indices.length; i++) {
  18121. if (indices[i] > 65535) {
  18122. needs32bits = true;
  18123. break;
  18124. }
  18125. }
  18126. if (needs32bits) {
  18127. this._depthSortedIndices = new Uint32Array(indices);
  18128. }
  18129. else {
  18130. this._depthSortedIndices = new Uint16Array(indices);
  18131. }
  18132. }
  18133. this._facetDepthSortFunction = function (f1, f2) {
  18134. return (f2.sqDistance - f1.sqDistance);
  18135. };
  18136. if (!this._facetDepthSortFrom) {
  18137. var camera = this.getScene().activeCamera;
  18138. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18139. }
  18140. this._depthSortedFacets = [];
  18141. for (var f = 0; f < this._facetNb; f++) {
  18142. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18143. this._depthSortedFacets.push(depthSortedFacet);
  18144. }
  18145. this._invertedMatrix = BABYLON.Matrix.Identity();
  18146. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18147. }
  18148. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18149. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18150. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18151. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18152. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18153. this._subDiv.max = this._partitioningSubdivisions;
  18154. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18155. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18156. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18157. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18158. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18159. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18160. // set the parameters for ComputeNormals()
  18161. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18162. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18163. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18164. this._facetParameters.bInfo = bInfo;
  18165. this._facetParameters.bbSize = this._bbSize;
  18166. this._facetParameters.subDiv = this._subDiv;
  18167. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18168. this._facetParameters.depthSort = this._facetDepthSort;
  18169. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18170. this.computeWorldMatrix(true);
  18171. this._worldMatrix.invertToRef(this._invertedMatrix);
  18172. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18173. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18174. }
  18175. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18176. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18177. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18178. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18179. var l = (this._depthSortedIndices.length / 3) | 0;
  18180. for (var f = 0; f < l; f++) {
  18181. var sind = this._depthSortedFacets[f].ind;
  18182. this._depthSortedIndices[f * 3] = indices[sind];
  18183. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18184. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18185. }
  18186. this.updateIndices(this._depthSortedIndices);
  18187. }
  18188. return this;
  18189. };
  18190. /**
  18191. * Returns the facetLocalNormals array.
  18192. * The normals are expressed in the mesh local space.
  18193. */
  18194. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18195. if (!this._facetNormals) {
  18196. this.updateFacetData();
  18197. }
  18198. return this._facetNormals;
  18199. };
  18200. /**
  18201. * Returns the facetLocalPositions array.
  18202. * The facet positions are expressed in the mesh local space.
  18203. */
  18204. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18205. if (!this._facetPositions) {
  18206. this.updateFacetData();
  18207. }
  18208. return this._facetPositions;
  18209. };
  18210. /**
  18211. * Returns the facetLocalPartioning array.
  18212. */
  18213. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18214. if (!this._facetPartitioning) {
  18215. this.updateFacetData();
  18216. }
  18217. return this._facetPartitioning;
  18218. };
  18219. /**
  18220. * Returns the i-th facet position in the world system.
  18221. * This method allocates a new Vector3 per call.
  18222. */
  18223. AbstractMesh.prototype.getFacetPosition = function (i) {
  18224. var pos = BABYLON.Vector3.Zero();
  18225. this.getFacetPositionToRef(i, pos);
  18226. return pos;
  18227. };
  18228. /**
  18229. * Sets the reference Vector3 with the i-th facet position in the world system.
  18230. * Returns the AbstractMesh.
  18231. */
  18232. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18233. var localPos = (this.getFacetLocalPositions())[i];
  18234. var world = this.getWorldMatrix();
  18235. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18236. return this;
  18237. };
  18238. /**
  18239. * Returns the i-th facet normal in the world system.
  18240. * This method allocates a new Vector3 per call.
  18241. */
  18242. AbstractMesh.prototype.getFacetNormal = function (i) {
  18243. var norm = BABYLON.Vector3.Zero();
  18244. this.getFacetNormalToRef(i, norm);
  18245. return norm;
  18246. };
  18247. /**
  18248. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18249. * Returns the AbstractMesh.
  18250. */
  18251. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18252. var localNorm = (this.getFacetLocalNormals())[i];
  18253. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18254. return this;
  18255. };
  18256. /**
  18257. * 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).
  18258. */
  18259. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18260. var bInfo = this.getBoundingInfo();
  18261. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18262. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18263. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18264. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18265. return null;
  18266. }
  18267. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18268. };
  18269. /**
  18270. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18271. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18272. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18273. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18274. * 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.
  18275. */
  18276. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18277. if (checkFace === void 0) { checkFace = false; }
  18278. if (facing === void 0) { facing = true; }
  18279. var world = this.getWorldMatrix();
  18280. var invMat = BABYLON.Tmp.Matrix[5];
  18281. world.invertToRef(invMat);
  18282. var invVect = BABYLON.Tmp.Vector3[8];
  18283. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18284. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18285. if (projected) {
  18286. // tranform the local computed projected vector to world coordinates
  18287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18288. }
  18289. return closest;
  18290. };
  18291. /**
  18292. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18293. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18294. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18295. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18296. * 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.
  18297. */
  18298. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18299. if (checkFace === void 0) { checkFace = false; }
  18300. if (facing === void 0) { facing = true; }
  18301. var closest = null;
  18302. var tmpx = 0.0;
  18303. var tmpy = 0.0;
  18304. var tmpz = 0.0;
  18305. var d = 0.0; // tmp dot facet normal * facet position
  18306. var t0 = 0.0;
  18307. var projx = 0.0;
  18308. var projy = 0.0;
  18309. var projz = 0.0;
  18310. // Get all the facets in the same partitioning block than (x, y, z)
  18311. var facetPositions = this.getFacetLocalPositions();
  18312. var facetNormals = this.getFacetLocalNormals();
  18313. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18314. if (!facetsInBlock) {
  18315. return null;
  18316. }
  18317. // Get the closest facet to (x, y, z)
  18318. var shortest = Number.MAX_VALUE; // init distance vars
  18319. var tmpDistance = shortest;
  18320. var fib; // current facet in the block
  18321. var norm; // current facet normal
  18322. var p0; // current facet barycenter position
  18323. // loop on all the facets in the current partitioning block
  18324. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18325. fib = facetsInBlock[idx];
  18326. norm = facetNormals[fib];
  18327. p0 = facetPositions[fib];
  18328. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18329. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18330. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18331. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18332. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18333. projx = x + norm.x * t0;
  18334. projy = y + norm.y * t0;
  18335. projz = z + norm.z * t0;
  18336. tmpx = projx - x;
  18337. tmpy = projy - y;
  18338. tmpz = projz - z;
  18339. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18340. if (tmpDistance < shortest) {
  18341. shortest = tmpDistance;
  18342. closest = fib;
  18343. if (projected) {
  18344. projected.x = projx;
  18345. projected.y = projy;
  18346. projected.z = projz;
  18347. }
  18348. }
  18349. }
  18350. }
  18351. return closest;
  18352. };
  18353. /**
  18354. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18355. */
  18356. AbstractMesh.prototype.getFacetDataParameters = function () {
  18357. return this._facetParameters;
  18358. };
  18359. /**
  18360. * Disables the feature FacetData and frees the related memory.
  18361. * Returns the AbstractMesh.
  18362. */
  18363. AbstractMesh.prototype.disableFacetData = function () {
  18364. if (this._facetDataEnabled) {
  18365. this._facetDataEnabled = false;
  18366. this._facetPositions = new Array();
  18367. this._facetNormals = new Array();
  18368. this._facetPartitioning = new Array();
  18369. this._facetParameters = null;
  18370. this._depthSortedIndices = new Uint32Array(0);
  18371. }
  18372. return this;
  18373. };
  18374. /**
  18375. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18376. * Returns the mesh.
  18377. */
  18378. AbstractMesh.prototype.updateIndices = function (indices) {
  18379. return this;
  18380. };
  18381. /**
  18382. * The mesh Geometry. Actually used by the Mesh object.
  18383. * Returns a blank geometry object.
  18384. */
  18385. /**
  18386. * Creates new normals data for the mesh.
  18387. * @param updatable.
  18388. */
  18389. AbstractMesh.prototype.createNormals = function (updatable) {
  18390. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18391. var indices = this.getIndices();
  18392. var normals;
  18393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18394. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18395. }
  18396. else {
  18397. normals = [];
  18398. }
  18399. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18400. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18401. };
  18402. /**
  18403. * Align the mesh with a normal.
  18404. * Returns the mesh.
  18405. */
  18406. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18407. if (!upDirection) {
  18408. upDirection = BABYLON.Axis.Y;
  18409. }
  18410. var axisX = BABYLON.Tmp.Vector3[0];
  18411. var axisZ = BABYLON.Tmp.Vector3[1];
  18412. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18413. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18414. if (this.rotationQuaternion) {
  18415. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18416. }
  18417. else {
  18418. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18419. }
  18420. return this;
  18421. };
  18422. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18423. var engine = this.getEngine();
  18424. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18425. this._isOccluded = false;
  18426. return;
  18427. }
  18428. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18429. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18430. if (isOcclusionQueryAvailable) {
  18431. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18432. this._isOcclusionQueryInProgress = false;
  18433. this._occlusionInternalRetryCounter = 0;
  18434. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18435. }
  18436. else {
  18437. this._occlusionInternalRetryCounter++;
  18438. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18439. this._isOcclusionQueryInProgress = false;
  18440. this._occlusionInternalRetryCounter = 0;
  18441. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18442. // if strict continue the last state of the object.
  18443. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18444. }
  18445. else {
  18446. return;
  18447. }
  18448. }
  18449. }
  18450. var scene = this.getScene();
  18451. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18452. if (!this._occlusionQuery) {
  18453. this._occlusionQuery = engine.createQuery();
  18454. }
  18455. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18456. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18457. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18458. this._isOcclusionQueryInProgress = true;
  18459. };
  18460. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18461. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18462. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18463. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18464. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18465. return AbstractMesh;
  18466. }(BABYLON.TransformNode));
  18467. BABYLON.AbstractMesh = AbstractMesh;
  18468. })(BABYLON || (BABYLON = {}));
  18469. //# sourceMappingURL=babylon.abstractMesh.js.map
  18470. var BABYLON;
  18471. (function (BABYLON) {
  18472. /**
  18473. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18474. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18475. * 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.
  18476. */
  18477. var Light = /** @class */ (function (_super) {
  18478. __extends(Light, _super);
  18479. /**
  18480. * Creates a Light object in the scene.
  18481. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18482. * @param name The firendly name of the light
  18483. * @param scene The scene the light belongs too
  18484. */
  18485. function Light(name, scene) {
  18486. var _this = _super.call(this, name, scene) || this;
  18487. /**
  18488. * Diffuse gives the basic color to an object.
  18489. */
  18490. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18491. /**
  18492. * Specular produces a highlight color on an object.
  18493. * Note: This is note affecting PBR materials.
  18494. */
  18495. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18496. /**
  18497. * Strength of the light.
  18498. * Note: By default it is define in the framework own unit.
  18499. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18500. */
  18501. _this.intensity = 1.0;
  18502. /**
  18503. * Defines how far from the source the light is impacting in scene units.
  18504. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18505. */
  18506. _this.range = Number.MAX_VALUE;
  18507. /**
  18508. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18509. * of light.
  18510. */
  18511. _this._photometricScale = 1.0;
  18512. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18513. _this._radius = 0.00001;
  18514. /**
  18515. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18516. * exceeding the number allowed of the materials.
  18517. */
  18518. _this.renderPriority = 0;
  18519. /**
  18520. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18521. * the current shadow generator.
  18522. */
  18523. _this.shadowEnabled = true;
  18524. _this._excludeWithLayerMask = 0;
  18525. _this._includeOnlyWithLayerMask = 0;
  18526. _this._lightmapMode = 0;
  18527. /**
  18528. * @ignore Internal use only.
  18529. */
  18530. _this._excludedMeshesIds = new Array();
  18531. /**
  18532. * @ignore Internal use only.
  18533. */
  18534. _this._includedOnlyMeshesIds = new Array();
  18535. _this.getScene().addLight(_this);
  18536. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18537. _this._buildUniformLayout();
  18538. _this.includedOnlyMeshes = new Array();
  18539. _this.excludedMeshes = new Array();
  18540. _this._resyncMeshes();
  18541. return _this;
  18542. }
  18543. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18544. /**
  18545. * If every light affecting the material is in this lightmapMode,
  18546. * material.lightmapTexture adds or multiplies
  18547. * (depends on material.useLightmapAsShadowmap)
  18548. * after every other light calculations.
  18549. */
  18550. get: function () {
  18551. return Light._LIGHTMAP_DEFAULT;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18557. /**
  18558. * material.lightmapTexture as only diffuse lighting from this light
  18559. * adds only specular lighting from this light
  18560. * adds dynamic shadows
  18561. */
  18562. get: function () {
  18563. return Light._LIGHTMAP_SPECULAR;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18569. /**
  18570. * material.lightmapTexture as only lighting
  18571. * no light calculation from this light
  18572. * only adds dynamic shadows from this light
  18573. */
  18574. get: function () {
  18575. return Light._LIGHTMAP_SHADOWSONLY;
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18581. /**
  18582. * Each light type uses the default quantity according to its type:
  18583. * point/spot lights use luminous intensity
  18584. * directional lights use illuminance
  18585. */
  18586. get: function () {
  18587. return Light._INTENSITYMODE_AUTOMATIC;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18593. /**
  18594. * lumen (lm)
  18595. */
  18596. get: function () {
  18597. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18598. },
  18599. enumerable: true,
  18600. configurable: true
  18601. });
  18602. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18603. /**
  18604. * candela (lm/sr)
  18605. */
  18606. get: function () {
  18607. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18613. /**
  18614. * lux (lm/m^2)
  18615. */
  18616. get: function () {
  18617. return Light._INTENSITYMODE_ILLUMINANCE;
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18623. /**
  18624. * nit (cd/m^2)
  18625. */
  18626. get: function () {
  18627. return Light._INTENSITYMODE_LUMINANCE;
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18633. /**
  18634. * Light type const id of the point light.
  18635. */
  18636. get: function () {
  18637. return Light._LIGHTTYPEID_POINTLIGHT;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18643. /**
  18644. * Light type const id of the directional light.
  18645. */
  18646. get: function () {
  18647. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18653. /**
  18654. * Light type const id of the spot light.
  18655. */
  18656. get: function () {
  18657. return Light._LIGHTTYPEID_SPOTLIGHT;
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18663. /**
  18664. * Light type const id of the hemispheric light.
  18665. */
  18666. get: function () {
  18667. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(Light.prototype, "intensityMode", {
  18673. /**
  18674. * Gets the photometric scale used to interpret the intensity.
  18675. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18676. */
  18677. get: function () {
  18678. return this._intensityMode;
  18679. },
  18680. /**
  18681. * Sets the photometric scale used to interpret the intensity.
  18682. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18683. */
  18684. set: function (value) {
  18685. this._intensityMode = value;
  18686. this._computePhotometricScale();
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. ;
  18692. ;
  18693. Object.defineProperty(Light.prototype, "radius", {
  18694. /**
  18695. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18696. */
  18697. get: function () {
  18698. return this._radius;
  18699. },
  18700. /**
  18701. * sets the light radius used by PBR Materials to simulate soft area lights.
  18702. */
  18703. set: function (value) {
  18704. this._radius = value;
  18705. this._computePhotometricScale();
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. ;
  18711. ;
  18712. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18713. /**
  18714. * Gets the only meshes impacted by this light.
  18715. */
  18716. get: function () {
  18717. return this._includedOnlyMeshes;
  18718. },
  18719. /**
  18720. * Sets the only meshes impacted by this light.
  18721. */
  18722. set: function (value) {
  18723. this._includedOnlyMeshes = value;
  18724. this._hookArrayForIncludedOnly(value);
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18730. /**
  18731. * Gets the meshes not impacted by this light.
  18732. */
  18733. get: function () {
  18734. return this._excludedMeshes;
  18735. },
  18736. /**
  18737. * Sets the meshes not impacted by this light.
  18738. */
  18739. set: function (value) {
  18740. this._excludedMeshes = value;
  18741. this._hookArrayForExcluded(value);
  18742. },
  18743. enumerable: true,
  18744. configurable: true
  18745. });
  18746. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18747. /**
  18748. * Gets the layer id use to find what meshes are not impacted by the light.
  18749. * Inactive if 0
  18750. */
  18751. get: function () {
  18752. return this._excludeWithLayerMask;
  18753. },
  18754. /**
  18755. * Sets the layer id use to find what meshes are not impacted by the light.
  18756. * Inactive if 0
  18757. */
  18758. set: function (value) {
  18759. this._excludeWithLayerMask = value;
  18760. this._resyncMeshes();
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18766. /**
  18767. * Gets the layer id use to find what meshes are impacted by the light.
  18768. * Inactive if 0
  18769. */
  18770. get: function () {
  18771. return this._includeOnlyWithLayerMask;
  18772. },
  18773. /**
  18774. * Sets the layer id use to find what meshes are impacted by the light.
  18775. * Inactive if 0
  18776. */
  18777. set: function (value) {
  18778. this._includeOnlyWithLayerMask = value;
  18779. this._resyncMeshes();
  18780. },
  18781. enumerable: true,
  18782. configurable: true
  18783. });
  18784. Object.defineProperty(Light.prototype, "lightmapMode", {
  18785. /**
  18786. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18787. */
  18788. get: function () {
  18789. return this._lightmapMode;
  18790. },
  18791. /**
  18792. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18793. */
  18794. set: function (value) {
  18795. if (this._lightmapMode === value) {
  18796. return;
  18797. }
  18798. this._lightmapMode = value;
  18799. this._markMeshesAsLightDirty();
  18800. },
  18801. enumerable: true,
  18802. configurable: true
  18803. });
  18804. /**
  18805. * Returns the string "Light".
  18806. * @returns the class name
  18807. */
  18808. Light.prototype.getClassName = function () {
  18809. return "Light";
  18810. };
  18811. /**
  18812. * Converts the light information to a readable string for debug purpose.
  18813. * @param fullDetails Supports for multiple levels of logging within scene loading
  18814. * @returns the human readable light info
  18815. */
  18816. Light.prototype.toString = function (fullDetails) {
  18817. var ret = "Name: " + this.name;
  18818. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18819. if (this.animations) {
  18820. for (var i = 0; i < this.animations.length; i++) {
  18821. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18822. }
  18823. }
  18824. if (fullDetails) {
  18825. }
  18826. return ret;
  18827. };
  18828. /**
  18829. * Set the enabled state of this node.
  18830. * @param value - the new enabled state
  18831. * @see isEnabled
  18832. */
  18833. Light.prototype.setEnabled = function (value) {
  18834. _super.prototype.setEnabled.call(this, value);
  18835. this._resyncMeshes();
  18836. };
  18837. /**
  18838. * Returns the Light associated shadow generator if any.
  18839. * @return the associated shadow generator.
  18840. */
  18841. Light.prototype.getShadowGenerator = function () {
  18842. return this._shadowGenerator;
  18843. };
  18844. /**
  18845. * Returns a Vector3, the absolute light position in the World.
  18846. * @returns the world space position of the light
  18847. */
  18848. Light.prototype.getAbsolutePosition = function () {
  18849. return BABYLON.Vector3.Zero();
  18850. };
  18851. /**
  18852. * Specifies if the light will affect the passed mesh.
  18853. * @param mesh The mesh to test against the light
  18854. * @return true the mesh is affected otherwise, false.
  18855. */
  18856. Light.prototype.canAffectMesh = function (mesh) {
  18857. if (!mesh) {
  18858. return true;
  18859. }
  18860. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18861. return false;
  18862. }
  18863. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18864. return false;
  18865. }
  18866. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18867. return false;
  18868. }
  18869. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18870. return false;
  18871. }
  18872. return true;
  18873. };
  18874. /**
  18875. * Computes and Returns the light World matrix.
  18876. * @returns the world matrix
  18877. */
  18878. Light.prototype.getWorldMatrix = function () {
  18879. this._currentRenderId = this.getScene().getRenderId();
  18880. var worldMatrix = this._getWorldMatrix();
  18881. if (this.parent && this.parent.getWorldMatrix) {
  18882. if (!this._parentedWorldMatrix) {
  18883. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18884. }
  18885. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18886. this._markSyncedWithParent();
  18887. return this._parentedWorldMatrix;
  18888. }
  18889. return worldMatrix;
  18890. };
  18891. /**
  18892. * Sort function to order lights for rendering.
  18893. * @param a First Light object to compare to second.
  18894. * @param b Second Light object to compare first.
  18895. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18896. */
  18897. Light.CompareLightsPriority = function (a, b) {
  18898. //shadow-casting lights have priority over non-shadow-casting lights
  18899. //the renderPrioirty is a secondary sort criterion
  18900. if (a.shadowEnabled !== b.shadowEnabled) {
  18901. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18902. }
  18903. return b.renderPriority - a.renderPriority;
  18904. };
  18905. /**
  18906. * Disposes the light.
  18907. */
  18908. Light.prototype.dispose = function () {
  18909. if (this._shadowGenerator) {
  18910. this._shadowGenerator.dispose();
  18911. this._shadowGenerator = null;
  18912. }
  18913. // Animations
  18914. this.getScene().stopAnimation(this);
  18915. // Remove from meshes
  18916. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18917. var mesh = _a[_i];
  18918. mesh._removeLightSource(this);
  18919. }
  18920. this._uniformBuffer.dispose();
  18921. // Remove from scene
  18922. this.getScene().removeLight(this);
  18923. _super.prototype.dispose.call(this);
  18924. };
  18925. /**
  18926. * Returns the light type ID (integer).
  18927. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18928. */
  18929. Light.prototype.getTypeID = function () {
  18930. return 0;
  18931. };
  18932. /**
  18933. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18934. * @returns the scaled intensity in intensity mode unit
  18935. */
  18936. Light.prototype.getScaledIntensity = function () {
  18937. return this._photometricScale * this.intensity;
  18938. };
  18939. /**
  18940. * Returns a new Light object, named "name", from the current one.
  18941. * @param name The name of the cloned light
  18942. * @returns the new created light
  18943. */
  18944. Light.prototype.clone = function (name) {
  18945. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18946. if (!constructor) {
  18947. return null;
  18948. }
  18949. return BABYLON.SerializationHelper.Clone(constructor, this);
  18950. };
  18951. /**
  18952. * Serializes the current light into a Serialization object.
  18953. * @returns the serialized object.
  18954. */
  18955. Light.prototype.serialize = function () {
  18956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18957. // Type
  18958. serializationObject.type = this.getTypeID();
  18959. // Parent
  18960. if (this.parent) {
  18961. serializationObject.parentId = this.parent.id;
  18962. }
  18963. // Inclusion / exclusions
  18964. if (this.excludedMeshes.length > 0) {
  18965. serializationObject.excludedMeshesIds = [];
  18966. this.excludedMeshes.forEach(function (mesh) {
  18967. serializationObject.excludedMeshesIds.push(mesh.id);
  18968. });
  18969. }
  18970. if (this.includedOnlyMeshes.length > 0) {
  18971. serializationObject.includedOnlyMeshesIds = [];
  18972. this.includedOnlyMeshes.forEach(function (mesh) {
  18973. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18974. });
  18975. }
  18976. // Animations
  18977. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18978. serializationObject.ranges = this.serializeAnimationRanges();
  18979. return serializationObject;
  18980. };
  18981. /**
  18982. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18983. * This new light is named "name" and added to the passed scene.
  18984. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18985. * @param name The friendly name of the light
  18986. * @param scene The scene the new light will belong to
  18987. * @returns the constructor function
  18988. */
  18989. Light.GetConstructorFromName = function (type, name, scene) {
  18990. switch (type) {
  18991. case 0:
  18992. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18993. case 1:
  18994. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18995. case 2:
  18996. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18997. case 3:
  18998. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18999. }
  19000. return null;
  19001. };
  19002. /**
  19003. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19004. * @param parsedLight The JSON representation of the light
  19005. * @param scene The scene to create the parsed light in
  19006. * @returns the created light after parsing
  19007. */
  19008. Light.Parse = function (parsedLight, scene) {
  19009. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19010. if (!constructor) {
  19011. return null;
  19012. }
  19013. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19014. // Inclusion / exclusions
  19015. if (parsedLight.excludedMeshesIds) {
  19016. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19017. }
  19018. if (parsedLight.includedOnlyMeshesIds) {
  19019. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19020. }
  19021. // Parent
  19022. if (parsedLight.parentId) {
  19023. light._waitingParentId = parsedLight.parentId;
  19024. }
  19025. // Animations
  19026. if (parsedLight.animations) {
  19027. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19028. var parsedAnimation = parsedLight.animations[animationIndex];
  19029. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19030. }
  19031. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19032. }
  19033. if (parsedLight.autoAnimate) {
  19034. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19035. }
  19036. return light;
  19037. };
  19038. Light.prototype._hookArrayForExcluded = function (array) {
  19039. var _this = this;
  19040. var oldPush = array.push;
  19041. array.push = function () {
  19042. var items = [];
  19043. for (var _i = 0; _i < arguments.length; _i++) {
  19044. items[_i] = arguments[_i];
  19045. }
  19046. var result = oldPush.apply(array, items);
  19047. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19048. var item = items_1[_a];
  19049. item._resyncLighSource(_this);
  19050. }
  19051. return result;
  19052. };
  19053. var oldSplice = array.splice;
  19054. array.splice = function (index, deleteCount) {
  19055. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19056. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19057. var item = deleted_1[_i];
  19058. item._resyncLighSource(_this);
  19059. }
  19060. return deleted;
  19061. };
  19062. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19063. var item = array_1[_i];
  19064. item._resyncLighSource(this);
  19065. }
  19066. };
  19067. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19068. var _this = this;
  19069. var oldPush = array.push;
  19070. array.push = function () {
  19071. var items = [];
  19072. for (var _i = 0; _i < arguments.length; _i++) {
  19073. items[_i] = arguments[_i];
  19074. }
  19075. var result = oldPush.apply(array, items);
  19076. _this._resyncMeshes();
  19077. return result;
  19078. };
  19079. var oldSplice = array.splice;
  19080. array.splice = function (index, deleteCount) {
  19081. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19082. _this._resyncMeshes();
  19083. return deleted;
  19084. };
  19085. this._resyncMeshes();
  19086. };
  19087. Light.prototype._resyncMeshes = function () {
  19088. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19089. var mesh = _a[_i];
  19090. mesh._resyncLighSource(this);
  19091. }
  19092. };
  19093. /**
  19094. * Forces the meshes to update their light related information in their rendering used effects
  19095. * @ignore Internal Use Only
  19096. */
  19097. Light.prototype._markMeshesAsLightDirty = function () {
  19098. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19099. var mesh = _a[_i];
  19100. if (mesh._lightSources.indexOf(this) !== -1) {
  19101. mesh._markSubMeshesAsLightDirty();
  19102. }
  19103. }
  19104. };
  19105. /**
  19106. * Recomputes the cached photometric scale if needed.
  19107. */
  19108. Light.prototype._computePhotometricScale = function () {
  19109. this._photometricScale = this._getPhotometricScale();
  19110. this.getScene().resetCachedMaterial();
  19111. };
  19112. /**
  19113. * Returns the Photometric Scale according to the light type and intensity mode.
  19114. */
  19115. Light.prototype._getPhotometricScale = function () {
  19116. var photometricScale = 0.0;
  19117. var lightTypeID = this.getTypeID();
  19118. //get photometric mode
  19119. var photometricMode = this.intensityMode;
  19120. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19121. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19122. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19123. }
  19124. else {
  19125. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19126. }
  19127. }
  19128. //compute photometric scale
  19129. switch (lightTypeID) {
  19130. case Light.LIGHTTYPEID_POINTLIGHT:
  19131. case Light.LIGHTTYPEID_SPOTLIGHT:
  19132. switch (photometricMode) {
  19133. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19134. photometricScale = 1.0 / (4.0 * Math.PI);
  19135. break;
  19136. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19137. photometricScale = 1.0;
  19138. break;
  19139. case Light.INTENSITYMODE_LUMINANCE:
  19140. photometricScale = this.radius * this.radius;
  19141. break;
  19142. }
  19143. break;
  19144. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19145. switch (photometricMode) {
  19146. case Light.INTENSITYMODE_ILLUMINANCE:
  19147. photometricScale = 1.0;
  19148. break;
  19149. case Light.INTENSITYMODE_LUMINANCE:
  19150. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19151. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19152. var apexAngleRadians = this.radius;
  19153. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19154. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19155. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19156. photometricScale = solidAngle;
  19157. break;
  19158. }
  19159. break;
  19160. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19161. // No fall off in hemisperic light.
  19162. photometricScale = 1.0;
  19163. break;
  19164. }
  19165. return photometricScale;
  19166. };
  19167. /**
  19168. * Reorder the light in the scene according to their defined priority.
  19169. * @ignore Internal Use Only
  19170. */
  19171. Light.prototype._reorderLightsInScene = function () {
  19172. var scene = this.getScene();
  19173. if (this._renderPriority != 0) {
  19174. scene.requireLightSorting = true;
  19175. }
  19176. this.getScene().sortLightsByPriority();
  19177. };
  19178. //lightmapMode Consts
  19179. Light._LIGHTMAP_DEFAULT = 0;
  19180. Light._LIGHTMAP_SPECULAR = 1;
  19181. Light._LIGHTMAP_SHADOWSONLY = 2;
  19182. // Intensity Mode Consts
  19183. Light._INTENSITYMODE_AUTOMATIC = 0;
  19184. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19185. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19186. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19187. Light._INTENSITYMODE_LUMINANCE = 4;
  19188. // Light types ids const.
  19189. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19190. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19191. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19192. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19193. __decorate([
  19194. BABYLON.serializeAsColor3()
  19195. ], Light.prototype, "diffuse", void 0);
  19196. __decorate([
  19197. BABYLON.serializeAsColor3()
  19198. ], Light.prototype, "specular", void 0);
  19199. __decorate([
  19200. BABYLON.serialize()
  19201. ], Light.prototype, "intensity", void 0);
  19202. __decorate([
  19203. BABYLON.serialize()
  19204. ], Light.prototype, "range", void 0);
  19205. __decorate([
  19206. BABYLON.serialize()
  19207. ], Light.prototype, "intensityMode", null);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], Light.prototype, "radius", null);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], Light.prototype, "_renderPriority", void 0);
  19214. __decorate([
  19215. BABYLON.expandToProperty("_reorderLightsInScene")
  19216. ], Light.prototype, "renderPriority", void 0);
  19217. __decorate([
  19218. BABYLON.serialize()
  19219. ], Light.prototype, "shadowEnabled", void 0);
  19220. __decorate([
  19221. BABYLON.serialize("excludeWithLayerMask")
  19222. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19223. __decorate([
  19224. BABYLON.serialize("includeOnlyWithLayerMask")
  19225. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19226. __decorate([
  19227. BABYLON.serialize("lightmapMode")
  19228. ], Light.prototype, "_lightmapMode", void 0);
  19229. return Light;
  19230. }(BABYLON.Node));
  19231. BABYLON.Light = Light;
  19232. })(BABYLON || (BABYLON = {}));
  19233. //# sourceMappingURL=babylon.light.js.map
  19234. var BABYLON;
  19235. (function (BABYLON) {
  19236. var Camera = /** @class */ (function (_super) {
  19237. __extends(Camera, _super);
  19238. function Camera(name, position, scene) {
  19239. var _this = _super.call(this, name, scene) || this;
  19240. /**
  19241. * The vector the camera should consider as up.
  19242. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19243. */
  19244. _this.upVector = BABYLON.Vector3.Up();
  19245. _this.orthoLeft = null;
  19246. _this.orthoRight = null;
  19247. _this.orthoBottom = null;
  19248. _this.orthoTop = null;
  19249. /**
  19250. * FOV is set in Radians. (default is 0.8)
  19251. */
  19252. _this.fov = 0.8;
  19253. _this.minZ = 1;
  19254. _this.maxZ = 10000.0;
  19255. _this.inertia = 0.9;
  19256. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19257. _this.isIntermediate = false;
  19258. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19259. /**
  19260. * Restricts the camera to viewing objects with the same layerMask.
  19261. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19262. */
  19263. _this.layerMask = 0x0FFFFFFF;
  19264. /**
  19265. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19266. */
  19267. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19268. // Camera rig members
  19269. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19270. _this._rigCameras = new Array();
  19271. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19272. _this._skipRendering = false;
  19273. _this.customRenderTargets = new Array();
  19274. // Observables
  19275. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19276. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19277. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19278. _this.onRestoreStateObservable = new BABYLON.Observable();
  19279. // Cache
  19280. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19281. _this._projectionMatrix = new BABYLON.Matrix();
  19282. _this._doNotComputeProjectionMatrix = false;
  19283. _this._postProcesses = new Array();
  19284. _this._transformMatrix = BABYLON.Matrix.Zero();
  19285. _this._activeMeshes = new BABYLON.SmartArray(256);
  19286. _this._globalPosition = BABYLON.Vector3.Zero();
  19287. _this._refreshFrustumPlanes = true;
  19288. _this.getScene().addCamera(_this);
  19289. if (!_this.getScene().activeCamera) {
  19290. _this.getScene().activeCamera = _this;
  19291. }
  19292. _this.position = position;
  19293. return _this;
  19294. }
  19295. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19296. get: function () {
  19297. return Camera._PERSPECTIVE_CAMERA;
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19303. get: function () {
  19304. return Camera._ORTHOGRAPHIC_CAMERA;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19310. /**
  19311. * This is the default FOV mode for perspective cameras.
  19312. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19313. *
  19314. */
  19315. get: function () {
  19316. return Camera._FOVMODE_VERTICAL_FIXED;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19322. /**
  19323. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19324. *
  19325. */
  19326. get: function () {
  19327. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19333. get: function () {
  19334. return Camera._RIG_MODE_NONE;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19340. get: function () {
  19341. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19347. get: function () {
  19348. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19354. get: function () {
  19355. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19361. get: function () {
  19362. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19368. get: function () {
  19369. return Camera._RIG_MODE_VR;
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19375. get: function () {
  19376. return Camera._RIG_MODE_WEBVR;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. /**
  19382. * Store current camera state (fov, position, etc..)
  19383. */
  19384. Camera.prototype.storeState = function () {
  19385. this._stateStored = true;
  19386. this._storedFov = this.fov;
  19387. return this;
  19388. };
  19389. /**
  19390. * Restores the camera state values if it has been stored. You must call storeState() first
  19391. */
  19392. Camera.prototype._restoreStateValues = function () {
  19393. if (!this._stateStored) {
  19394. return false;
  19395. }
  19396. this.fov = this._storedFov;
  19397. return true;
  19398. };
  19399. /**
  19400. * Restored camera state. You must call storeState() first
  19401. */
  19402. Camera.prototype.restoreState = function () {
  19403. if (this._restoreStateValues()) {
  19404. this.onRestoreStateObservable.notifyObservers(this);
  19405. return true;
  19406. }
  19407. return false;
  19408. };
  19409. Camera.prototype.getClassName = function () {
  19410. return "Camera";
  19411. };
  19412. /**
  19413. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19414. */
  19415. Camera.prototype.toString = function (fullDetails) {
  19416. var ret = "Name: " + this.name;
  19417. ret += ", type: " + this.getClassName();
  19418. if (this.animations) {
  19419. for (var i = 0; i < this.animations.length; i++) {
  19420. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19421. }
  19422. }
  19423. if (fullDetails) {
  19424. }
  19425. return ret;
  19426. };
  19427. Object.defineProperty(Camera.prototype, "globalPosition", {
  19428. get: function () {
  19429. return this._globalPosition;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. Camera.prototype.getActiveMeshes = function () {
  19435. return this._activeMeshes;
  19436. };
  19437. Camera.prototype.isActiveMesh = function (mesh) {
  19438. return (this._activeMeshes.indexOf(mesh) !== -1);
  19439. };
  19440. //Cache
  19441. Camera.prototype._initCache = function () {
  19442. _super.prototype._initCache.call(this);
  19443. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19444. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19445. this._cache.mode = undefined;
  19446. this._cache.minZ = undefined;
  19447. this._cache.maxZ = undefined;
  19448. this._cache.fov = undefined;
  19449. this._cache.fovMode = undefined;
  19450. this._cache.aspectRatio = undefined;
  19451. this._cache.orthoLeft = undefined;
  19452. this._cache.orthoRight = undefined;
  19453. this._cache.orthoBottom = undefined;
  19454. this._cache.orthoTop = undefined;
  19455. this._cache.renderWidth = undefined;
  19456. this._cache.renderHeight = undefined;
  19457. };
  19458. Camera.prototype._updateCache = function (ignoreParentClass) {
  19459. if (!ignoreParentClass) {
  19460. _super.prototype._updateCache.call(this);
  19461. }
  19462. this._cache.position.copyFrom(this.position);
  19463. this._cache.upVector.copyFrom(this.upVector);
  19464. };
  19465. // Synchronized
  19466. Camera.prototype._isSynchronized = function () {
  19467. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19468. };
  19469. Camera.prototype._isSynchronizedViewMatrix = function () {
  19470. if (!_super.prototype._isSynchronized.call(this))
  19471. return false;
  19472. return this._cache.position.equals(this.position)
  19473. && this._cache.upVector.equals(this.upVector)
  19474. && this.isSynchronizedWithParent();
  19475. };
  19476. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19477. var check = this._cache.mode === this.mode
  19478. && this._cache.minZ === this.minZ
  19479. && this._cache.maxZ === this.maxZ;
  19480. if (!check) {
  19481. return false;
  19482. }
  19483. var engine = this.getEngine();
  19484. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19485. check = this._cache.fov === this.fov
  19486. && this._cache.fovMode === this.fovMode
  19487. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19488. }
  19489. else {
  19490. check = this._cache.orthoLeft === this.orthoLeft
  19491. && this._cache.orthoRight === this.orthoRight
  19492. && this._cache.orthoBottom === this.orthoBottom
  19493. && this._cache.orthoTop === this.orthoTop
  19494. && this._cache.renderWidth === engine.getRenderWidth()
  19495. && this._cache.renderHeight === engine.getRenderHeight();
  19496. }
  19497. return check;
  19498. };
  19499. // Controls
  19500. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19501. };
  19502. Camera.prototype.detachControl = function (element) {
  19503. };
  19504. Camera.prototype.update = function () {
  19505. this._checkInputs();
  19506. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19507. this._updateRigCameras();
  19508. }
  19509. };
  19510. Camera.prototype._checkInputs = function () {
  19511. this.onAfterCheckInputsObservable.notifyObservers(this);
  19512. };
  19513. Object.defineProperty(Camera.prototype, "rigCameras", {
  19514. get: function () {
  19515. return this._rigCameras;
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19521. get: function () {
  19522. return this._rigPostProcess;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19528. // invalidate framebuffer
  19529. if (this._postProcesses.length > 0) {
  19530. this._postProcesses[0].markTextureDirty();
  19531. }
  19532. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19533. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19534. var cam = this._rigCameras[i];
  19535. var rigPostProcess = cam._rigPostProcess;
  19536. // for VR rig, there does not have to be a post process
  19537. if (rigPostProcess) {
  19538. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19539. if (isPass) {
  19540. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19541. cam.isIntermediate = this._postProcesses.length === 0;
  19542. }
  19543. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19544. rigPostProcess.markTextureDirty();
  19545. }
  19546. else {
  19547. cam._postProcesses = this._postProcesses.slice(0);
  19548. }
  19549. }
  19550. };
  19551. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19552. if (insertAt === void 0) { insertAt = null; }
  19553. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19554. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19555. return 0;
  19556. }
  19557. if (insertAt == null || insertAt < 0) {
  19558. this._postProcesses.push(postProcess);
  19559. }
  19560. else {
  19561. this._postProcesses.splice(insertAt, 0, postProcess);
  19562. }
  19563. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19564. return this._postProcesses.indexOf(postProcess);
  19565. };
  19566. Camera.prototype.detachPostProcess = function (postProcess) {
  19567. var idx = this._postProcesses.indexOf(postProcess);
  19568. if (idx !== -1) {
  19569. this._postProcesses.splice(idx, 1);
  19570. }
  19571. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19572. };
  19573. Camera.prototype.getWorldMatrix = function () {
  19574. if (!this._worldMatrix) {
  19575. this._worldMatrix = BABYLON.Matrix.Identity();
  19576. }
  19577. var viewMatrix = this.getViewMatrix();
  19578. viewMatrix.invertToRef(this._worldMatrix);
  19579. return this._worldMatrix;
  19580. };
  19581. Camera.prototype._getViewMatrix = function () {
  19582. return BABYLON.Matrix.Identity();
  19583. };
  19584. Camera.prototype.getViewMatrix = function (force) {
  19585. if (!force && this._isSynchronizedViewMatrix()) {
  19586. return this._computedViewMatrix;
  19587. }
  19588. this.updateCache();
  19589. this._computedViewMatrix = this._getViewMatrix();
  19590. this._currentRenderId = this.getScene().getRenderId();
  19591. this._refreshFrustumPlanes = true;
  19592. if (!this.parent || !this.parent.getWorldMatrix) {
  19593. this._globalPosition.copyFrom(this.position);
  19594. }
  19595. else {
  19596. if (!this._worldMatrix) {
  19597. this._worldMatrix = BABYLON.Matrix.Identity();
  19598. }
  19599. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19600. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19601. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19602. this._computedViewMatrix.invert();
  19603. this._markSyncedWithParent();
  19604. }
  19605. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19606. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19607. }
  19608. this.onViewMatrixChangedObservable.notifyObservers(this);
  19609. return this._computedViewMatrix;
  19610. };
  19611. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19612. this._doNotComputeProjectionMatrix = true;
  19613. if (projection !== undefined) {
  19614. this._projectionMatrix = projection;
  19615. }
  19616. };
  19617. ;
  19618. Camera.prototype.unfreezeProjectionMatrix = function () {
  19619. this._doNotComputeProjectionMatrix = false;
  19620. };
  19621. ;
  19622. Camera.prototype.getProjectionMatrix = function (force) {
  19623. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19624. return this._projectionMatrix;
  19625. }
  19626. // Cache
  19627. this._cache.mode = this.mode;
  19628. this._cache.minZ = this.minZ;
  19629. this._cache.maxZ = this.maxZ;
  19630. // Matrix
  19631. this._refreshFrustumPlanes = true;
  19632. var engine = this.getEngine();
  19633. var scene = this.getScene();
  19634. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19635. this._cache.fov = this.fov;
  19636. this._cache.fovMode = this.fovMode;
  19637. this._cache.aspectRatio = engine.getAspectRatio(this);
  19638. if (this.minZ <= 0) {
  19639. this.minZ = 0.1;
  19640. }
  19641. if (scene.useRightHandedSystem) {
  19642. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19643. }
  19644. else {
  19645. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19646. }
  19647. }
  19648. else {
  19649. var halfWidth = engine.getRenderWidth() / 2.0;
  19650. var halfHeight = engine.getRenderHeight() / 2.0;
  19651. if (scene.useRightHandedSystem) {
  19652. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19653. }
  19654. else {
  19655. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19656. }
  19657. this._cache.orthoLeft = this.orthoLeft;
  19658. this._cache.orthoRight = this.orthoRight;
  19659. this._cache.orthoBottom = this.orthoBottom;
  19660. this._cache.orthoTop = this.orthoTop;
  19661. this._cache.renderWidth = engine.getRenderWidth();
  19662. this._cache.renderHeight = engine.getRenderHeight();
  19663. }
  19664. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19665. return this._projectionMatrix;
  19666. };
  19667. Camera.prototype.getTranformationMatrix = function () {
  19668. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19669. return this._transformMatrix;
  19670. };
  19671. Camera.prototype.updateFrustumPlanes = function () {
  19672. if (!this._refreshFrustumPlanes) {
  19673. return;
  19674. }
  19675. this.getTranformationMatrix();
  19676. if (!this._frustumPlanes) {
  19677. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19678. }
  19679. else {
  19680. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19681. }
  19682. this._refreshFrustumPlanes = false;
  19683. };
  19684. Camera.prototype.isInFrustum = function (target) {
  19685. this.updateFrustumPlanes();
  19686. return target.isInFrustum(this._frustumPlanes);
  19687. };
  19688. Camera.prototype.isCompletelyInFrustum = function (target) {
  19689. this.updateFrustumPlanes();
  19690. return target.isCompletelyInFrustum(this._frustumPlanes);
  19691. };
  19692. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19693. if (length === void 0) { length = 100; }
  19694. if (!transform) {
  19695. transform = this.getWorldMatrix();
  19696. }
  19697. if (!origin) {
  19698. origin = this.position;
  19699. }
  19700. var forward = new BABYLON.Vector3(0, 0, 1);
  19701. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19702. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19703. return new BABYLON.Ray(origin, direction, length);
  19704. };
  19705. Camera.prototype.dispose = function () {
  19706. // Observables
  19707. this.onViewMatrixChangedObservable.clear();
  19708. this.onProjectionMatrixChangedObservable.clear();
  19709. this.onAfterCheckInputsObservable.clear();
  19710. this.onRestoreStateObservable.clear();
  19711. // Inputs
  19712. if (this.inputs) {
  19713. this.inputs.clear();
  19714. }
  19715. // Animations
  19716. this.getScene().stopAnimation(this);
  19717. // Remove from scene
  19718. this.getScene().removeCamera(this);
  19719. while (this._rigCameras.length > 0) {
  19720. var camera = this._rigCameras.pop();
  19721. if (camera) {
  19722. camera.dispose();
  19723. }
  19724. }
  19725. // Postprocesses
  19726. if (this._rigPostProcess) {
  19727. this._rigPostProcess.dispose(this);
  19728. this._rigPostProcess = null;
  19729. this._postProcesses = [];
  19730. }
  19731. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19732. this._rigPostProcess = null;
  19733. this._postProcesses = [];
  19734. }
  19735. else {
  19736. var i = this._postProcesses.length;
  19737. while (--i >= 0) {
  19738. this._postProcesses[i].dispose(this);
  19739. }
  19740. }
  19741. // Render targets
  19742. var i = this.customRenderTargets.length;
  19743. while (--i >= 0) {
  19744. this.customRenderTargets[i].dispose();
  19745. }
  19746. this.customRenderTargets = [];
  19747. // Active Meshes
  19748. this._activeMeshes.dispose();
  19749. _super.prototype.dispose.call(this);
  19750. };
  19751. Object.defineProperty(Camera.prototype, "leftCamera", {
  19752. // ---- Camera rigs section ----
  19753. get: function () {
  19754. if (this._rigCameras.length < 1) {
  19755. return null;
  19756. }
  19757. return this._rigCameras[0];
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(Camera.prototype, "rightCamera", {
  19763. get: function () {
  19764. if (this._rigCameras.length < 2) {
  19765. return null;
  19766. }
  19767. return this._rigCameras[1];
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Camera.prototype.getLeftTarget = function () {
  19773. if (this._rigCameras.length < 1) {
  19774. return null;
  19775. }
  19776. return this._rigCameras[0].getTarget();
  19777. };
  19778. Camera.prototype.getRightTarget = function () {
  19779. if (this._rigCameras.length < 2) {
  19780. return null;
  19781. }
  19782. return this._rigCameras[1].getTarget();
  19783. };
  19784. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19785. if (this.cameraRigMode === mode) {
  19786. return;
  19787. }
  19788. while (this._rigCameras.length > 0) {
  19789. var camera = this._rigCameras.pop();
  19790. if (camera) {
  19791. camera.dispose();
  19792. }
  19793. }
  19794. this.cameraRigMode = mode;
  19795. this._cameraRigParams = {};
  19796. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19797. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19798. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19799. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19800. // create the rig cameras, unless none
  19801. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19802. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19803. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19804. if (leftCamera && rightCamera) {
  19805. this._rigCameras.push(leftCamera);
  19806. this._rigCameras.push(rightCamera);
  19807. }
  19808. }
  19809. switch (this.cameraRigMode) {
  19810. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19812. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19813. break;
  19814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19815. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19816. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19817. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19818. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19819. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19820. break;
  19821. case Camera.RIG_MODE_VR:
  19822. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19823. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19824. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19825. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19826. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19827. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19828. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19829. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19830. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19831. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19832. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19833. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19834. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19835. if (metrics.compensateDistortion) {
  19836. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19837. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19838. }
  19839. break;
  19840. case Camera.RIG_MODE_WEBVR:
  19841. if (rigParams.vrDisplay) {
  19842. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19843. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19844. //Left eye
  19845. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19846. this._rigCameras[0].setCameraRigParameter("left", true);
  19847. //leaving this for future reference
  19848. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19849. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19850. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19851. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19852. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19853. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19854. this._rigCameras[0].parent = this;
  19855. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19856. //Right eye
  19857. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19858. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19859. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19860. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19861. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19862. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19863. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19864. this._rigCameras[1].parent = this;
  19865. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19866. if (Camera.UseAlternateWebVRRendering) {
  19867. this._rigCameras[1]._skipRendering = true;
  19868. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19869. }
  19870. }
  19871. break;
  19872. }
  19873. this._cascadePostProcessesToRigCams();
  19874. this.update();
  19875. };
  19876. Camera.prototype._getVRProjectionMatrix = function () {
  19877. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19878. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19879. return this._projectionMatrix;
  19880. };
  19881. Camera.prototype._updateCameraRotationMatrix = function () {
  19882. //Here for WebVR
  19883. };
  19884. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19885. //Here for WebVR
  19886. };
  19887. /**
  19888. * This function MUST be overwritten by the different WebVR cameras available.
  19889. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19890. */
  19891. Camera.prototype._getWebVRProjectionMatrix = function () {
  19892. return BABYLON.Matrix.Identity();
  19893. };
  19894. /**
  19895. * This function MUST be overwritten by the different WebVR cameras available.
  19896. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19897. */
  19898. Camera.prototype._getWebVRViewMatrix = function () {
  19899. return BABYLON.Matrix.Identity();
  19900. };
  19901. Camera.prototype.setCameraRigParameter = function (name, value) {
  19902. if (!this._cameraRigParams) {
  19903. this._cameraRigParams = {};
  19904. }
  19905. this._cameraRigParams[name] = value;
  19906. //provisionnally:
  19907. if (name === "interaxialDistance") {
  19908. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19909. }
  19910. };
  19911. /**
  19912. * needs to be overridden by children so sub has required properties to be copied
  19913. */
  19914. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19915. return null;
  19916. };
  19917. /**
  19918. * May need to be overridden by children
  19919. */
  19920. Camera.prototype._updateRigCameras = function () {
  19921. for (var i = 0; i < this._rigCameras.length; i++) {
  19922. this._rigCameras[i].minZ = this.minZ;
  19923. this._rigCameras[i].maxZ = this.maxZ;
  19924. this._rigCameras[i].fov = this.fov;
  19925. }
  19926. // only update viewport when ANAGLYPH
  19927. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19928. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19929. }
  19930. };
  19931. Camera.prototype._setupInputs = function () {
  19932. };
  19933. Camera.prototype.serialize = function () {
  19934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19935. // Type
  19936. serializationObject.type = this.getClassName();
  19937. // Parent
  19938. if (this.parent) {
  19939. serializationObject.parentId = this.parent.id;
  19940. }
  19941. if (this.inputs) {
  19942. this.inputs.serialize(serializationObject);
  19943. }
  19944. // Animations
  19945. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19946. serializationObject.ranges = this.serializeAnimationRanges();
  19947. return serializationObject;
  19948. };
  19949. Camera.prototype.clone = function (name) {
  19950. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19951. };
  19952. Camera.prototype.getDirection = function (localAxis) {
  19953. var result = BABYLON.Vector3.Zero();
  19954. this.getDirectionToRef(localAxis, result);
  19955. return result;
  19956. };
  19957. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19958. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19959. };
  19960. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19961. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19962. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19963. switch (type) {
  19964. case "ArcRotateCamera":
  19965. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19966. case "DeviceOrientationCamera":
  19967. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19968. case "FollowCamera":
  19969. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19970. case "ArcFollowCamera":
  19971. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19972. case "GamepadCamera":
  19973. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19974. case "TouchCamera":
  19975. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19976. case "VirtualJoysticksCamera":
  19977. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19978. case "WebVRFreeCamera":
  19979. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19980. case "WebVRGamepadCamera":
  19981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19982. case "VRDeviceOrientationFreeCamera":
  19983. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19984. case "VRDeviceOrientationGamepadCamera":
  19985. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19986. case "AnaglyphArcRotateCamera":
  19987. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19988. case "AnaglyphFreeCamera":
  19989. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19990. case "AnaglyphGamepadCamera":
  19991. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19992. case "AnaglyphUniversalCamera":
  19993. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19994. case "StereoscopicArcRotateCamera":
  19995. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19996. case "StereoscopicFreeCamera":
  19997. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19998. case "StereoscopicGamepadCamera":
  19999. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20000. case "StereoscopicUniversalCamera":
  20001. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20002. case "FreeCamera":// Forcing Universal here
  20003. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20004. default:// Universal Camera is the default value
  20005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20006. }
  20007. };
  20008. Camera.prototype.computeWorldMatrix = function () {
  20009. return this.getWorldMatrix();
  20010. };
  20011. Camera.Parse = function (parsedCamera, scene) {
  20012. var type = parsedCamera.type;
  20013. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20014. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20015. // Parent
  20016. if (parsedCamera.parentId) {
  20017. camera._waitingParentId = parsedCamera.parentId;
  20018. }
  20019. //If camera has an input manager, let it parse inputs settings
  20020. if (camera.inputs) {
  20021. camera.inputs.parse(parsedCamera);
  20022. camera._setupInputs();
  20023. }
  20024. if (camera.setPosition) {
  20025. camera.position.copyFromFloats(0, 0, 0);
  20026. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20027. }
  20028. // Target
  20029. if (parsedCamera.target) {
  20030. if (camera.setTarget) {
  20031. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20032. }
  20033. }
  20034. // Apply 3d rig, when found
  20035. if (parsedCamera.cameraRigMode) {
  20036. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20037. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20038. }
  20039. // Animations
  20040. if (parsedCamera.animations) {
  20041. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20042. var parsedAnimation = parsedCamera.animations[animationIndex];
  20043. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20044. }
  20045. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20046. }
  20047. if (parsedCamera.autoAnimate) {
  20048. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20049. }
  20050. return camera;
  20051. };
  20052. // Statics
  20053. Camera._PERSPECTIVE_CAMERA = 0;
  20054. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20055. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20056. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20057. Camera._RIG_MODE_NONE = 0;
  20058. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20059. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20060. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20061. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20062. Camera._RIG_MODE_VR = 20;
  20063. Camera._RIG_MODE_WEBVR = 21;
  20064. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20065. Camera.UseAlternateWebVRRendering = false;
  20066. __decorate([
  20067. BABYLON.serializeAsVector3()
  20068. ], Camera.prototype, "position", void 0);
  20069. __decorate([
  20070. BABYLON.serializeAsVector3()
  20071. ], Camera.prototype, "upVector", void 0);
  20072. __decorate([
  20073. BABYLON.serialize()
  20074. ], Camera.prototype, "orthoLeft", void 0);
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Camera.prototype, "orthoRight", void 0);
  20078. __decorate([
  20079. BABYLON.serialize()
  20080. ], Camera.prototype, "orthoBottom", void 0);
  20081. __decorate([
  20082. BABYLON.serialize()
  20083. ], Camera.prototype, "orthoTop", void 0);
  20084. __decorate([
  20085. BABYLON.serialize()
  20086. ], Camera.prototype, "fov", void 0);
  20087. __decorate([
  20088. BABYLON.serialize()
  20089. ], Camera.prototype, "minZ", void 0);
  20090. __decorate([
  20091. BABYLON.serialize()
  20092. ], Camera.prototype, "maxZ", void 0);
  20093. __decorate([
  20094. BABYLON.serialize()
  20095. ], Camera.prototype, "inertia", void 0);
  20096. __decorate([
  20097. BABYLON.serialize()
  20098. ], Camera.prototype, "mode", void 0);
  20099. __decorate([
  20100. BABYLON.serialize()
  20101. ], Camera.prototype, "layerMask", void 0);
  20102. __decorate([
  20103. BABYLON.serialize()
  20104. ], Camera.prototype, "fovMode", void 0);
  20105. __decorate([
  20106. BABYLON.serialize()
  20107. ], Camera.prototype, "cameraRigMode", void 0);
  20108. __decorate([
  20109. BABYLON.serialize()
  20110. ], Camera.prototype, "interaxialDistance", void 0);
  20111. __decorate([
  20112. BABYLON.serialize()
  20113. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20114. return Camera;
  20115. }(BABYLON.Node));
  20116. BABYLON.Camera = Camera;
  20117. })(BABYLON || (BABYLON = {}));
  20118. //# sourceMappingURL=babylon.camera.js.map
  20119. var BABYLON;
  20120. (function (BABYLON) {
  20121. var RenderingManager = /** @class */ (function () {
  20122. function RenderingManager(scene) {
  20123. this._renderingGroups = new Array();
  20124. this._autoClearDepthStencil = {};
  20125. this._customOpaqueSortCompareFn = {};
  20126. this._customAlphaTestSortCompareFn = {};
  20127. this._customTransparentSortCompareFn = {};
  20128. this._renderinGroupInfo = null;
  20129. this._scene = scene;
  20130. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20131. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20132. }
  20133. }
  20134. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20135. if (depth === void 0) { depth = true; }
  20136. if (stencil === void 0) { stencil = true; }
  20137. if (this._depthStencilBufferAlreadyCleaned) {
  20138. return;
  20139. }
  20140. this._scene.getEngine().clear(null, false, depth, stencil);
  20141. this._depthStencilBufferAlreadyCleaned = true;
  20142. };
  20143. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20144. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20145. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20146. var info = null;
  20147. if (observable) {
  20148. if (!this._renderinGroupInfo) {
  20149. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20150. }
  20151. info = this._renderinGroupInfo;
  20152. info.scene = this._scene;
  20153. info.camera = this._scene.activeCamera;
  20154. }
  20155. // Dispatch sprites
  20156. if (renderSprites) {
  20157. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20158. var manager = this._scene.spriteManagers[index];
  20159. this.dispatchSprites(manager);
  20160. }
  20161. }
  20162. // Render
  20163. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20164. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20165. var renderingGroup = this._renderingGroups[index];
  20166. if (!renderingGroup && !observable)
  20167. continue;
  20168. var renderingGroupMask = 0;
  20169. // Fire PRECLEAR stage
  20170. if (observable && info) {
  20171. renderingGroupMask = Math.pow(2, index);
  20172. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20173. info.renderingGroupId = index;
  20174. observable.notifyObservers(info, renderingGroupMask);
  20175. }
  20176. // Clear depth/stencil if needed
  20177. if (RenderingManager.AUTOCLEAR) {
  20178. var autoClear = this._autoClearDepthStencil[index];
  20179. if (autoClear && autoClear.autoClear) {
  20180. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20181. }
  20182. }
  20183. if (observable && info) {
  20184. // Fire PREOPAQUE stage
  20185. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20186. observable.notifyObservers(info, renderingGroupMask);
  20187. // Fire PRETRANSPARENT stage
  20188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20189. observable.notifyObservers(info, renderingGroupMask);
  20190. }
  20191. if (renderingGroup)
  20192. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20193. // Fire POSTTRANSPARENT stage
  20194. if (observable && info) {
  20195. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20196. observable.notifyObservers(info, renderingGroupMask);
  20197. }
  20198. }
  20199. };
  20200. RenderingManager.prototype.reset = function () {
  20201. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20202. var renderingGroup = this._renderingGroups[index];
  20203. if (renderingGroup) {
  20204. renderingGroup.prepare();
  20205. }
  20206. }
  20207. };
  20208. RenderingManager.prototype.dispose = function () {
  20209. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20210. var renderingGroup = this._renderingGroups[index];
  20211. if (renderingGroup) {
  20212. renderingGroup.dispose();
  20213. }
  20214. }
  20215. this._renderingGroups.length = 0;
  20216. };
  20217. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20218. if (this._renderingGroups[renderingGroupId] === undefined) {
  20219. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20220. }
  20221. };
  20222. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20223. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20224. this._prepareRenderingGroup(renderingGroupId);
  20225. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20226. };
  20227. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20228. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20229. this._prepareRenderingGroup(renderingGroupId);
  20230. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20231. };
  20232. /**
  20233. * @param subMesh The submesh to dispatch
  20234. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20235. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20236. */
  20237. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20238. if (mesh === undefined) {
  20239. mesh = subMesh.getMesh();
  20240. }
  20241. var renderingGroupId = mesh.renderingGroupId || 0;
  20242. this._prepareRenderingGroup(renderingGroupId);
  20243. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20244. };
  20245. /**
  20246. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20247. * This allowed control for front to back rendering or reversly depending of the special needs.
  20248. *
  20249. * @param renderingGroupId The rendering group id corresponding to its index
  20250. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20251. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20252. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20253. */
  20254. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20255. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20256. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20257. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20258. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20259. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20260. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20261. if (this._renderingGroups[renderingGroupId]) {
  20262. var group = this._renderingGroups[renderingGroupId];
  20263. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20264. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20265. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20266. }
  20267. };
  20268. /**
  20269. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20270. *
  20271. * @param renderingGroupId The rendering group id corresponding to its index
  20272. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20273. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20274. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20275. */
  20276. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20277. if (depth === void 0) { depth = true; }
  20278. if (stencil === void 0) { stencil = true; }
  20279. this._autoClearDepthStencil[renderingGroupId] = {
  20280. autoClear: autoClearDepthStencil,
  20281. depth: depth,
  20282. stencil: stencil
  20283. };
  20284. };
  20285. /**
  20286. * The max id used for rendering groups (not included)
  20287. */
  20288. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20289. /**
  20290. * The min id used for rendering groups (included)
  20291. */
  20292. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20293. /**
  20294. * Used to globally prevent autoclearing scenes.
  20295. */
  20296. RenderingManager.AUTOCLEAR = true;
  20297. return RenderingManager;
  20298. }());
  20299. BABYLON.RenderingManager = RenderingManager;
  20300. })(BABYLON || (BABYLON = {}));
  20301. //# sourceMappingURL=babylon.renderingManager.js.map
  20302. var BABYLON;
  20303. (function (BABYLON) {
  20304. var RenderingGroup = /** @class */ (function () {
  20305. /**
  20306. * Creates a new rendering group.
  20307. * @param index The rendering group index
  20308. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20309. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20310. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20311. */
  20312. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20313. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20314. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20315. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20316. this.index = index;
  20317. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20318. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20319. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20320. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20321. this._particleSystems = new BABYLON.SmartArray(256);
  20322. this._spriteManagers = new BABYLON.SmartArray(256);
  20323. this._edgesRenderers = new BABYLON.SmartArray(16);
  20324. this._scene = scene;
  20325. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20326. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20327. this.transparentSortCompareFn = transparentSortCompareFn;
  20328. }
  20329. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20330. /**
  20331. * Set the opaque sort comparison function.
  20332. * If null the sub meshes will be render in the order they were created
  20333. */
  20334. set: function (value) {
  20335. this._opaqueSortCompareFn = value;
  20336. if (value) {
  20337. this._renderOpaque = this.renderOpaqueSorted;
  20338. }
  20339. else {
  20340. this._renderOpaque = RenderingGroup.renderUnsorted;
  20341. }
  20342. },
  20343. enumerable: true,
  20344. configurable: true
  20345. });
  20346. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20347. /**
  20348. * Set the alpha test sort comparison function.
  20349. * If null the sub meshes will be render in the order they were created
  20350. */
  20351. set: function (value) {
  20352. this._alphaTestSortCompareFn = value;
  20353. if (value) {
  20354. this._renderAlphaTest = this.renderAlphaTestSorted;
  20355. }
  20356. else {
  20357. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20358. }
  20359. },
  20360. enumerable: true,
  20361. configurable: true
  20362. });
  20363. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20364. /**
  20365. * Set the transparent sort comparison function.
  20366. * If null the sub meshes will be render in the order they were created
  20367. */
  20368. set: function (value) {
  20369. if (value) {
  20370. this._transparentSortCompareFn = value;
  20371. }
  20372. else {
  20373. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20374. }
  20375. this._renderTransparent = this.renderTransparentSorted;
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. /**
  20381. * Render all the sub meshes contained in the group.
  20382. * @param customRenderFunction Used to override the default render behaviour of the group.
  20383. * @returns true if rendered some submeshes.
  20384. */
  20385. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20386. if (customRenderFunction) {
  20387. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20388. return;
  20389. }
  20390. var engine = this._scene.getEngine();
  20391. // Depth only
  20392. if (this._depthOnlySubMeshes.length !== 0) {
  20393. engine.setColorWrite(false);
  20394. this._renderAlphaTest(this._depthOnlySubMeshes);
  20395. engine.setColorWrite(true);
  20396. }
  20397. // Opaque
  20398. if (this._opaqueSubMeshes.length !== 0) {
  20399. this._renderOpaque(this._opaqueSubMeshes);
  20400. }
  20401. // Alpha test
  20402. if (this._alphaTestSubMeshes.length !== 0) {
  20403. this._renderAlphaTest(this._alphaTestSubMeshes);
  20404. }
  20405. var stencilState = engine.getStencilBuffer();
  20406. engine.setStencilBuffer(false);
  20407. // Sprites
  20408. if (renderSprites) {
  20409. this._renderSprites();
  20410. }
  20411. // Particles
  20412. if (renderParticles) {
  20413. this._renderParticles(activeMeshes);
  20414. }
  20415. if (this.onBeforeTransparentRendering) {
  20416. this.onBeforeTransparentRendering();
  20417. }
  20418. // Transparent
  20419. if (this._transparentSubMeshes.length !== 0) {
  20420. this._renderTransparent(this._transparentSubMeshes);
  20421. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20422. }
  20423. // Set back stencil to false in case it changes before the edge renderer.
  20424. engine.setStencilBuffer(false);
  20425. // Edges
  20426. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20427. this._edgesRenderers.data[edgesRendererIndex].render();
  20428. }
  20429. // Restore Stencil state.
  20430. engine.setStencilBuffer(stencilState);
  20431. };
  20432. /**
  20433. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20434. * @param subMeshes The submeshes to render
  20435. */
  20436. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20437. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20438. };
  20439. /**
  20440. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20441. * @param subMeshes The submeshes to render
  20442. */
  20443. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20444. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20445. };
  20446. /**
  20447. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20448. * @param subMeshes The submeshes to render
  20449. */
  20450. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20451. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20452. };
  20453. /**
  20454. * Renders the submeshes in a specified order.
  20455. * @param subMeshes The submeshes to sort before render
  20456. * @param sortCompareFn The comparison function use to sort
  20457. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20458. * @param transparent Specifies to activate blending if true
  20459. */
  20460. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20461. var subIndex = 0;
  20462. var subMesh;
  20463. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20464. for (; subIndex < subMeshes.length; subIndex++) {
  20465. subMesh = subMeshes.data[subIndex];
  20466. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20467. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20468. }
  20469. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20470. if (sortCompareFn) {
  20471. sortedArray.sort(sortCompareFn);
  20472. }
  20473. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20474. subMesh = sortedArray[subIndex];
  20475. if (transparent) {
  20476. var material = subMesh.getMaterial();
  20477. if (material && material.needDepthPrePass) {
  20478. var engine = material.getScene().getEngine();
  20479. engine.setColorWrite(false);
  20480. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20481. subMesh.render(false);
  20482. engine.setColorWrite(true);
  20483. }
  20484. }
  20485. subMesh.render(transparent);
  20486. }
  20487. };
  20488. /**
  20489. * Renders the submeshes in the order they were dispatched (no sort applied).
  20490. * @param subMeshes The submeshes to render
  20491. */
  20492. RenderingGroup.renderUnsorted = function (subMeshes) {
  20493. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20494. var submesh = subMeshes.data[subIndex];
  20495. submesh.render(false);
  20496. }
  20497. };
  20498. /**
  20499. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20500. * are rendered back to front if in the same alpha index.
  20501. *
  20502. * @param a The first submesh
  20503. * @param b The second submesh
  20504. * @returns The result of the comparison
  20505. */
  20506. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20507. // Alpha index first
  20508. if (a._alphaIndex > b._alphaIndex) {
  20509. return 1;
  20510. }
  20511. if (a._alphaIndex < b._alphaIndex) {
  20512. return -1;
  20513. }
  20514. // Then distance to camera
  20515. return RenderingGroup.backToFrontSortCompare(a, b);
  20516. };
  20517. /**
  20518. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20519. * are rendered back to front.
  20520. *
  20521. * @param a The first submesh
  20522. * @param b The second submesh
  20523. * @returns The result of the comparison
  20524. */
  20525. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20526. // Then distance to camera
  20527. if (a._distanceToCamera < b._distanceToCamera) {
  20528. return 1;
  20529. }
  20530. if (a._distanceToCamera > b._distanceToCamera) {
  20531. return -1;
  20532. }
  20533. return 0;
  20534. };
  20535. /**
  20536. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20537. * are rendered front to back (prevent overdraw).
  20538. *
  20539. * @param a The first submesh
  20540. * @param b The second submesh
  20541. * @returns The result of the comparison
  20542. */
  20543. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20544. // Then distance to camera
  20545. if (a._distanceToCamera < b._distanceToCamera) {
  20546. return -1;
  20547. }
  20548. if (a._distanceToCamera > b._distanceToCamera) {
  20549. return 1;
  20550. }
  20551. return 0;
  20552. };
  20553. /**
  20554. * Resets the different lists of submeshes to prepare a new frame.
  20555. */
  20556. RenderingGroup.prototype.prepare = function () {
  20557. this._opaqueSubMeshes.reset();
  20558. this._transparentSubMeshes.reset();
  20559. this._alphaTestSubMeshes.reset();
  20560. this._depthOnlySubMeshes.reset();
  20561. this._particleSystems.reset();
  20562. this._spriteManagers.reset();
  20563. this._edgesRenderers.reset();
  20564. };
  20565. RenderingGroup.prototype.dispose = function () {
  20566. this._opaqueSubMeshes.dispose();
  20567. this._transparentSubMeshes.dispose();
  20568. this._alphaTestSubMeshes.dispose();
  20569. this._depthOnlySubMeshes.dispose();
  20570. this._particleSystems.dispose();
  20571. this._spriteManagers.dispose();
  20572. this._edgesRenderers.dispose();
  20573. };
  20574. /**
  20575. * Inserts the submesh in its correct queue depending on its material.
  20576. * @param subMesh The submesh to dispatch
  20577. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20578. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20579. */
  20580. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20581. // Get mesh and materials if not provided
  20582. if (mesh === undefined) {
  20583. mesh = subMesh.getMesh();
  20584. }
  20585. if (material === undefined) {
  20586. material = subMesh.getMaterial();
  20587. }
  20588. if (material === null || material === undefined) {
  20589. return;
  20590. }
  20591. if (material.needAlphaBlendingForMesh(mesh)) {
  20592. this._transparentSubMeshes.push(subMesh);
  20593. }
  20594. else if (material.needAlphaTesting()) {
  20595. if (material.needDepthPrePass) {
  20596. this._depthOnlySubMeshes.push(subMesh);
  20597. }
  20598. this._alphaTestSubMeshes.push(subMesh);
  20599. }
  20600. else {
  20601. if (material.needDepthPrePass) {
  20602. this._depthOnlySubMeshes.push(subMesh);
  20603. }
  20604. this._opaqueSubMeshes.push(subMesh); // Opaque
  20605. }
  20606. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20607. this._edgesRenderers.push(mesh._edgesRenderer);
  20608. }
  20609. };
  20610. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20611. this._spriteManagers.push(spriteManager);
  20612. };
  20613. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20614. this._particleSystems.push(particleSystem);
  20615. };
  20616. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20617. if (this._particleSystems.length === 0) {
  20618. return;
  20619. }
  20620. // Particles
  20621. var activeCamera = this._scene.activeCamera;
  20622. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20623. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20624. var particleSystem = this._particleSystems.data[particleIndex];
  20625. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20626. continue;
  20627. }
  20628. var emitter = particleSystem.emitter;
  20629. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20630. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20631. }
  20632. }
  20633. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20634. };
  20635. RenderingGroup.prototype._renderSprites = function () {
  20636. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20637. return;
  20638. }
  20639. // Sprites
  20640. var activeCamera = this._scene.activeCamera;
  20641. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20642. for (var id = 0; id < this._spriteManagers.length; id++) {
  20643. var spriteManager = this._spriteManagers.data[id];
  20644. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20645. spriteManager.render();
  20646. }
  20647. }
  20648. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20649. };
  20650. return RenderingGroup;
  20651. }());
  20652. BABYLON.RenderingGroup = RenderingGroup;
  20653. })(BABYLON || (BABYLON = {}));
  20654. //# sourceMappingURL=babylon.renderingGroup.js.map
  20655. var BABYLON;
  20656. (function (BABYLON) {
  20657. var ClickInfo = /** @class */ (function () {
  20658. function ClickInfo() {
  20659. this._singleClick = false;
  20660. this._doubleClick = false;
  20661. this._hasSwiped = false;
  20662. this._ignore = false;
  20663. }
  20664. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20665. get: function () {
  20666. return this._singleClick;
  20667. },
  20668. set: function (b) {
  20669. this._singleClick = b;
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20675. get: function () {
  20676. return this._doubleClick;
  20677. },
  20678. set: function (b) {
  20679. this._doubleClick = b;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20685. get: function () {
  20686. return this._hasSwiped;
  20687. },
  20688. set: function (b) {
  20689. this._hasSwiped = b;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20695. get: function () {
  20696. return this._ignore;
  20697. },
  20698. set: function (b) {
  20699. this._ignore = b;
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. return ClickInfo;
  20705. }());
  20706. /**
  20707. * This class is used by the onRenderingGroupObservable
  20708. */
  20709. var RenderingGroupInfo = /** @class */ (function () {
  20710. function RenderingGroupInfo() {
  20711. }
  20712. /**
  20713. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20714. * This stage will be fired no matter what
  20715. */
  20716. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20717. /**
  20718. * Called before opaque object are rendered.
  20719. * This stage will be fired only if there's 3D Opaque content to render
  20720. */
  20721. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20722. /**
  20723. * Called after the opaque objects are rendered and before the transparent ones
  20724. * This stage will be fired only if there's 3D transparent content to render
  20725. */
  20726. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20727. /**
  20728. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20729. * This stage will be fired no matter what
  20730. */
  20731. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20732. return RenderingGroupInfo;
  20733. }());
  20734. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20735. /**
  20736. * Represents a scene to be rendered by the engine.
  20737. * @see http://doc.babylonjs.com/page.php?p=21911
  20738. */
  20739. var Scene = /** @class */ (function () {
  20740. /**
  20741. * @constructor
  20742. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20743. */
  20744. function Scene(engine) {
  20745. // Members
  20746. this.autoClear = true;
  20747. this.autoClearDepthAndStencil = true;
  20748. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20749. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20750. this.forceWireframe = false;
  20751. this._forcePointsCloud = false;
  20752. this.forceShowBoundingBoxes = false;
  20753. this.animationsEnabled = true;
  20754. this.useConstantAnimationDeltaTime = false;
  20755. this.constantlyUpdateMeshUnderPointer = false;
  20756. this.hoverCursor = "pointer";
  20757. this.defaultCursor = "";
  20758. /**
  20759. * This is used to call preventDefault() on pointer down
  20760. * in order to block unwanted artifacts like system double clicks
  20761. */
  20762. this.preventDefaultOnPointerDown = true;
  20763. // Metadata
  20764. this.metadata = null;
  20765. /**
  20766. * An event triggered when the scene is disposed.
  20767. * @type {BABYLON.Observable}
  20768. */
  20769. this.onDisposeObservable = new BABYLON.Observable();
  20770. /**
  20771. * An event triggered before rendering the scene (right after animations and physics)
  20772. * @type {BABYLON.Observable}
  20773. */
  20774. this.onBeforeRenderObservable = new BABYLON.Observable();
  20775. /**
  20776. * An event triggered after rendering the scene
  20777. * @type {BABYLON.Observable}
  20778. */
  20779. this.onAfterRenderObservable = new BABYLON.Observable();
  20780. /**
  20781. * An event triggered before animating the scene
  20782. * @type {BABYLON.Observable}
  20783. */
  20784. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20785. /**
  20786. * An event triggered after animations processing
  20787. * @type {BABYLON.Observable}
  20788. */
  20789. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20790. /**
  20791. * An event triggered before draw calls are ready to be sent
  20792. * @type {BABYLON.Observable}
  20793. */
  20794. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20795. /**
  20796. * An event triggered after draw calls have been sent
  20797. * @type {BABYLON.Observable}
  20798. */
  20799. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20800. /**
  20801. * An event triggered when physic simulation is about to be run
  20802. * @type {BABYLON.Observable}
  20803. */
  20804. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20805. /**
  20806. * An event triggered when physic simulation has been done
  20807. * @type {BABYLON.Observable}
  20808. */
  20809. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20810. /**
  20811. * An event triggered when the scene is ready
  20812. * @type {BABYLON.Observable}
  20813. */
  20814. this.onReadyObservable = new BABYLON.Observable();
  20815. /**
  20816. * An event triggered before rendering a camera
  20817. * @type {BABYLON.Observable}
  20818. */
  20819. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20820. /**
  20821. * An event triggered after rendering a camera
  20822. * @type {BABYLON.Observable}
  20823. */
  20824. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20825. /**
  20826. * An event triggered when active meshes evaluation is about to start
  20827. * @type {BABYLON.Observable}
  20828. */
  20829. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20830. /**
  20831. * An event triggered when active meshes evaluation is done
  20832. * @type {BABYLON.Observable}
  20833. */
  20834. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20835. /**
  20836. * An event triggered when particles rendering is about to start
  20837. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20838. * @type {BABYLON.Observable}
  20839. */
  20840. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20841. /**
  20842. * An event triggered when particles rendering is done
  20843. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20844. * @type {BABYLON.Observable}
  20845. */
  20846. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20847. /**
  20848. * An event triggered when sprites rendering is about to start
  20849. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20850. * @type {BABYLON.Observable}
  20851. */
  20852. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20853. /**
  20854. * An event triggered when sprites rendering is done
  20855. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20856. * @type {BABYLON.Observable}
  20857. */
  20858. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20859. /**
  20860. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20861. * @type {BABYLON.Observable}
  20862. */
  20863. this.onDataLoadedObservable = new BABYLON.Observable();
  20864. /**
  20865. * An event triggered when a camera is created
  20866. * @type {BABYLON.Observable}
  20867. */
  20868. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20869. /**
  20870. * An event triggered when a camera is removed
  20871. * @type {BABYLON.Observable}
  20872. */
  20873. this.onCameraRemovedObservable = new BABYLON.Observable();
  20874. /**
  20875. * An event triggered when a light is created
  20876. * @type {BABYLON.Observable}
  20877. */
  20878. this.onNewLightAddedObservable = new BABYLON.Observable();
  20879. /**
  20880. * An event triggered when a light is removed
  20881. * @type {BABYLON.Observable}
  20882. */
  20883. this.onLightRemovedObservable = new BABYLON.Observable();
  20884. /**
  20885. * An event triggered when a geometry is created
  20886. * @type {BABYLON.Observable}
  20887. */
  20888. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20889. /**
  20890. * An event triggered when a geometry is removed
  20891. * @type {BABYLON.Observable}
  20892. */
  20893. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20894. /**
  20895. * An event triggered when a transform node is created
  20896. * @type {BABYLON.Observable}
  20897. */
  20898. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20899. /**
  20900. * An event triggered when a transform node is removed
  20901. * @type {BABYLON.Observable}
  20902. */
  20903. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20904. /**
  20905. * An event triggered when a mesh is created
  20906. * @type {BABYLON.Observable}
  20907. */
  20908. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20909. /**
  20910. * An event triggered when a mesh is removed
  20911. * @type {BABYLON.Observable}
  20912. */
  20913. this.onMeshRemovedObservable = new BABYLON.Observable();
  20914. /**
  20915. * An event triggered when render targets are about to be rendered
  20916. * Can happen multiple times per frame.
  20917. * @type {BABYLON.Observable}
  20918. */
  20919. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20920. /**
  20921. * An event triggered when render targets were rendered.
  20922. * Can happen multiple times per frame.
  20923. * @type {BABYLON.Observable}
  20924. */
  20925. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20926. /**
  20927. * An event triggered before calculating deterministic simulation step
  20928. * @type {BABYLON.Observable}
  20929. */
  20930. this.onBeforeStepObservable = new BABYLON.Observable();
  20931. /**
  20932. * An event triggered after calculating deterministic simulation step
  20933. * @type {BABYLON.Observable}
  20934. */
  20935. this.onAfterStepObservable = new BABYLON.Observable();
  20936. /**
  20937. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20938. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20939. * 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)
  20940. */
  20941. this.onRenderingGroupObservable = new BABYLON.Observable();
  20942. // Animations
  20943. this.animations = [];
  20944. /**
  20945. * 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).
  20946. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20947. */
  20948. this.onPrePointerObservable = new BABYLON.Observable();
  20949. /**
  20950. * Observable event triggered each time an input event is received from the rendering canvas
  20951. */
  20952. this.onPointerObservable = new BABYLON.Observable();
  20953. this._meshPickProceed = false;
  20954. this._currentPickResult = null;
  20955. this._previousPickResult = null;
  20956. this._totalPointersPressed = 0;
  20957. this._doubleClickOccured = false;
  20958. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20959. this.cameraToUseForPointers = null;
  20960. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20961. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20962. this._startingPointerTime = 0;
  20963. this._previousStartingPointerTime = 0;
  20964. // Deterministic lockstep
  20965. this._timeAccumulator = 0;
  20966. this._currentStepId = 0;
  20967. this._currentInternalStep = 0;
  20968. // Keyboard
  20969. /**
  20970. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20971. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20972. */
  20973. this.onPreKeyboardObservable = new BABYLON.Observable();
  20974. /**
  20975. * Observable event triggered each time an keyboard event is received from the hosting window
  20976. */
  20977. this.onKeyboardObservable = new BABYLON.Observable();
  20978. // Coordinate system
  20979. /**
  20980. * use right-handed coordinate system on this scene.
  20981. * @type {boolean}
  20982. */
  20983. this._useRightHandedSystem = false;
  20984. // Fog
  20985. this._fogEnabled = true;
  20986. this._fogMode = Scene.FOGMODE_NONE;
  20987. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20988. this.fogDensity = 0.1;
  20989. this.fogStart = 0;
  20990. this.fogEnd = 1000.0;
  20991. // Lights
  20992. /**
  20993. * is shadow enabled on this scene.
  20994. * @type {boolean}
  20995. */
  20996. this._shadowsEnabled = true;
  20997. /**
  20998. * is light enabled on this scene.
  20999. * @type {boolean}
  21000. */
  21001. this._lightsEnabled = true;
  21002. /**
  21003. * All of the lights added to this scene.
  21004. * @see BABYLON.Light
  21005. * @type {BABYLON.Light[]}
  21006. */
  21007. this.lights = new Array();
  21008. // Cameras
  21009. /** All of the cameras added to this scene. */
  21010. this.cameras = new Array();
  21011. /** All of the active cameras added to this scene. */
  21012. this.activeCameras = new Array();
  21013. // Meshes
  21014. /**
  21015. * All of the tranform nodes added to this scene.
  21016. * @see BABYLON.TransformNode
  21017. * @type {BABYLON.TransformNode[]}
  21018. */
  21019. this.transformNodes = new Array();
  21020. /**
  21021. * All of the (abstract) meshes added to this scene.
  21022. * @see BABYLON.AbstractMesh
  21023. * @type {BABYLON.AbstractMesh[]}
  21024. */
  21025. this.meshes = new Array();
  21026. /**
  21027. * All of the animation groups added to this scene.
  21028. * @see BABYLON.AnimationGroup
  21029. * @type {BABYLON.AnimationGroup[]}
  21030. */
  21031. this.animationGroups = new Array();
  21032. // Geometries
  21033. this._geometries = new Array();
  21034. this.materials = new Array();
  21035. this.multiMaterials = new Array();
  21036. // Textures
  21037. this._texturesEnabled = true;
  21038. this.textures = new Array();
  21039. // Particles
  21040. this.particlesEnabled = true;
  21041. this.particleSystems = new Array();
  21042. // Sprites
  21043. this.spritesEnabled = true;
  21044. this.spriteManagers = new Array();
  21045. /**
  21046. * The list of layers (background and foreground) of the scene.
  21047. */
  21048. this.layers = new Array();
  21049. /**
  21050. * The list of effect layers (highlights/glow) contained in the scene.
  21051. */
  21052. this.effectLayers = new Array();
  21053. // Skeletons
  21054. this._skeletonsEnabled = true;
  21055. this.skeletons = new Array();
  21056. // Morph targets
  21057. this.morphTargetManagers = new Array();
  21058. // Lens flares
  21059. this.lensFlaresEnabled = true;
  21060. this.lensFlareSystems = new Array();
  21061. // Collisions
  21062. this.collisionsEnabled = true;
  21063. /** Defines the gravity applied to this scene */
  21064. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21065. // Postprocesses
  21066. this.postProcesses = new Array();
  21067. this.postProcessesEnabled = true;
  21068. // Customs render targets
  21069. this.renderTargetsEnabled = true;
  21070. this.dumpNextRenderTargets = false;
  21071. this.customRenderTargets = new Array();
  21072. // Imported meshes
  21073. this.importedMeshesFiles = new Array();
  21074. // Probes
  21075. this.probesEnabled = true;
  21076. this.reflectionProbes = new Array();
  21077. this._actionManagers = new Array();
  21078. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21079. // Procedural textures
  21080. this.proceduralTexturesEnabled = true;
  21081. this._proceduralTextures = new Array();
  21082. this.soundTracks = new Array();
  21083. this._audioEnabled = true;
  21084. this._headphone = false;
  21085. // Performance counters
  21086. this._totalVertices = new BABYLON.PerfCounter();
  21087. this._activeIndices = new BABYLON.PerfCounter();
  21088. this._activeParticles = new BABYLON.PerfCounter();
  21089. this._activeBones = new BABYLON.PerfCounter();
  21090. this._animationTime = 0;
  21091. this.animationTimeScale = 1;
  21092. this._renderId = 0;
  21093. this._executeWhenReadyTimeoutId = -1;
  21094. this._intermediateRendering = false;
  21095. this._viewUpdateFlag = -1;
  21096. this._projectionUpdateFlag = -1;
  21097. this._alternateViewUpdateFlag = -1;
  21098. this._alternateProjectionUpdateFlag = -1;
  21099. this._toBeDisposed = new BABYLON.SmartArray(256);
  21100. this._activeRequests = new Array();
  21101. this._pendingData = new Array();
  21102. this._isDisposed = false;
  21103. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21104. this._activeMeshes = new BABYLON.SmartArray(256);
  21105. this._processedMaterials = new BABYLON.SmartArray(256);
  21106. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21107. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21108. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21109. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21110. this._activeAnimatables = new Array();
  21111. this._transformMatrix = BABYLON.Matrix.Zero();
  21112. this._useAlternateCameraConfiguration = false;
  21113. this._alternateRendering = false;
  21114. this.requireLightSorting = false;
  21115. this._activeMeshesFrozen = false;
  21116. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21117. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21118. this._engine.scenes.push(this);
  21119. this._uid = null;
  21120. this._renderingManager = new BABYLON.RenderingManager(this);
  21121. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21122. if (BABYLON.OutlineRenderer) {
  21123. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21124. }
  21125. if (BABYLON.Tools.IsWindowObjectExist()) {
  21126. this.attachControl();
  21127. }
  21128. //simplification queue
  21129. if (BABYLON.SimplificationQueue) {
  21130. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21131. }
  21132. //collision coordinator initialization. For now legacy per default.
  21133. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21134. // Uniform Buffer
  21135. this._createUbo();
  21136. // Default Image processing definition.
  21137. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21138. }
  21139. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21140. /** The fog is deactivated */
  21141. get: function () {
  21142. return Scene._FOGMODE_NONE;
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21148. /** The fog density is following an exponential function */
  21149. get: function () {
  21150. return Scene._FOGMODE_EXP;
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21156. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21157. get: function () {
  21158. return Scene._FOGMODE_EXP2;
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21164. /** The fog density is following a linear function. */
  21165. get: function () {
  21166. return Scene._FOGMODE_LINEAR;
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21172. /**
  21173. * Texture used in all pbr material as the reflection texture.
  21174. * As in the majority of the scene they are the same (exception for multi room and so on),
  21175. * this is easier to reference from here than from all the materials.
  21176. */
  21177. get: function () {
  21178. return this._environmentTexture;
  21179. },
  21180. /**
  21181. * Texture used in all pbr material as the reflection texture.
  21182. * As in the majority of the scene they are the same (exception for multi room and so on),
  21183. * this is easier to set here than in all the materials.
  21184. */
  21185. set: function (value) {
  21186. if (this._environmentTexture === value) {
  21187. return;
  21188. }
  21189. this._environmentTexture = value;
  21190. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21196. /**
  21197. * Default image processing configuration used either in the rendering
  21198. * Forward main pass or through the imageProcessingPostProcess if present.
  21199. * As in the majority of the scene they are the same (exception for multi camera),
  21200. * this is easier to reference from here than from all the materials and post process.
  21201. *
  21202. * No setter as we it is a shared configuration, you can set the values instead.
  21203. */
  21204. get: function () {
  21205. return this._imageProcessingConfiguration;
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21211. get: function () {
  21212. return this._forcePointsCloud;
  21213. },
  21214. set: function (value) {
  21215. if (this._forcePointsCloud === value) {
  21216. return;
  21217. }
  21218. this._forcePointsCloud = value;
  21219. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. Object.defineProperty(Scene.prototype, "onDispose", {
  21225. /** A function to be executed when this scene is disposed. */
  21226. set: function (callback) {
  21227. if (this._onDisposeObserver) {
  21228. this.onDisposeObservable.remove(this._onDisposeObserver);
  21229. }
  21230. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21231. },
  21232. enumerable: true,
  21233. configurable: true
  21234. });
  21235. Object.defineProperty(Scene.prototype, "beforeRender", {
  21236. /** A function to be executed before rendering this scene */
  21237. set: function (callback) {
  21238. if (this._onBeforeRenderObserver) {
  21239. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21240. }
  21241. if (callback) {
  21242. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21243. }
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(Scene.prototype, "afterRender", {
  21249. /** A function to be executed after rendering this scene */
  21250. set: function (callback) {
  21251. if (this._onAfterRenderObserver) {
  21252. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21253. }
  21254. if (callback) {
  21255. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21256. }
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21262. set: function (callback) {
  21263. if (this._onBeforeCameraRenderObserver) {
  21264. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21265. }
  21266. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21272. set: function (callback) {
  21273. if (this._onAfterCameraRenderObserver) {
  21274. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21275. }
  21276. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21282. get: function () {
  21283. if (!this._gamepadManager) {
  21284. this._gamepadManager = new BABYLON.GamepadManager(this);
  21285. }
  21286. return this._gamepadManager;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21292. get: function () {
  21293. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21299. get: function () {
  21300. return this._useRightHandedSystem;
  21301. },
  21302. set: function (value) {
  21303. if (this._useRightHandedSystem === value) {
  21304. return;
  21305. }
  21306. this._useRightHandedSystem = value;
  21307. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Scene.prototype.setStepId = function (newStepId) {
  21313. this._currentStepId = newStepId;
  21314. };
  21315. ;
  21316. Scene.prototype.getStepId = function () {
  21317. return this._currentStepId;
  21318. };
  21319. ;
  21320. Scene.prototype.getInternalStep = function () {
  21321. return this._currentInternalStep;
  21322. };
  21323. ;
  21324. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21325. get: function () {
  21326. return this._fogEnabled;
  21327. },
  21328. /**
  21329. * is fog enabled on this scene.
  21330. */
  21331. set: function (value) {
  21332. if (this._fogEnabled === value) {
  21333. return;
  21334. }
  21335. this._fogEnabled = value;
  21336. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. Object.defineProperty(Scene.prototype, "fogMode", {
  21342. get: function () {
  21343. return this._fogMode;
  21344. },
  21345. set: function (value) {
  21346. if (this._fogMode === value) {
  21347. return;
  21348. }
  21349. this._fogMode = value;
  21350. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21356. get: function () {
  21357. return this._shadowsEnabled;
  21358. },
  21359. set: function (value) {
  21360. if (this._shadowsEnabled === value) {
  21361. return;
  21362. }
  21363. this._shadowsEnabled = value;
  21364. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21370. get: function () {
  21371. return this._lightsEnabled;
  21372. },
  21373. set: function (value) {
  21374. if (this._lightsEnabled === value) {
  21375. return;
  21376. }
  21377. this._lightsEnabled = value;
  21378. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21384. /** The default material used on meshes when no material is affected */
  21385. get: function () {
  21386. if (!this._defaultMaterial) {
  21387. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21388. }
  21389. return this._defaultMaterial;
  21390. },
  21391. /** The default material used on meshes when no material is affected */
  21392. set: function (value) {
  21393. this._defaultMaterial = value;
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21399. get: function () {
  21400. return this._texturesEnabled;
  21401. },
  21402. set: function (value) {
  21403. if (this._texturesEnabled === value) {
  21404. return;
  21405. }
  21406. this._texturesEnabled = value;
  21407. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21408. },
  21409. enumerable: true,
  21410. configurable: true
  21411. });
  21412. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21413. get: function () {
  21414. return this._skeletonsEnabled;
  21415. },
  21416. set: function (value) {
  21417. if (this._skeletonsEnabled === value) {
  21418. return;
  21419. }
  21420. this._skeletonsEnabled = value;
  21421. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21427. get: function () {
  21428. if (!this._postProcessRenderPipelineManager) {
  21429. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21430. }
  21431. return this._postProcessRenderPipelineManager;
  21432. },
  21433. enumerable: true,
  21434. configurable: true
  21435. });
  21436. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21437. get: function () {
  21438. if (!this._mainSoundTrack) {
  21439. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21440. }
  21441. return this._mainSoundTrack;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21447. get: function () {
  21448. return this._alternateRendering;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21454. get: function () {
  21455. return this._frustumPlanes;
  21456. },
  21457. enumerable: true,
  21458. configurable: true
  21459. });
  21460. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21461. /**
  21462. * Gets the current geometry buffer associated to the scene.
  21463. */
  21464. get: function () {
  21465. return this._geometryBufferRenderer;
  21466. },
  21467. /**
  21468. * Sets the current geometry buffer for the scene.
  21469. */
  21470. set: function (geometryBufferRenderer) {
  21471. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21472. this._geometryBufferRenderer = geometryBufferRenderer;
  21473. }
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(Scene.prototype, "debugLayer", {
  21479. // Properties
  21480. get: function () {
  21481. if (!this._debugLayer) {
  21482. this._debugLayer = new BABYLON.DebugLayer(this);
  21483. }
  21484. return this._debugLayer;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21490. get: function () {
  21491. return this._workerCollisions;
  21492. },
  21493. set: function (enabled) {
  21494. if (!BABYLON.CollisionCoordinatorLegacy) {
  21495. return;
  21496. }
  21497. enabled = (enabled && !!Worker);
  21498. this._workerCollisions = enabled;
  21499. if (this.collisionCoordinator) {
  21500. this.collisionCoordinator.destroy();
  21501. }
  21502. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21503. this.collisionCoordinator.init(this);
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21509. get: function () {
  21510. return this._selectionOctree;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21516. /**
  21517. * The mesh that is currently under the pointer.
  21518. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21519. */
  21520. get: function () {
  21521. return this._pointerOverMesh;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(Scene.prototype, "pointerX", {
  21527. /**
  21528. * Current on-screen X position of the pointer
  21529. * @return {number} X position of the pointer
  21530. */
  21531. get: function () {
  21532. return this._pointerX;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Scene.prototype, "pointerY", {
  21538. /**
  21539. * Current on-screen Y position of the pointer
  21540. * @return {number} Y position of the pointer
  21541. */
  21542. get: function () {
  21543. return this._pointerY;
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. Scene.prototype.getCachedMaterial = function () {
  21549. return this._cachedMaterial;
  21550. };
  21551. Scene.prototype.getCachedEffect = function () {
  21552. return this._cachedEffect;
  21553. };
  21554. Scene.prototype.getCachedVisibility = function () {
  21555. return this._cachedVisibility;
  21556. };
  21557. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21558. if (visibility === void 0) { visibility = 1; }
  21559. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21560. };
  21561. Scene.prototype.getBoundingBoxRenderer = function () {
  21562. if (!this._boundingBoxRenderer) {
  21563. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21564. }
  21565. return this._boundingBoxRenderer;
  21566. };
  21567. Scene.prototype.getOutlineRenderer = function () {
  21568. return this._outlineRenderer;
  21569. };
  21570. Scene.prototype.getEngine = function () {
  21571. return this._engine;
  21572. };
  21573. Scene.prototype.getTotalVertices = function () {
  21574. return this._totalVertices.current;
  21575. };
  21576. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21577. get: function () {
  21578. return this._totalVertices;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Scene.prototype.getActiveIndices = function () {
  21584. return this._activeIndices.current;
  21585. };
  21586. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21587. get: function () {
  21588. return this._activeIndices;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Scene.prototype.getActiveParticles = function () {
  21594. return this._activeParticles.current;
  21595. };
  21596. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21597. get: function () {
  21598. return this._activeParticles;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Scene.prototype.getActiveBones = function () {
  21604. return this._activeBones.current;
  21605. };
  21606. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21607. get: function () {
  21608. return this._activeBones;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. // Stats
  21614. Scene.prototype.getInterFramePerfCounter = function () {
  21615. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21616. return 0;
  21617. };
  21618. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21619. get: function () {
  21620. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21621. return null;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Scene.prototype.getLastFrameDuration = function () {
  21627. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21628. return 0;
  21629. };
  21630. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21631. get: function () {
  21632. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21633. return null;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21639. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21640. return 0;
  21641. };
  21642. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21643. get: function () {
  21644. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21645. return null;
  21646. },
  21647. enumerable: true,
  21648. configurable: true
  21649. });
  21650. Scene.prototype.getActiveMeshes = function () {
  21651. return this._activeMeshes;
  21652. };
  21653. Scene.prototype.getRenderTargetsDuration = function () {
  21654. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21655. return 0;
  21656. };
  21657. Scene.prototype.getRenderDuration = function () {
  21658. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21659. return 0;
  21660. };
  21661. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21662. get: function () {
  21663. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21664. return null;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Scene.prototype.getParticlesDuration = function () {
  21670. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21671. return 0;
  21672. };
  21673. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21674. get: function () {
  21675. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21676. return null;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Scene.prototype.getSpritesDuration = function () {
  21682. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21683. return 0;
  21684. };
  21685. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21686. get: function () {
  21687. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21688. return null;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Scene.prototype.getAnimationRatio = function () {
  21694. return this._animationRatio;
  21695. };
  21696. Scene.prototype.getRenderId = function () {
  21697. return this._renderId;
  21698. };
  21699. Scene.prototype.incrementRenderId = function () {
  21700. this._renderId++;
  21701. };
  21702. Scene.prototype._updatePointerPosition = function (evt) {
  21703. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21704. if (!canvasRect) {
  21705. return;
  21706. }
  21707. this._pointerX = evt.clientX - canvasRect.left;
  21708. this._pointerY = evt.clientY - canvasRect.top;
  21709. this._unTranslatedPointerX = this._pointerX;
  21710. this._unTranslatedPointerY = this._pointerY;
  21711. };
  21712. Scene.prototype._createUbo = function () {
  21713. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21714. this._sceneUbo.addUniform("viewProjection", 16);
  21715. this._sceneUbo.addUniform("view", 16);
  21716. };
  21717. Scene.prototype._createAlternateUbo = function () {
  21718. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21719. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21720. this._alternateSceneUbo.addUniform("view", 16);
  21721. };
  21722. // Pointers handling
  21723. /**
  21724. * Use this method to simulate a pointer move on a mesh
  21725. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21726. */
  21727. Scene.prototype.simulatePointerMove = function (pickResult) {
  21728. var evt = new PointerEvent("pointermove");
  21729. return this._processPointerMove(pickResult, evt);
  21730. };
  21731. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21732. var canvas = this._engine.getRenderingCanvas();
  21733. if (!canvas) {
  21734. return this;
  21735. }
  21736. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21737. this.setPointerOverSprite(null);
  21738. this.setPointerOverMesh(pickResult.pickedMesh);
  21739. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21740. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21741. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21742. }
  21743. else {
  21744. canvas.style.cursor = this.hoverCursor;
  21745. }
  21746. }
  21747. else {
  21748. canvas.style.cursor = this.defaultCursor;
  21749. }
  21750. }
  21751. else {
  21752. this.setPointerOverMesh(null);
  21753. // Sprites
  21754. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21755. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21756. this.setPointerOverSprite(pickResult.pickedSprite);
  21757. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21758. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21759. }
  21760. else {
  21761. canvas.style.cursor = this.hoverCursor;
  21762. }
  21763. }
  21764. else {
  21765. this.setPointerOverSprite(null);
  21766. // Restore pointer
  21767. canvas.style.cursor = this.defaultCursor;
  21768. }
  21769. }
  21770. if (pickResult) {
  21771. if (this.onPointerMove) {
  21772. this.onPointerMove(evt, pickResult);
  21773. }
  21774. if (this.onPointerObservable.hasObservers()) {
  21775. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21776. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21777. this.onPointerObservable.notifyObservers(pi, type);
  21778. }
  21779. }
  21780. return this;
  21781. };
  21782. /**
  21783. * Use this method to simulate a pointer down on a mesh
  21784. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21785. */
  21786. Scene.prototype.simulatePointerDown = function (pickResult) {
  21787. var evt = new PointerEvent("pointerdown");
  21788. return this._processPointerDown(pickResult, evt);
  21789. };
  21790. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21791. var _this = this;
  21792. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21793. this._pickedDownMesh = pickResult.pickedMesh;
  21794. var actionManager = pickResult.pickedMesh.actionManager;
  21795. if (actionManager) {
  21796. if (actionManager.hasPickTriggers) {
  21797. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21798. switch (evt.button) {
  21799. case 0:
  21800. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21801. break;
  21802. case 1:
  21803. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21804. break;
  21805. case 2:
  21806. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21807. break;
  21808. }
  21809. }
  21810. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21811. window.setTimeout(function () {
  21812. 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);
  21813. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21814. if (_this._totalPointersPressed !== 0 &&
  21815. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21816. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21817. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21818. _this._startingPointerTime = 0;
  21819. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21820. }
  21821. }
  21822. }, Scene.LongPressDelay);
  21823. }
  21824. }
  21825. }
  21826. if (pickResult) {
  21827. if (this.onPointerDown) {
  21828. this.onPointerDown(evt, pickResult);
  21829. }
  21830. if (this.onPointerObservable.hasObservers()) {
  21831. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21832. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21833. this.onPointerObservable.notifyObservers(pi, type);
  21834. }
  21835. }
  21836. return this;
  21837. };
  21838. /**
  21839. * Use this method to simulate a pointer up on a mesh
  21840. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21841. */
  21842. Scene.prototype.simulatePointerUp = function (pickResult) {
  21843. var evt = new PointerEvent("pointerup");
  21844. var clickInfo = new ClickInfo();
  21845. clickInfo.singleClick = true;
  21846. clickInfo.ignore = true;
  21847. return this._processPointerUp(pickResult, evt, clickInfo);
  21848. };
  21849. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21850. if (pickResult && pickResult && pickResult.pickedMesh) {
  21851. this._pickedUpMesh = pickResult.pickedMesh;
  21852. if (this._pickedDownMesh === this._pickedUpMesh) {
  21853. if (this.onPointerPick) {
  21854. this.onPointerPick(evt, pickResult);
  21855. }
  21856. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21857. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21858. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21859. this.onPointerObservable.notifyObservers(pi, type);
  21860. }
  21861. }
  21862. if (pickResult.pickedMesh.actionManager) {
  21863. if (clickInfo.ignore) {
  21864. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21865. }
  21866. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21867. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21868. }
  21869. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21870. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21871. }
  21872. }
  21873. }
  21874. if (this._pickedDownMesh &&
  21875. this._pickedDownMesh.actionManager &&
  21876. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21877. this._pickedDownMesh !== this._pickedUpMesh) {
  21878. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21879. }
  21880. if (this.onPointerUp) {
  21881. this.onPointerUp(evt, pickResult);
  21882. }
  21883. if (this.onPointerObservable.hasObservers()) {
  21884. if (!clickInfo.ignore) {
  21885. if (!clickInfo.hasSwiped) {
  21886. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21887. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21888. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21889. this.onPointerObservable.notifyObservers(pi, type);
  21890. }
  21891. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21892. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21893. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21894. this.onPointerObservable.notifyObservers(pi, type);
  21895. }
  21896. }
  21897. }
  21898. else {
  21899. var type = BABYLON.PointerEventTypes.POINTERUP;
  21900. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21901. this.onPointerObservable.notifyObservers(pi, type);
  21902. }
  21903. }
  21904. return this;
  21905. };
  21906. /**
  21907. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21908. * @param attachUp defines if you want to attach events to pointerup
  21909. * @param attachDown defines if you want to attach events to pointerdown
  21910. * @param attachMove defines if you want to attach events to pointermove
  21911. */
  21912. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21913. var _this = this;
  21914. if (attachUp === void 0) { attachUp = true; }
  21915. if (attachDown === void 0) { attachDown = true; }
  21916. if (attachMove === void 0) { attachMove = true; }
  21917. this._initActionManager = function (act, clickInfo) {
  21918. if (!_this._meshPickProceed) {
  21919. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21920. _this._currentPickResult = pickResult;
  21921. if (pickResult) {
  21922. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21923. }
  21924. _this._meshPickProceed = true;
  21925. }
  21926. return act;
  21927. };
  21928. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21929. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21930. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21931. btn !== _this._previousButtonPressed) {
  21932. _this._doubleClickOccured = false;
  21933. clickInfo.singleClick = true;
  21934. clickInfo.ignore = false;
  21935. cb(clickInfo, _this._currentPickResult);
  21936. }
  21937. };
  21938. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21939. var clickInfo = new ClickInfo();
  21940. _this._currentPickResult = null;
  21941. var act = null;
  21942. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21943. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21944. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21945. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21946. act = _this._initActionManager(act, clickInfo);
  21947. if (act)
  21948. checkPicking = act.hasPickTriggers;
  21949. }
  21950. if (checkPicking) {
  21951. var btn = evt.button;
  21952. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21953. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21954. if (!clickInfo.hasSwiped) {
  21955. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21956. if (!checkSingleClickImmediately) {
  21957. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21958. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21959. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21960. act = _this._initActionManager(act, clickInfo);
  21961. if (act)
  21962. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21963. }
  21964. }
  21965. if (checkSingleClickImmediately) {
  21966. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21967. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21968. btn !== _this._previousButtonPressed) {
  21969. clickInfo.singleClick = true;
  21970. cb(clickInfo, _this._currentPickResult);
  21971. }
  21972. }
  21973. else {
  21974. // wait that no double click has been raised during the double click delay
  21975. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21976. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21977. }
  21978. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21979. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21980. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21981. act = _this._initActionManager(act, clickInfo);
  21982. if (act)
  21983. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21984. }
  21985. if (checkDoubleClick) {
  21986. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21987. if (btn === _this._previousButtonPressed &&
  21988. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21989. !_this._doubleClickOccured) {
  21990. // pointer has not moved for 2 clicks, it's a double click
  21991. if (!clickInfo.hasSwiped &&
  21992. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21993. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21994. _this._previousStartingPointerTime = 0;
  21995. _this._doubleClickOccured = true;
  21996. clickInfo.doubleClick = true;
  21997. clickInfo.ignore = false;
  21998. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21999. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22000. }
  22001. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22002. cb(clickInfo, _this._currentPickResult);
  22003. }
  22004. else {
  22005. _this._doubleClickOccured = false;
  22006. _this._previousStartingPointerTime = _this._startingPointerTime;
  22007. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22008. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22009. _this._previousButtonPressed = btn;
  22010. if (Scene.ExclusiveDoubleClickMode) {
  22011. if (_this._previousDelayedSimpleClickTimeout) {
  22012. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22013. }
  22014. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22015. cb(clickInfo, _this._previousPickResult);
  22016. }
  22017. else {
  22018. cb(clickInfo, _this._currentPickResult);
  22019. }
  22020. }
  22021. }
  22022. else {
  22023. _this._doubleClickOccured = false;
  22024. _this._previousStartingPointerTime = _this._startingPointerTime;
  22025. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22026. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22027. _this._previousButtonPressed = btn;
  22028. }
  22029. }
  22030. }
  22031. }
  22032. clickInfo.ignore = true;
  22033. cb(clickInfo, _this._currentPickResult);
  22034. };
  22035. this._spritePredicate = function (sprite) {
  22036. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22037. };
  22038. this._onPointerMove = function (evt) {
  22039. _this._updatePointerPosition(evt);
  22040. // PreObservable support
  22041. if (_this.onPrePointerObservable.hasObservers()) {
  22042. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22043. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22044. _this.onPrePointerObservable.notifyObservers(pi, type);
  22045. if (pi.skipOnPointerObservable) {
  22046. return;
  22047. }
  22048. }
  22049. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22050. return;
  22051. }
  22052. if (!_this.pointerMovePredicate) {
  22053. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22054. }
  22055. // Meshes
  22056. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22057. _this._processPointerMove(pickResult, evt);
  22058. };
  22059. this._onPointerDown = function (evt) {
  22060. _this._totalPointersPressed++;
  22061. _this._pickedDownMesh = null;
  22062. _this._meshPickProceed = false;
  22063. _this._updatePointerPosition(evt);
  22064. if (_this.preventDefaultOnPointerDown && canvas) {
  22065. evt.preventDefault();
  22066. canvas.focus();
  22067. }
  22068. // PreObservable support
  22069. if (_this.onPrePointerObservable.hasObservers()) {
  22070. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22071. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22072. _this.onPrePointerObservable.notifyObservers(pi, type);
  22073. if (pi.skipOnPointerObservable) {
  22074. return;
  22075. }
  22076. }
  22077. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22078. return;
  22079. }
  22080. _this._startingPointerPosition.x = _this._pointerX;
  22081. _this._startingPointerPosition.y = _this._pointerY;
  22082. _this._startingPointerTime = new Date().getTime();
  22083. if (!_this.pointerDownPredicate) {
  22084. _this.pointerDownPredicate = function (mesh) {
  22085. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22086. };
  22087. }
  22088. // Meshes
  22089. _this._pickedDownMesh = null;
  22090. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22091. _this._processPointerDown(pickResult, evt);
  22092. // Sprites
  22093. _this._pickedDownSprite = null;
  22094. if (_this.spriteManagers.length > 0) {
  22095. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22096. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22097. if (pickResult.pickedSprite.actionManager) {
  22098. _this._pickedDownSprite = pickResult.pickedSprite;
  22099. switch (evt.button) {
  22100. case 0:
  22101. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22102. break;
  22103. case 1:
  22104. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22105. break;
  22106. case 2:
  22107. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22108. break;
  22109. }
  22110. if (pickResult.pickedSprite.actionManager) {
  22111. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22112. }
  22113. }
  22114. }
  22115. }
  22116. };
  22117. this._onPointerUp = function (evt) {
  22118. if (_this._totalPointersPressed === 0) {
  22119. return; // So we need to test it the pointer down was pressed before.
  22120. }
  22121. _this._totalPointersPressed--;
  22122. _this._pickedUpMesh = null;
  22123. _this._meshPickProceed = false;
  22124. _this._updatePointerPosition(evt);
  22125. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22126. // PreObservable support
  22127. if (_this.onPrePointerObservable.hasObservers()) {
  22128. if (!clickInfo.ignore) {
  22129. if (!clickInfo.hasSwiped) {
  22130. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22131. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22132. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22133. _this.onPrePointerObservable.notifyObservers(pi, type);
  22134. if (pi.skipOnPointerObservable) {
  22135. return;
  22136. }
  22137. }
  22138. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22139. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22140. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22141. _this.onPrePointerObservable.notifyObservers(pi, type);
  22142. if (pi.skipOnPointerObservable) {
  22143. return;
  22144. }
  22145. }
  22146. }
  22147. }
  22148. else {
  22149. var type = BABYLON.PointerEventTypes.POINTERUP;
  22150. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22151. _this.onPrePointerObservable.notifyObservers(pi, type);
  22152. if (pi.skipOnPointerObservable) {
  22153. return;
  22154. }
  22155. }
  22156. }
  22157. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22158. return;
  22159. }
  22160. if (!_this.pointerUpPredicate) {
  22161. _this.pointerUpPredicate = function (mesh) {
  22162. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22163. };
  22164. }
  22165. // Meshes
  22166. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22167. _this._initActionManager(null, clickInfo);
  22168. }
  22169. if (!pickResult) {
  22170. pickResult = _this._currentPickResult;
  22171. }
  22172. _this._processPointerUp(pickResult, evt, clickInfo);
  22173. // Sprites
  22174. if (_this.spriteManagers.length > 0) {
  22175. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22176. if (spritePickResult) {
  22177. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22178. if (spritePickResult.pickedSprite.actionManager) {
  22179. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22180. if (spritePickResult.pickedSprite.actionManager) {
  22181. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22182. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22183. }
  22184. }
  22185. }
  22186. }
  22187. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22188. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22189. }
  22190. }
  22191. }
  22192. _this._previousPickResult = _this._currentPickResult;
  22193. });
  22194. };
  22195. this._onKeyDown = function (evt) {
  22196. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22197. if (_this.onPreKeyboardObservable.hasObservers()) {
  22198. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22199. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22200. if (pi.skipOnPointerObservable) {
  22201. return;
  22202. }
  22203. }
  22204. if (_this.onKeyboardObservable.hasObservers()) {
  22205. var pi = new BABYLON.KeyboardInfo(type, evt);
  22206. _this.onKeyboardObservable.notifyObservers(pi, type);
  22207. }
  22208. if (_this.actionManager) {
  22209. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22210. }
  22211. };
  22212. this._onKeyUp = function (evt) {
  22213. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22214. if (_this.onPreKeyboardObservable.hasObservers()) {
  22215. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22216. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22217. if (pi.skipOnPointerObservable) {
  22218. return;
  22219. }
  22220. }
  22221. if (_this.onKeyboardObservable.hasObservers()) {
  22222. var pi = new BABYLON.KeyboardInfo(type, evt);
  22223. _this.onKeyboardObservable.notifyObservers(pi, type);
  22224. }
  22225. if (_this.actionManager) {
  22226. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22227. }
  22228. };
  22229. var engine = this.getEngine();
  22230. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22231. if (!canvas) {
  22232. return;
  22233. }
  22234. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22235. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22236. });
  22237. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22238. if (!canvas) {
  22239. return;
  22240. }
  22241. canvas.removeEventListener("keydown", _this._onKeyDown);
  22242. canvas.removeEventListener("keyup", _this._onKeyUp);
  22243. });
  22244. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22245. var canvas = this._engine.getRenderingCanvas();
  22246. if (!canvas) {
  22247. return;
  22248. }
  22249. if (attachMove) {
  22250. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22251. // Wheel
  22252. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22253. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22254. }
  22255. if (attachDown) {
  22256. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22257. }
  22258. if (attachUp) {
  22259. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22260. }
  22261. canvas.tabIndex = 1;
  22262. };
  22263. Scene.prototype.detachControl = function () {
  22264. var engine = this.getEngine();
  22265. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22266. var canvas = engine.getRenderingCanvas();
  22267. if (!canvas) {
  22268. return;
  22269. }
  22270. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22271. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22272. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22273. if (this._onCanvasBlurObserver) {
  22274. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22275. }
  22276. if (this._onCanvasFocusObserver) {
  22277. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22278. }
  22279. // Wheel
  22280. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22281. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22282. // Keyboard
  22283. canvas.removeEventListener("keydown", this._onKeyDown);
  22284. canvas.removeEventListener("keyup", this._onKeyUp);
  22285. // Observables
  22286. this.onKeyboardObservable.clear();
  22287. this.onPreKeyboardObservable.clear();
  22288. this.onPointerObservable.clear();
  22289. this.onPrePointerObservable.clear();
  22290. };
  22291. /**
  22292. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22293. * Delay loaded resources are not taking in account
  22294. * @return true if all required resources are ready
  22295. */
  22296. Scene.prototype.isReady = function () {
  22297. if (this._isDisposed) {
  22298. return false;
  22299. }
  22300. if (this._pendingData.length > 0) {
  22301. return false;
  22302. }
  22303. var index;
  22304. var engine = this.getEngine();
  22305. // Geometries
  22306. for (index = 0; index < this._geometries.length; index++) {
  22307. var geometry = this._geometries[index];
  22308. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22309. return false;
  22310. }
  22311. }
  22312. // Meshes
  22313. for (index = 0; index < this.meshes.length; index++) {
  22314. var mesh = this.meshes[index];
  22315. if (!mesh.isEnabled()) {
  22316. continue;
  22317. }
  22318. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22319. continue;
  22320. }
  22321. if (!mesh.isReady()) {
  22322. return false;
  22323. }
  22324. // Effect layers
  22325. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22326. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22327. var layer = _a[_i];
  22328. if (!layer.hasMesh(mesh)) {
  22329. continue;
  22330. }
  22331. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22332. var subMesh = _c[_b];
  22333. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22334. return false;
  22335. }
  22336. }
  22337. }
  22338. }
  22339. return true;
  22340. };
  22341. Scene.prototype.resetCachedMaterial = function () {
  22342. this._cachedMaterial = null;
  22343. this._cachedEffect = null;
  22344. this._cachedVisibility = null;
  22345. };
  22346. Scene.prototype.registerBeforeRender = function (func) {
  22347. this.onBeforeRenderObservable.add(func);
  22348. };
  22349. Scene.prototype.unregisterBeforeRender = function (func) {
  22350. this.onBeforeRenderObservable.removeCallback(func);
  22351. };
  22352. Scene.prototype.registerAfterRender = function (func) {
  22353. this.onAfterRenderObservable.add(func);
  22354. };
  22355. Scene.prototype.unregisterAfterRender = function (func) {
  22356. this.onAfterRenderObservable.removeCallback(func);
  22357. };
  22358. Scene.prototype._executeOnceBeforeRender = function (func) {
  22359. var _this = this;
  22360. var execFunc = function () {
  22361. func();
  22362. setTimeout(function () {
  22363. _this.unregisterBeforeRender(execFunc);
  22364. });
  22365. };
  22366. this.registerBeforeRender(execFunc);
  22367. };
  22368. /**
  22369. * The provided function will run before render once and will be disposed afterwards.
  22370. * A timeout delay can be provided so that the function will be executed in N ms.
  22371. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22372. * @param func The function to be executed.
  22373. * @param timeout optional delay in ms
  22374. */
  22375. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22376. var _this = this;
  22377. if (timeout !== undefined) {
  22378. setTimeout(function () {
  22379. _this._executeOnceBeforeRender(func);
  22380. }, timeout);
  22381. }
  22382. else {
  22383. this._executeOnceBeforeRender(func);
  22384. }
  22385. };
  22386. Scene.prototype._addPendingData = function (data) {
  22387. this._pendingData.push(data);
  22388. };
  22389. Scene.prototype._removePendingData = function (data) {
  22390. var wasLoading = this.isLoading;
  22391. var index = this._pendingData.indexOf(data);
  22392. if (index !== -1) {
  22393. this._pendingData.splice(index, 1);
  22394. }
  22395. if (wasLoading && !this.isLoading) {
  22396. this.onDataLoadedObservable.notifyObservers(this);
  22397. }
  22398. };
  22399. Scene.prototype.getWaitingItemsCount = function () {
  22400. return this._pendingData.length;
  22401. };
  22402. Object.defineProperty(Scene.prototype, "isLoading", {
  22403. get: function () {
  22404. return this._pendingData.length > 0;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. /**
  22410. * Registers a function to be executed when the scene is ready.
  22411. * @param {Function} func - the function to be executed.
  22412. */
  22413. Scene.prototype.executeWhenReady = function (func) {
  22414. var _this = this;
  22415. this.onReadyObservable.add(func);
  22416. if (this._executeWhenReadyTimeoutId !== -1) {
  22417. return;
  22418. }
  22419. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22420. _this._checkIsReady();
  22421. }, 150);
  22422. };
  22423. /**
  22424. * Returns a promise that resolves when the scene is ready.
  22425. * @returns A promise that resolves when the scene is ready.
  22426. */
  22427. Scene.prototype.whenReadyAsync = function () {
  22428. var _this = this;
  22429. return new Promise(function (resolve) {
  22430. _this.executeWhenReady(function () {
  22431. resolve();
  22432. });
  22433. });
  22434. };
  22435. Scene.prototype._checkIsReady = function () {
  22436. var _this = this;
  22437. if (this.isReady()) {
  22438. this.onReadyObservable.notifyObservers(this);
  22439. this.onReadyObservable.clear();
  22440. this._executeWhenReadyTimeoutId = -1;
  22441. return;
  22442. }
  22443. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22444. _this._checkIsReady();
  22445. }, 150);
  22446. };
  22447. // Animations
  22448. /**
  22449. * Will start the animation sequence of a given target
  22450. * @param target - the target
  22451. * @param {number} from - from which frame should animation start
  22452. * @param {number} to - till which frame should animation run.
  22453. * @param {boolean} [loop] - should the animation loop
  22454. * @param {number} [speedRatio] - the speed in which to run the animation
  22455. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22456. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22457. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22458. * See BABYLON.Animatable
  22459. */
  22460. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22461. if (speedRatio === void 0) { speedRatio = 1.0; }
  22462. if (from > to && speedRatio > 0) {
  22463. speedRatio *= -1;
  22464. }
  22465. this.stopAnimation(target);
  22466. if (!animatable) {
  22467. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22468. }
  22469. // Local animations
  22470. if (target.animations) {
  22471. animatable.appendAnimations(target, target.animations);
  22472. }
  22473. // Children animations
  22474. if (target.getAnimatables) {
  22475. var animatables = target.getAnimatables();
  22476. for (var index = 0; index < animatables.length; index++) {
  22477. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22478. }
  22479. }
  22480. animatable.reset();
  22481. return animatable;
  22482. };
  22483. /**
  22484. * Begin a new animation on a given node
  22485. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22486. * @param {BABYLON.Animation[]} defines the list of animations to start
  22487. * @param {number} from defines the initial value
  22488. * @param {number} to defines the final value
  22489. * @param {boolean} loop defines if you want animation to loop (off by default)
  22490. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22491. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22492. * @returns the list of created animatables
  22493. */
  22494. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22495. if (speedRatio === undefined) {
  22496. speedRatio = 1.0;
  22497. }
  22498. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22499. return animatable;
  22500. };
  22501. /**
  22502. * Begin a new animation on a given node and its hierarchy
  22503. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22504. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  22505. * @param {BABYLON.Animation[]} defines the list of animations to start
  22506. * @param {number} from defines the initial value
  22507. * @param {number} to defines the final value
  22508. * @param {boolean} loop defines if you want animation to loop (off by default)
  22509. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22510. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22511. * @returns the list of animatables created for all nodes
  22512. */
  22513. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22514. var children = target.getDescendants(directDescendantsOnly);
  22515. var result = [];
  22516. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22517. var child = children_1[_i];
  22518. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22519. }
  22520. return result;
  22521. };
  22522. Scene.prototype.getAnimatableByTarget = function (target) {
  22523. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22524. if (this._activeAnimatables[index].target === target) {
  22525. return this._activeAnimatables[index];
  22526. }
  22527. }
  22528. return null;
  22529. };
  22530. Object.defineProperty(Scene.prototype, "animatables", {
  22531. get: function () {
  22532. return this._activeAnimatables;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. /**
  22538. * Will stop the animation of the given target
  22539. * @param target - the target
  22540. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22541. * @see beginAnimation
  22542. */
  22543. Scene.prototype.stopAnimation = function (target, animationName) {
  22544. var animatable = this.getAnimatableByTarget(target);
  22545. if (animatable) {
  22546. animatable.stop(animationName);
  22547. }
  22548. };
  22549. /**
  22550. * Stops and removes all animations that have been applied to the scene
  22551. */
  22552. Scene.prototype.stopAllAnimations = function () {
  22553. if (this._activeAnimatables) {
  22554. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22555. this._activeAnimatables[i].stop();
  22556. }
  22557. this._activeAnimatables = [];
  22558. }
  22559. };
  22560. Scene.prototype._animate = function () {
  22561. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22562. return;
  22563. }
  22564. // Getting time
  22565. var now = BABYLON.Tools.Now;
  22566. if (!this._animationTimeLast) {
  22567. if (this._pendingData.length > 0) {
  22568. return;
  22569. }
  22570. this._animationTimeLast = now;
  22571. }
  22572. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22573. this._animationTime += deltaTime;
  22574. this._animationTimeLast = now;
  22575. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22576. this._activeAnimatables[index]._animate(this._animationTime);
  22577. }
  22578. };
  22579. // Matrix
  22580. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22581. this._useAlternateCameraConfiguration = active;
  22582. };
  22583. Scene.prototype.getViewMatrix = function () {
  22584. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22585. };
  22586. Scene.prototype.getProjectionMatrix = function () {
  22587. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22588. };
  22589. Scene.prototype.getTransformMatrix = function () {
  22590. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22591. };
  22592. Scene.prototype.setTransformMatrix = function (view, projection) {
  22593. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22594. return;
  22595. }
  22596. this._viewUpdateFlag = view.updateFlag;
  22597. this._projectionUpdateFlag = projection.updateFlag;
  22598. this._viewMatrix = view;
  22599. this._projectionMatrix = projection;
  22600. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22601. // Update frustum
  22602. if (!this._frustumPlanes) {
  22603. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22604. }
  22605. else {
  22606. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22607. }
  22608. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22609. var otherCamera = this.activeCamera._alternateCamera;
  22610. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22611. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22612. }
  22613. if (this._sceneUbo.useUbo) {
  22614. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22615. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22616. this._sceneUbo.update();
  22617. }
  22618. };
  22619. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22620. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22621. return;
  22622. }
  22623. this._alternateViewUpdateFlag = view.updateFlag;
  22624. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22625. this._alternateViewMatrix = view;
  22626. this._alternateProjectionMatrix = projection;
  22627. if (!this._alternateTransformMatrix) {
  22628. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22629. }
  22630. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22631. if (!this._alternateSceneUbo) {
  22632. this._createAlternateUbo();
  22633. }
  22634. if (this._alternateSceneUbo.useUbo) {
  22635. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22636. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22637. this._alternateSceneUbo.update();
  22638. }
  22639. };
  22640. Scene.prototype.getSceneUniformBuffer = function () {
  22641. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22642. };
  22643. // Methods
  22644. Scene.prototype.getUniqueId = function () {
  22645. var result = Scene._uniqueIdCounter;
  22646. Scene._uniqueIdCounter++;
  22647. return result;
  22648. };
  22649. Scene.prototype.addMesh = function (newMesh) {
  22650. this.meshes.push(newMesh);
  22651. //notify the collision coordinator
  22652. if (this.collisionCoordinator) {
  22653. this.collisionCoordinator.onMeshAdded(newMesh);
  22654. }
  22655. newMesh._resyncLightSources();
  22656. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22657. };
  22658. Scene.prototype.removeMesh = function (toRemove) {
  22659. var index = this.meshes.indexOf(toRemove);
  22660. if (index !== -1) {
  22661. // Remove from the scene if mesh found
  22662. this.meshes.splice(index, 1);
  22663. }
  22664. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22665. return index;
  22666. };
  22667. Scene.prototype.addTransformNode = function (newTransformNode) {
  22668. this.transformNodes.push(newTransformNode);
  22669. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22670. };
  22671. Scene.prototype.removeTransformNode = function (toRemove) {
  22672. var index = this.transformNodes.indexOf(toRemove);
  22673. if (index !== -1) {
  22674. // Remove from the scene if found
  22675. this.transformNodes.splice(index, 1);
  22676. }
  22677. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22678. return index;
  22679. };
  22680. Scene.prototype.removeSkeleton = function (toRemove) {
  22681. var index = this.skeletons.indexOf(toRemove);
  22682. if (index !== -1) {
  22683. // Remove from the scene if found
  22684. this.skeletons.splice(index, 1);
  22685. }
  22686. return index;
  22687. };
  22688. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22689. var index = this.morphTargetManagers.indexOf(toRemove);
  22690. if (index !== -1) {
  22691. // Remove from the scene if found
  22692. this.morphTargetManagers.splice(index, 1);
  22693. }
  22694. return index;
  22695. };
  22696. Scene.prototype.removeLight = function (toRemove) {
  22697. var index = this.lights.indexOf(toRemove);
  22698. if (index !== -1) {
  22699. // Remove from meshes
  22700. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22701. var mesh = _a[_i];
  22702. mesh._removeLightSource(toRemove);
  22703. }
  22704. // Remove from the scene if mesh found
  22705. this.lights.splice(index, 1);
  22706. this.sortLightsByPriority();
  22707. }
  22708. this.onLightRemovedObservable.notifyObservers(toRemove);
  22709. return index;
  22710. };
  22711. Scene.prototype.removeCamera = function (toRemove) {
  22712. var index = this.cameras.indexOf(toRemove);
  22713. if (index !== -1) {
  22714. // Remove from the scene if mesh found
  22715. this.cameras.splice(index, 1);
  22716. }
  22717. // Remove from activeCameras
  22718. var index2 = this.activeCameras.indexOf(toRemove);
  22719. if (index2 !== -1) {
  22720. // Remove from the scene if mesh found
  22721. this.activeCameras.splice(index2, 1);
  22722. }
  22723. // Reset the activeCamera
  22724. if (this.activeCamera === toRemove) {
  22725. if (this.cameras.length > 0) {
  22726. this.activeCamera = this.cameras[0];
  22727. }
  22728. else {
  22729. this.activeCamera = null;
  22730. }
  22731. }
  22732. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22733. return index;
  22734. };
  22735. Scene.prototype.removeParticleSystem = function (toRemove) {
  22736. var index = this.particleSystems.indexOf(toRemove);
  22737. if (index !== -1) {
  22738. this.particleSystems.splice(index, 1);
  22739. }
  22740. return index;
  22741. };
  22742. ;
  22743. Scene.prototype.removeAnimation = function (toRemove) {
  22744. var index = this.animations.indexOf(toRemove);
  22745. if (index !== -1) {
  22746. this.animations.splice(index, 1);
  22747. }
  22748. return index;
  22749. };
  22750. ;
  22751. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22752. var index = this.multiMaterials.indexOf(toRemove);
  22753. if (index !== -1) {
  22754. this.multiMaterials.splice(index, 1);
  22755. }
  22756. return index;
  22757. };
  22758. ;
  22759. Scene.prototype.removeMaterial = function (toRemove) {
  22760. var index = this.materials.indexOf(toRemove);
  22761. if (index !== -1) {
  22762. this.materials.splice(index, 1);
  22763. }
  22764. return index;
  22765. };
  22766. ;
  22767. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22768. var index = this.lensFlareSystems.indexOf(toRemove);
  22769. if (index !== -1) {
  22770. this.lensFlareSystems.splice(index, 1);
  22771. }
  22772. return index;
  22773. };
  22774. ;
  22775. Scene.prototype.removeActionManager = function (toRemove) {
  22776. var index = this._actionManagers.indexOf(toRemove);
  22777. if (index !== -1) {
  22778. this._actionManagers.splice(index, 1);
  22779. }
  22780. return index;
  22781. };
  22782. ;
  22783. Scene.prototype.addLight = function (newLight) {
  22784. this.lights.push(newLight);
  22785. this.sortLightsByPriority();
  22786. // Add light to all meshes (To support if the light is removed and then readded)
  22787. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22788. var mesh = _a[_i];
  22789. if (mesh._lightSources.indexOf(newLight) === -1) {
  22790. mesh._lightSources.push(newLight);
  22791. mesh._resyncLightSources();
  22792. }
  22793. }
  22794. this.onNewLightAddedObservable.notifyObservers(newLight);
  22795. };
  22796. Scene.prototype.sortLightsByPriority = function () {
  22797. if (this.requireLightSorting) {
  22798. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22799. }
  22800. };
  22801. Scene.prototype.addCamera = function (newCamera) {
  22802. this.cameras.push(newCamera);
  22803. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22804. };
  22805. Scene.prototype.addSkeleton = function (newSkeleton) {
  22806. this.skeletons.push(newSkeleton);
  22807. };
  22808. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22809. this.particleSystems.push(newParticleSystem);
  22810. };
  22811. Scene.prototype.addAnimation = function (newAnimation) {
  22812. this.animations.push(newAnimation);
  22813. };
  22814. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22815. this.multiMaterials.push(newMultiMaterial);
  22816. };
  22817. Scene.prototype.addMaterial = function (newMaterial) {
  22818. this.materials.push(newMaterial);
  22819. };
  22820. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22821. this.morphTargetManagers.push(newMorphTargetManager);
  22822. };
  22823. Scene.prototype.addGeometry = function (newGeometrie) {
  22824. this._geometries.push(newGeometrie);
  22825. };
  22826. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22827. this.lensFlareSystems.push(newLensFlareSystem);
  22828. };
  22829. Scene.prototype.addActionManager = function (newActionManager) {
  22830. this._actionManagers.push(newActionManager);
  22831. };
  22832. /**
  22833. * Switch active camera
  22834. * @param {Camera} newCamera - new active camera
  22835. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22836. */
  22837. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22838. if (attachControl === void 0) { attachControl = true; }
  22839. var canvas = this._engine.getRenderingCanvas();
  22840. if (!canvas) {
  22841. return;
  22842. }
  22843. if (this.activeCamera) {
  22844. this.activeCamera.detachControl(canvas);
  22845. }
  22846. this.activeCamera = newCamera;
  22847. if (attachControl) {
  22848. newCamera.attachControl(canvas);
  22849. }
  22850. };
  22851. /**
  22852. * sets the active camera of the scene using its ID
  22853. * @param {string} id - the camera's ID
  22854. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22855. * @see activeCamera
  22856. */
  22857. Scene.prototype.setActiveCameraByID = function (id) {
  22858. var camera = this.getCameraByID(id);
  22859. if (camera) {
  22860. this.activeCamera = camera;
  22861. return camera;
  22862. }
  22863. return null;
  22864. };
  22865. /**
  22866. * sets the active camera of the scene using its name
  22867. * @param {string} name - the camera's name
  22868. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22869. * @see activeCamera
  22870. */
  22871. Scene.prototype.setActiveCameraByName = function (name) {
  22872. var camera = this.getCameraByName(name);
  22873. if (camera) {
  22874. this.activeCamera = camera;
  22875. return camera;
  22876. }
  22877. return null;
  22878. };
  22879. /**
  22880. * get an animation group using its name
  22881. * @param {string} the material's name
  22882. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22883. */
  22884. Scene.prototype.getAnimationGroupByName = function (name) {
  22885. for (var index = 0; index < this.animationGroups.length; index++) {
  22886. if (this.animationGroups[index].name === name) {
  22887. return this.animationGroups[index];
  22888. }
  22889. }
  22890. return null;
  22891. };
  22892. /**
  22893. * get a material using its id
  22894. * @param {string} the material's ID
  22895. * @return {BABYLON.Material|null} the material or null if none found.
  22896. */
  22897. Scene.prototype.getMaterialByID = function (id) {
  22898. for (var index = 0; index < this.materials.length; index++) {
  22899. if (this.materials[index].id === id) {
  22900. return this.materials[index];
  22901. }
  22902. }
  22903. return null;
  22904. };
  22905. /**
  22906. * get a material using its name
  22907. * @param {string} the material's name
  22908. * @return {BABYLON.Material|null} the material or null if none found.
  22909. */
  22910. Scene.prototype.getMaterialByName = function (name) {
  22911. for (var index = 0; index < this.materials.length; index++) {
  22912. if (this.materials[index].name === name) {
  22913. return this.materials[index];
  22914. }
  22915. }
  22916. return null;
  22917. };
  22918. Scene.prototype.getLensFlareSystemByName = function (name) {
  22919. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22920. if (this.lensFlareSystems[index].name === name) {
  22921. return this.lensFlareSystems[index];
  22922. }
  22923. }
  22924. return null;
  22925. };
  22926. Scene.prototype.getLensFlareSystemByID = function (id) {
  22927. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22928. if (this.lensFlareSystems[index].id === id) {
  22929. return this.lensFlareSystems[index];
  22930. }
  22931. }
  22932. return null;
  22933. };
  22934. Scene.prototype.getCameraByID = function (id) {
  22935. for (var index = 0; index < this.cameras.length; index++) {
  22936. if (this.cameras[index].id === id) {
  22937. return this.cameras[index];
  22938. }
  22939. }
  22940. return null;
  22941. };
  22942. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22943. for (var index = 0; index < this.cameras.length; index++) {
  22944. if (this.cameras[index].uniqueId === uniqueId) {
  22945. return this.cameras[index];
  22946. }
  22947. }
  22948. return null;
  22949. };
  22950. /**
  22951. * get a camera using its name
  22952. * @param {string} the camera's name
  22953. * @return {BABYLON.Camera|null} the camera or null if none found.
  22954. */
  22955. Scene.prototype.getCameraByName = function (name) {
  22956. for (var index = 0; index < this.cameras.length; index++) {
  22957. if (this.cameras[index].name === name) {
  22958. return this.cameras[index];
  22959. }
  22960. }
  22961. return null;
  22962. };
  22963. /**
  22964. * get a bone using its id
  22965. * @param {string} the bone's id
  22966. * @return {BABYLON.Bone|null} the bone or null if not found
  22967. */
  22968. Scene.prototype.getBoneByID = function (id) {
  22969. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22970. var skeleton = this.skeletons[skeletonIndex];
  22971. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22972. if (skeleton.bones[boneIndex].id === id) {
  22973. return skeleton.bones[boneIndex];
  22974. }
  22975. }
  22976. }
  22977. return null;
  22978. };
  22979. /**
  22980. * get a bone using its id
  22981. * @param {string} the bone's name
  22982. * @return {BABYLON.Bone|null} the bone or null if not found
  22983. */
  22984. Scene.prototype.getBoneByName = function (name) {
  22985. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22986. var skeleton = this.skeletons[skeletonIndex];
  22987. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22988. if (skeleton.bones[boneIndex].name === name) {
  22989. return skeleton.bones[boneIndex];
  22990. }
  22991. }
  22992. }
  22993. return null;
  22994. };
  22995. /**
  22996. * get a light node using its name
  22997. * @param {string} the light's name
  22998. * @return {BABYLON.Light|null} the light or null if none found.
  22999. */
  23000. Scene.prototype.getLightByName = function (name) {
  23001. for (var index = 0; index < this.lights.length; index++) {
  23002. if (this.lights[index].name === name) {
  23003. return this.lights[index];
  23004. }
  23005. }
  23006. return null;
  23007. };
  23008. /**
  23009. * get a light node using its ID
  23010. * @param {string} the light's id
  23011. * @return {BABYLON.Light|null} the light or null if none found.
  23012. */
  23013. Scene.prototype.getLightByID = function (id) {
  23014. for (var index = 0; index < this.lights.length; index++) {
  23015. if (this.lights[index].id === id) {
  23016. return this.lights[index];
  23017. }
  23018. }
  23019. return null;
  23020. };
  23021. /**
  23022. * get a light node using its scene-generated unique ID
  23023. * @param {number} the light's unique id
  23024. * @return {BABYLON.Light|null} the light or null if none found.
  23025. */
  23026. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23027. for (var index = 0; index < this.lights.length; index++) {
  23028. if (this.lights[index].uniqueId === uniqueId) {
  23029. return this.lights[index];
  23030. }
  23031. }
  23032. return null;
  23033. };
  23034. /**
  23035. * get a particle system by id
  23036. * @param id {number} the particle system id
  23037. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23038. */
  23039. Scene.prototype.getParticleSystemByID = function (id) {
  23040. for (var index = 0; index < this.particleSystems.length; index++) {
  23041. if (this.particleSystems[index].id === id) {
  23042. return this.particleSystems[index];
  23043. }
  23044. }
  23045. return null;
  23046. };
  23047. /**
  23048. * get a geometry using its ID
  23049. * @param {string} the geometry's id
  23050. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23051. */
  23052. Scene.prototype.getGeometryByID = function (id) {
  23053. for (var index = 0; index < this._geometries.length; index++) {
  23054. if (this._geometries[index].id === id) {
  23055. return this._geometries[index];
  23056. }
  23057. }
  23058. return null;
  23059. };
  23060. /**
  23061. * add a new geometry to this scene.
  23062. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23063. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23064. * @return {boolean} was the geometry added or not
  23065. */
  23066. Scene.prototype.pushGeometry = function (geometry, force) {
  23067. if (!force && this.getGeometryByID(geometry.id)) {
  23068. return false;
  23069. }
  23070. this._geometries.push(geometry);
  23071. //notify the collision coordinator
  23072. if (this.collisionCoordinator) {
  23073. this.collisionCoordinator.onGeometryAdded(geometry);
  23074. }
  23075. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23076. return true;
  23077. };
  23078. /**
  23079. * Removes an existing geometry
  23080. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23081. * @return {boolean} was the geometry removed or not
  23082. */
  23083. Scene.prototype.removeGeometry = function (geometry) {
  23084. var index = this._geometries.indexOf(geometry);
  23085. if (index > -1) {
  23086. this._geometries.splice(index, 1);
  23087. //notify the collision coordinator
  23088. if (this.collisionCoordinator) {
  23089. this.collisionCoordinator.onGeometryDeleted(geometry);
  23090. }
  23091. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23092. return true;
  23093. }
  23094. return false;
  23095. };
  23096. Scene.prototype.getGeometries = function () {
  23097. return this._geometries;
  23098. };
  23099. /**
  23100. * Get the first added mesh found of a given ID
  23101. * @param {string} id - the id to search for
  23102. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23103. */
  23104. Scene.prototype.getMeshByID = function (id) {
  23105. for (var index = 0; index < this.meshes.length; index++) {
  23106. if (this.meshes[index].id === id) {
  23107. return this.meshes[index];
  23108. }
  23109. }
  23110. return null;
  23111. };
  23112. Scene.prototype.getMeshesByID = function (id) {
  23113. return this.meshes.filter(function (m) {
  23114. return m.id === id;
  23115. });
  23116. };
  23117. /**
  23118. * Get the first added transform node found of a given ID
  23119. * @param {string} id - the id to search for
  23120. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23121. */
  23122. Scene.prototype.getTransformNodeByID = function (id) {
  23123. for (var index = 0; index < this.transformNodes.length; index++) {
  23124. if (this.transformNodes[index].id === id) {
  23125. return this.transformNodes[index];
  23126. }
  23127. }
  23128. return null;
  23129. };
  23130. Scene.prototype.getTransformNodesByID = function (id) {
  23131. return this.transformNodes.filter(function (m) {
  23132. return m.id === id;
  23133. });
  23134. };
  23135. /**
  23136. * Get a mesh with its auto-generated unique id
  23137. * @param {number} uniqueId - the unique id to search for
  23138. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23139. */
  23140. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23141. for (var index = 0; index < this.meshes.length; index++) {
  23142. if (this.meshes[index].uniqueId === uniqueId) {
  23143. return this.meshes[index];
  23144. }
  23145. }
  23146. return null;
  23147. };
  23148. /**
  23149. * Get a the last added mesh found of a given ID
  23150. * @param {string} id - the id to search for
  23151. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23152. */
  23153. Scene.prototype.getLastMeshByID = function (id) {
  23154. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23155. if (this.meshes[index].id === id) {
  23156. return this.meshes[index];
  23157. }
  23158. }
  23159. return null;
  23160. };
  23161. /**
  23162. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23163. * @param {string} id - the id to search for
  23164. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23165. */
  23166. Scene.prototype.getLastEntryByID = function (id) {
  23167. var index;
  23168. for (index = this.meshes.length - 1; index >= 0; index--) {
  23169. if (this.meshes[index].id === id) {
  23170. return this.meshes[index];
  23171. }
  23172. }
  23173. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23174. if (this.transformNodes[index].id === id) {
  23175. return this.transformNodes[index];
  23176. }
  23177. }
  23178. for (index = this.cameras.length - 1; index >= 0; index--) {
  23179. if (this.cameras[index].id === id) {
  23180. return this.cameras[index];
  23181. }
  23182. }
  23183. for (index = this.lights.length - 1; index >= 0; index--) {
  23184. if (this.lights[index].id === id) {
  23185. return this.lights[index];
  23186. }
  23187. }
  23188. return null;
  23189. };
  23190. Scene.prototype.getNodeByID = function (id) {
  23191. var mesh = this.getMeshByID(id);
  23192. if (mesh) {
  23193. return mesh;
  23194. }
  23195. var light = this.getLightByID(id);
  23196. if (light) {
  23197. return light;
  23198. }
  23199. var camera = this.getCameraByID(id);
  23200. if (camera) {
  23201. return camera;
  23202. }
  23203. var bone = this.getBoneByID(id);
  23204. return bone;
  23205. };
  23206. Scene.prototype.getNodeByName = function (name) {
  23207. var mesh = this.getMeshByName(name);
  23208. if (mesh) {
  23209. return mesh;
  23210. }
  23211. var light = this.getLightByName(name);
  23212. if (light) {
  23213. return light;
  23214. }
  23215. var camera = this.getCameraByName(name);
  23216. if (camera) {
  23217. return camera;
  23218. }
  23219. var bone = this.getBoneByName(name);
  23220. return bone;
  23221. };
  23222. Scene.prototype.getMeshByName = function (name) {
  23223. for (var index = 0; index < this.meshes.length; index++) {
  23224. if (this.meshes[index].name === name) {
  23225. return this.meshes[index];
  23226. }
  23227. }
  23228. return null;
  23229. };
  23230. Scene.prototype.getTransformNodeByName = function (name) {
  23231. for (var index = 0; index < this.transformNodes.length; index++) {
  23232. if (this.transformNodes[index].name === name) {
  23233. return this.transformNodes[index];
  23234. }
  23235. }
  23236. return null;
  23237. };
  23238. Scene.prototype.getSoundByName = function (name) {
  23239. var index;
  23240. if (BABYLON.AudioEngine) {
  23241. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23242. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23243. return this.mainSoundTrack.soundCollection[index];
  23244. }
  23245. }
  23246. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23247. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23248. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23249. return this.soundTracks[sdIndex].soundCollection[index];
  23250. }
  23251. }
  23252. }
  23253. }
  23254. return null;
  23255. };
  23256. Scene.prototype.getLastSkeletonByID = function (id) {
  23257. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23258. if (this.skeletons[index].id === id) {
  23259. return this.skeletons[index];
  23260. }
  23261. }
  23262. return null;
  23263. };
  23264. Scene.prototype.getSkeletonById = function (id) {
  23265. for (var index = 0; index < this.skeletons.length; index++) {
  23266. if (this.skeletons[index].id === id) {
  23267. return this.skeletons[index];
  23268. }
  23269. }
  23270. return null;
  23271. };
  23272. Scene.prototype.getSkeletonByName = function (name) {
  23273. for (var index = 0; index < this.skeletons.length; index++) {
  23274. if (this.skeletons[index].name === name) {
  23275. return this.skeletons[index];
  23276. }
  23277. }
  23278. return null;
  23279. };
  23280. Scene.prototype.getMorphTargetManagerById = function (id) {
  23281. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23282. if (this.morphTargetManagers[index].uniqueId === id) {
  23283. return this.morphTargetManagers[index];
  23284. }
  23285. }
  23286. return null;
  23287. };
  23288. Scene.prototype.isActiveMesh = function (mesh) {
  23289. return (this._activeMeshes.indexOf(mesh) !== -1);
  23290. };
  23291. /**
  23292. * Return a the first highlight layer of the scene with a given name.
  23293. * @param name The name of the highlight layer to look for.
  23294. * @return The highlight layer if found otherwise null.
  23295. */
  23296. Scene.prototype.getHighlightLayerByName = function (name) {
  23297. for (var index = 0; index < this.effectLayers.length; index++) {
  23298. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23299. return this.effectLayers[index];
  23300. }
  23301. }
  23302. return null;
  23303. };
  23304. /**
  23305. * Return a the first highlight layer of the scene with a given name.
  23306. * @param name The name of the highlight layer to look for.
  23307. * @return The highlight layer if found otherwise null.
  23308. */
  23309. Scene.prototype.getGlowLayerByName = function (name) {
  23310. for (var index = 0; index < this.effectLayers.length; index++) {
  23311. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23312. return this.effectLayers[index];
  23313. }
  23314. }
  23315. return null;
  23316. };
  23317. Object.defineProperty(Scene.prototype, "uid", {
  23318. /**
  23319. * Return a unique id as a string which can serve as an identifier for the scene
  23320. */
  23321. get: function () {
  23322. if (!this._uid) {
  23323. this._uid = BABYLON.Tools.RandomId();
  23324. }
  23325. return this._uid;
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. /**
  23331. * Add an externaly attached data from its key.
  23332. * This method call will fail and return false, if such key already exists.
  23333. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23334. * @param key the unique key that identifies the data
  23335. * @param data the data object to associate to the key for this Engine instance
  23336. * @return true if no such key were already present and the data was added successfully, false otherwise
  23337. */
  23338. Scene.prototype.addExternalData = function (key, data) {
  23339. if (!this._externalData) {
  23340. this._externalData = new BABYLON.StringDictionary();
  23341. }
  23342. return this._externalData.add(key, data);
  23343. };
  23344. /**
  23345. * Get an externaly attached data from its key
  23346. * @param key the unique key that identifies the data
  23347. * @return the associated data, if present (can be null), or undefined if not present
  23348. */
  23349. Scene.prototype.getExternalData = function (key) {
  23350. if (!this._externalData) {
  23351. return null;
  23352. }
  23353. return this._externalData.get(key);
  23354. };
  23355. /**
  23356. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23357. * @param key the unique key that identifies the data
  23358. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23359. * @return the associated data, can be null if the factory returned null.
  23360. */
  23361. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23362. if (!this._externalData) {
  23363. this._externalData = new BABYLON.StringDictionary();
  23364. }
  23365. return this._externalData.getOrAddWithFactory(key, factory);
  23366. };
  23367. /**
  23368. * Remove an externaly attached data from the Engine instance
  23369. * @param key the unique key that identifies the data
  23370. * @return true if the data was successfully removed, false if it doesn't exist
  23371. */
  23372. Scene.prototype.removeExternalData = function (key) {
  23373. return this._externalData.remove(key);
  23374. };
  23375. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23376. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23377. if (mesh.showSubMeshesBoundingBox) {
  23378. var boundingInfo = subMesh.getBoundingInfo();
  23379. if (boundingInfo !== null && boundingInfo !== undefined) {
  23380. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23381. }
  23382. }
  23383. var material = subMesh.getMaterial();
  23384. if (material !== null && material !== undefined) {
  23385. // Render targets
  23386. if (material.getRenderTargetTextures !== undefined) {
  23387. if (this._processedMaterials.indexOf(material) === -1) {
  23388. this._processedMaterials.push(material);
  23389. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23390. }
  23391. }
  23392. // Dispatch
  23393. this._activeIndices.addCount(subMesh.indexCount, false);
  23394. this._renderingManager.dispatch(subMesh, mesh, material);
  23395. }
  23396. }
  23397. };
  23398. Scene.prototype._isInIntermediateRendering = function () {
  23399. return this._intermediateRendering;
  23400. };
  23401. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23402. this._activeMeshCandidateProvider = provider;
  23403. };
  23404. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23405. return this._activeMeshCandidateProvider;
  23406. };
  23407. /**
  23408. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23409. */
  23410. Scene.prototype.freezeActiveMeshes = function () {
  23411. this._evaluateActiveMeshes();
  23412. this._activeMeshesFrozen = true;
  23413. return this;
  23414. };
  23415. /**
  23416. * Use this function to restart evaluating active meshes on every frame
  23417. */
  23418. Scene.prototype.unfreezeActiveMeshes = function () {
  23419. this._activeMeshesFrozen = false;
  23420. return this;
  23421. };
  23422. Scene.prototype._evaluateActiveMeshes = function () {
  23423. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23424. return;
  23425. }
  23426. if (!this.activeCamera) {
  23427. return;
  23428. }
  23429. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23430. this.activeCamera._activeMeshes.reset();
  23431. this._activeMeshes.reset();
  23432. this._renderingManager.reset();
  23433. this._processedMaterials.reset();
  23434. this._activeParticleSystems.reset();
  23435. this._activeSkeletons.reset();
  23436. this._softwareSkinnedMeshes.reset();
  23437. if (this._boundingBoxRenderer) {
  23438. this._boundingBoxRenderer.reset();
  23439. }
  23440. // Meshes
  23441. var meshes;
  23442. var len;
  23443. var checkIsEnabled = true;
  23444. // Determine mesh candidates
  23445. if (this._activeMeshCandidateProvider !== undefined) {
  23446. // Use _activeMeshCandidateProvider
  23447. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23448. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23449. if (meshes !== undefined) {
  23450. len = meshes.length;
  23451. }
  23452. else {
  23453. len = 0;
  23454. }
  23455. }
  23456. else if (this._selectionOctree !== undefined) {
  23457. // Octree
  23458. var selection = this._selectionOctree.select(this._frustumPlanes);
  23459. meshes = selection.data;
  23460. len = selection.length;
  23461. }
  23462. else {
  23463. // Full scene traversal
  23464. len = this.meshes.length;
  23465. meshes = this.meshes;
  23466. }
  23467. // Check each mesh
  23468. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23469. mesh = meshes[meshIndex];
  23470. if (mesh.isBlocked) {
  23471. continue;
  23472. }
  23473. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23474. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23475. continue;
  23476. }
  23477. mesh.computeWorldMatrix();
  23478. // Intersections
  23479. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23480. this._meshesForIntersections.pushNoDuplicate(mesh);
  23481. }
  23482. // Switch to current LOD
  23483. meshLOD = mesh.getLOD(this.activeCamera);
  23484. if (meshLOD === undefined || meshLOD === null) {
  23485. continue;
  23486. }
  23487. mesh._preActivate();
  23488. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23489. this._activeMeshes.push(mesh);
  23490. this.activeCamera._activeMeshes.push(mesh);
  23491. mesh._activate(this._renderId);
  23492. if (meshLOD !== mesh) {
  23493. meshLOD._activate(this._renderId);
  23494. }
  23495. this._activeMesh(mesh, meshLOD);
  23496. }
  23497. }
  23498. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23499. // Particle systems
  23500. if (this.particlesEnabled) {
  23501. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23502. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23503. var particleSystem = this.particleSystems[particleIndex];
  23504. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23505. continue;
  23506. }
  23507. var emitter = particleSystem.emitter;
  23508. if (!emitter.position || emitter.isEnabled()) {
  23509. this._activeParticleSystems.push(particleSystem);
  23510. particleSystem.animate();
  23511. this._renderingManager.dispatchParticles(particleSystem);
  23512. }
  23513. }
  23514. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23515. }
  23516. };
  23517. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23518. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23519. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23520. mesh.skeleton.prepare();
  23521. }
  23522. if (!mesh.computeBonesUsingShaders) {
  23523. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23524. }
  23525. }
  23526. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23527. var boundingInfo = sourceMesh.getBoundingInfo();
  23528. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23529. }
  23530. if (mesh !== undefined && mesh !== null
  23531. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23532. // Submeshes Octrees
  23533. var len;
  23534. var subMeshes;
  23535. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23536. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23537. len = intersections.length;
  23538. subMeshes = intersections.data;
  23539. }
  23540. else {
  23541. subMeshes = mesh.subMeshes;
  23542. len = subMeshes.length;
  23543. }
  23544. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23545. subMesh = subMeshes[subIndex];
  23546. this._evaluateSubMesh(subMesh, mesh);
  23547. }
  23548. }
  23549. };
  23550. Scene.prototype.updateTransformMatrix = function (force) {
  23551. if (!this.activeCamera) {
  23552. return;
  23553. }
  23554. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23555. };
  23556. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23557. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23558. };
  23559. Scene.prototype._renderForCamera = function (camera) {
  23560. if (camera && camera._skipRendering) {
  23561. return;
  23562. }
  23563. var engine = this._engine;
  23564. this.activeCamera = camera;
  23565. if (!this.activeCamera)
  23566. throw new Error("Active camera not set");
  23567. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23568. // Viewport
  23569. engine.setViewport(this.activeCamera.viewport);
  23570. // Camera
  23571. this.resetCachedMaterial();
  23572. this._renderId++;
  23573. this.activeCamera.update();
  23574. this.updateTransformMatrix();
  23575. if (camera._alternateCamera) {
  23576. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23577. this._alternateRendering = true;
  23578. }
  23579. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23580. // Meshes
  23581. this._evaluateActiveMeshes();
  23582. // Software skinning
  23583. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23584. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23585. mesh.applySkeleton(mesh.skeleton);
  23586. }
  23587. // Render targets
  23588. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23589. var needsRestoreFrameBuffer = false;
  23590. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23591. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23592. }
  23593. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23594. this._intermediateRendering = true;
  23595. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23596. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23597. var renderTarget = this._renderTargets.data[renderIndex];
  23598. if (renderTarget._shouldRender()) {
  23599. this._renderId++;
  23600. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23601. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23602. }
  23603. }
  23604. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23605. this._intermediateRendering = false;
  23606. this._renderId++;
  23607. needsRestoreFrameBuffer = true; // Restore back buffer
  23608. }
  23609. // Render EffecttLayer Texture
  23610. var stencilState = this._engine.getStencilBuffer();
  23611. var renderEffects = false;
  23612. var needStencil = false;
  23613. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23614. this._intermediateRendering = true;
  23615. for (var i = 0; i < this.effectLayers.length; i++) {
  23616. var effectLayer = this.effectLayers[i];
  23617. if (effectLayer.shouldRender() &&
  23618. (!effectLayer.camera ||
  23619. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23620. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23621. renderEffects = true;
  23622. needStencil = needStencil || effectLayer.needStencil();
  23623. var renderTarget = effectLayer._mainTexture;
  23624. if (renderTarget._shouldRender()) {
  23625. this._renderId++;
  23626. renderTarget.render(false, false);
  23627. needsRestoreFrameBuffer = true;
  23628. }
  23629. }
  23630. }
  23631. this._intermediateRendering = false;
  23632. this._renderId++;
  23633. }
  23634. if (needsRestoreFrameBuffer) {
  23635. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23636. }
  23637. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23638. // Prepare Frame
  23639. this.postProcessManager._prepareFrame();
  23640. // Backgrounds
  23641. var layerIndex;
  23642. var layer;
  23643. if (this.layers.length) {
  23644. engine.setDepthBuffer(false);
  23645. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23646. layer = this.layers[layerIndex];
  23647. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23648. layer.render();
  23649. }
  23650. }
  23651. engine.setDepthBuffer(true);
  23652. }
  23653. // Activate effect Layer stencil
  23654. if (needStencil) {
  23655. this._engine.setStencilBuffer(true);
  23656. }
  23657. // Render
  23658. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23659. this._renderingManager.render(null, null, true, true);
  23660. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23661. // Restore effect Layer stencil
  23662. if (needStencil) {
  23663. this._engine.setStencilBuffer(stencilState);
  23664. }
  23665. // Bounding boxes
  23666. if (this._boundingBoxRenderer) {
  23667. this._boundingBoxRenderer.render();
  23668. }
  23669. // Lens flares
  23670. if (this.lensFlaresEnabled) {
  23671. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23672. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23673. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23674. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23675. lensFlareSystem.render();
  23676. }
  23677. }
  23678. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23679. }
  23680. // Foregrounds
  23681. if (this.layers.length) {
  23682. engine.setDepthBuffer(false);
  23683. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23684. layer = this.layers[layerIndex];
  23685. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23686. layer.render();
  23687. }
  23688. }
  23689. engine.setDepthBuffer(true);
  23690. }
  23691. // Effect Layer
  23692. if (renderEffects) {
  23693. engine.setDepthBuffer(false);
  23694. for (var i = 0; i < this.effectLayers.length; i++) {
  23695. if (this.effectLayers[i].shouldRender()) {
  23696. this.effectLayers[i].render();
  23697. }
  23698. }
  23699. engine.setDepthBuffer(true);
  23700. }
  23701. // Finalize frame
  23702. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23703. // Reset some special arrays
  23704. this._renderTargets.reset();
  23705. this._alternateRendering = false;
  23706. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23707. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23708. };
  23709. Scene.prototype._processSubCameras = function (camera) {
  23710. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23711. this._renderForCamera(camera);
  23712. return;
  23713. }
  23714. // Update camera
  23715. if (this.activeCamera) {
  23716. this.activeCamera.update();
  23717. }
  23718. // rig cameras
  23719. for (var index = 0; index < camera._rigCameras.length; index++) {
  23720. this._renderForCamera(camera._rigCameras[index]);
  23721. }
  23722. this.activeCamera = camera;
  23723. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23724. };
  23725. Scene.prototype._checkIntersections = function () {
  23726. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23727. var sourceMesh = this._meshesForIntersections.data[index];
  23728. if (!sourceMesh.actionManager) {
  23729. continue;
  23730. }
  23731. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23732. var action = sourceMesh.actionManager.actions[actionIndex];
  23733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23734. var parameters = action.getTriggerParameter();
  23735. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23736. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23737. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23738. if (areIntersecting && currentIntersectionInProgress === -1) {
  23739. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23740. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23741. sourceMesh._intersectionsInProgress.push(otherMesh);
  23742. }
  23743. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23744. sourceMesh._intersectionsInProgress.push(otherMesh);
  23745. }
  23746. }
  23747. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23748. //They intersected, and now they don't.
  23749. //is this trigger an exit trigger? execute an event.
  23750. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23751. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23752. }
  23753. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23754. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23755. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23756. }
  23757. }
  23758. }
  23759. }
  23760. }
  23761. };
  23762. Scene.prototype.render = function () {
  23763. if (this.isDisposed) {
  23764. return;
  23765. }
  23766. this._activeParticles.fetchNewFrame();
  23767. this._totalVertices.fetchNewFrame();
  23768. this._activeIndices.fetchNewFrame();
  23769. this._activeBones.fetchNewFrame();
  23770. this._meshesForIntersections.reset();
  23771. this.resetCachedMaterial();
  23772. this.onBeforeAnimationsObservable.notifyObservers(this);
  23773. // Actions
  23774. if (this.actionManager) {
  23775. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23776. }
  23777. //Simplification Queue
  23778. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23779. this.simplificationQueue.executeNext();
  23780. }
  23781. if (this._engine.isDeterministicLockStep()) {
  23782. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23783. var defaultFPS = (60.0 / 1000.0);
  23784. var defaultFrameTime = 1000 / 60; // frame time in MS
  23785. if (this._physicsEngine) {
  23786. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23787. }
  23788. var stepsTaken = 0;
  23789. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23790. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23791. internalSteps = Math.min(internalSteps, maxSubSteps);
  23792. do {
  23793. this.onBeforeStepObservable.notifyObservers(this);
  23794. // Animations
  23795. this._animationRatio = defaultFrameTime * defaultFPS;
  23796. this._animate();
  23797. this.onAfterAnimationsObservable.notifyObservers(this);
  23798. // Physics
  23799. if (this._physicsEngine) {
  23800. this.onBeforePhysicsObservable.notifyObservers(this);
  23801. this._physicsEngine._step(defaultFrameTime / 1000);
  23802. this.onAfterPhysicsObservable.notifyObservers(this);
  23803. }
  23804. this.onAfterStepObservable.notifyObservers(this);
  23805. this._currentStepId++;
  23806. stepsTaken++;
  23807. deltaTime -= defaultFrameTime;
  23808. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23809. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23810. }
  23811. else {
  23812. // Animations
  23813. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23814. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23815. this._animate();
  23816. this.onAfterAnimationsObservable.notifyObservers(this);
  23817. // Physics
  23818. if (this._physicsEngine) {
  23819. this.onBeforePhysicsObservable.notifyObservers(this);
  23820. this._physicsEngine._step(deltaTime / 1000.0);
  23821. this.onAfterPhysicsObservable.notifyObservers(this);
  23822. }
  23823. }
  23824. // update gamepad manager
  23825. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23826. this._gamepadManager._checkGamepadsStatus();
  23827. }
  23828. // Before render
  23829. this.onBeforeRenderObservable.notifyObservers(this);
  23830. // Customs render targets
  23831. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23832. var engine = this.getEngine();
  23833. var currentActiveCamera = this.activeCamera;
  23834. if (this.renderTargetsEnabled) {
  23835. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23836. this._intermediateRendering = true;
  23837. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23838. var renderTarget = this.customRenderTargets[customIndex];
  23839. if (renderTarget._shouldRender()) {
  23840. this._renderId++;
  23841. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23842. if (!this.activeCamera)
  23843. throw new Error("Active camera not set");
  23844. // Viewport
  23845. engine.setViewport(this.activeCamera.viewport);
  23846. // Camera
  23847. this.updateTransformMatrix();
  23848. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23849. }
  23850. }
  23851. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23852. this._intermediateRendering = false;
  23853. this._renderId++;
  23854. }
  23855. // Restore back buffer
  23856. if (this.customRenderTargets.length > 0) {
  23857. engine.restoreDefaultFramebuffer();
  23858. }
  23859. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23860. this.activeCamera = currentActiveCamera;
  23861. // Procedural textures
  23862. if (this.proceduralTexturesEnabled) {
  23863. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23864. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23865. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23866. if (proceduralTexture._shouldRender()) {
  23867. proceduralTexture.render();
  23868. }
  23869. }
  23870. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23871. }
  23872. // Clear
  23873. if (this.autoClearDepthAndStencil || this.autoClear) {
  23874. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23875. }
  23876. // Shadows
  23877. if (this.shadowsEnabled) {
  23878. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23879. var light = this.lights[lightIndex];
  23880. var shadowGenerator = light.getShadowGenerator();
  23881. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23882. var shadowMap = (shadowGenerator.getShadowMap());
  23883. if (this.textures.indexOf(shadowMap) !== -1) {
  23884. this._renderTargets.push(shadowMap);
  23885. }
  23886. }
  23887. }
  23888. }
  23889. // Depth renderer
  23890. if (this._depthRenderer) {
  23891. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23892. }
  23893. // Geometry renderer
  23894. if (this._geometryBufferRenderer) {
  23895. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23896. }
  23897. // RenderPipeline
  23898. if (this._postProcessRenderPipelineManager) {
  23899. this._postProcessRenderPipelineManager.update();
  23900. }
  23901. // Multi-cameras?
  23902. if (this.activeCameras.length > 0) {
  23903. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23904. if (cameraIndex > 0) {
  23905. this._engine.clear(null, false, true, true);
  23906. }
  23907. this._processSubCameras(this.activeCameras[cameraIndex]);
  23908. }
  23909. }
  23910. else {
  23911. if (!this.activeCamera) {
  23912. throw new Error("No camera defined");
  23913. }
  23914. this._processSubCameras(this.activeCamera);
  23915. }
  23916. // Intersection checks
  23917. this._checkIntersections();
  23918. // Update the audio listener attached to the camera
  23919. if (BABYLON.AudioEngine) {
  23920. this._updateAudioParameters();
  23921. }
  23922. // After render
  23923. if (this.afterRender) {
  23924. this.afterRender();
  23925. }
  23926. this.onAfterRenderObservable.notifyObservers(this);
  23927. // Cleaning
  23928. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23929. var data = this._toBeDisposed.data[index];
  23930. if (data) {
  23931. data.dispose();
  23932. }
  23933. this._toBeDisposed[index] = null;
  23934. }
  23935. this._toBeDisposed.reset();
  23936. if (this.dumpNextRenderTargets) {
  23937. this.dumpNextRenderTargets = false;
  23938. }
  23939. this._activeBones.addCount(0, true);
  23940. this._activeIndices.addCount(0, true);
  23941. this._activeParticles.addCount(0, true);
  23942. };
  23943. Scene.prototype._updateAudioParameters = function () {
  23944. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23945. return;
  23946. }
  23947. var listeningCamera;
  23948. var audioEngine = BABYLON.Engine.audioEngine;
  23949. if (this.activeCameras.length > 0) {
  23950. listeningCamera = this.activeCameras[0];
  23951. }
  23952. else {
  23953. listeningCamera = this.activeCamera;
  23954. }
  23955. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23956. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23957. // for VR cameras
  23958. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23959. listeningCamera = listeningCamera.rigCameras[0];
  23960. }
  23961. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23962. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23963. cameraDirection.normalize();
  23964. // To avoid some errors on GearVR
  23965. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23966. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23967. }
  23968. var i;
  23969. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23970. var sound = this.mainSoundTrack.soundCollection[i];
  23971. if (sound.useCustomAttenuation) {
  23972. sound.updateDistanceFromListener();
  23973. }
  23974. }
  23975. for (i = 0; i < this.soundTracks.length; i++) {
  23976. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23977. sound = this.soundTracks[i].soundCollection[j];
  23978. if (sound.useCustomAttenuation) {
  23979. sound.updateDistanceFromListener();
  23980. }
  23981. }
  23982. }
  23983. }
  23984. };
  23985. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23986. // Audio
  23987. get: function () {
  23988. return this._audioEnabled;
  23989. },
  23990. set: function (value) {
  23991. this._audioEnabled = value;
  23992. if (BABYLON.AudioEngine) {
  23993. if (this._audioEnabled) {
  23994. this._enableAudio();
  23995. }
  23996. else {
  23997. this._disableAudio();
  23998. }
  23999. }
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. Scene.prototype._disableAudio = function () {
  24005. var i;
  24006. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24007. this.mainSoundTrack.soundCollection[i].pause();
  24008. }
  24009. for (i = 0; i < this.soundTracks.length; i++) {
  24010. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24011. this.soundTracks[i].soundCollection[j].pause();
  24012. }
  24013. }
  24014. };
  24015. Scene.prototype._enableAudio = function () {
  24016. var i;
  24017. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24018. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24019. this.mainSoundTrack.soundCollection[i].play();
  24020. }
  24021. }
  24022. for (i = 0; i < this.soundTracks.length; i++) {
  24023. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24024. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24025. this.soundTracks[i].soundCollection[j].play();
  24026. }
  24027. }
  24028. }
  24029. };
  24030. Object.defineProperty(Scene.prototype, "headphone", {
  24031. get: function () {
  24032. return this._headphone;
  24033. },
  24034. set: function (value) {
  24035. this._headphone = value;
  24036. if (BABYLON.AudioEngine) {
  24037. if (this._headphone) {
  24038. this._switchAudioModeForHeadphones();
  24039. }
  24040. else {
  24041. this._switchAudioModeForNormalSpeakers();
  24042. }
  24043. }
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Scene.prototype._switchAudioModeForHeadphones = function () {
  24049. this.mainSoundTrack.switchPanningModelToHRTF();
  24050. for (var i = 0; i < this.soundTracks.length; i++) {
  24051. this.soundTracks[i].switchPanningModelToHRTF();
  24052. }
  24053. };
  24054. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24055. this.mainSoundTrack.switchPanningModelToEqualPower();
  24056. for (var i = 0; i < this.soundTracks.length; i++) {
  24057. this.soundTracks[i].switchPanningModelToEqualPower();
  24058. }
  24059. };
  24060. Scene.prototype.enableDepthRenderer = function () {
  24061. if (this._depthRenderer) {
  24062. return this._depthRenderer;
  24063. }
  24064. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24065. return this._depthRenderer;
  24066. };
  24067. Scene.prototype.disableDepthRenderer = function () {
  24068. if (!this._depthRenderer) {
  24069. return;
  24070. }
  24071. this._depthRenderer.dispose();
  24072. this._depthRenderer = null;
  24073. };
  24074. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24075. if (ratio === void 0) { ratio = 1; }
  24076. if (this._geometryBufferRenderer) {
  24077. return this._geometryBufferRenderer;
  24078. }
  24079. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24080. if (!this._geometryBufferRenderer.isSupported) {
  24081. this._geometryBufferRenderer = null;
  24082. }
  24083. return this._geometryBufferRenderer;
  24084. };
  24085. Scene.prototype.disableGeometryBufferRenderer = function () {
  24086. if (!this._geometryBufferRenderer) {
  24087. return;
  24088. }
  24089. this._geometryBufferRenderer.dispose();
  24090. this._geometryBufferRenderer = null;
  24091. };
  24092. Scene.prototype.freezeMaterials = function () {
  24093. for (var i = 0; i < this.materials.length; i++) {
  24094. this.materials[i].freeze();
  24095. }
  24096. };
  24097. Scene.prototype.unfreezeMaterials = function () {
  24098. for (var i = 0; i < this.materials.length; i++) {
  24099. this.materials[i].unfreeze();
  24100. }
  24101. };
  24102. Scene.prototype.dispose = function () {
  24103. this.beforeRender = null;
  24104. this.afterRender = null;
  24105. this.skeletons = [];
  24106. this.morphTargetManagers = [];
  24107. this.importedMeshesFiles = new Array();
  24108. this.stopAllAnimations();
  24109. this.resetCachedMaterial();
  24110. if (this._depthRenderer) {
  24111. this._depthRenderer.dispose();
  24112. }
  24113. if (this._gamepadManager) {
  24114. this._gamepadManager.dispose();
  24115. this._gamepadManager = null;
  24116. }
  24117. // Smart arrays
  24118. if (this.activeCamera) {
  24119. this.activeCamera._activeMeshes.dispose();
  24120. this.activeCamera = null;
  24121. }
  24122. this._activeMeshes.dispose();
  24123. this._renderingManager.dispose();
  24124. this._processedMaterials.dispose();
  24125. this._activeParticleSystems.dispose();
  24126. this._activeSkeletons.dispose();
  24127. this._softwareSkinnedMeshes.dispose();
  24128. this._renderTargets.dispose();
  24129. if (this._boundingBoxRenderer) {
  24130. this._boundingBoxRenderer.dispose();
  24131. }
  24132. this._meshesForIntersections.dispose();
  24133. this._toBeDisposed.dispose();
  24134. // Abort active requests
  24135. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24136. var request = _a[_i];
  24137. request.abort();
  24138. }
  24139. // Debug layer
  24140. if (this._debugLayer) {
  24141. this._debugLayer.hide();
  24142. }
  24143. // Events
  24144. this.onDisposeObservable.notifyObservers(this);
  24145. this.onDisposeObservable.clear();
  24146. this.onBeforeRenderObservable.clear();
  24147. this.onAfterRenderObservable.clear();
  24148. this.OnBeforeRenderTargetsRenderObservable.clear();
  24149. this.OnAfterRenderTargetsRenderObservable.clear();
  24150. this.onAfterStepObservable.clear();
  24151. this.onBeforeStepObservable.clear();
  24152. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24153. this.onAfterActiveMeshesEvaluationObservable.clear();
  24154. this.onBeforeParticlesRenderingObservable.clear();
  24155. this.onAfterParticlesRenderingObservable.clear();
  24156. this.onBeforeSpritesRenderingObservable.clear();
  24157. this.onAfterSpritesRenderingObservable.clear();
  24158. this.onBeforeDrawPhaseObservable.clear();
  24159. this.onAfterDrawPhaseObservable.clear();
  24160. this.onBeforePhysicsObservable.clear();
  24161. this.onAfterPhysicsObservable.clear();
  24162. this.onBeforeAnimationsObservable.clear();
  24163. this.onAfterAnimationsObservable.clear();
  24164. this.onDataLoadedObservable.clear();
  24165. this.detachControl();
  24166. // Release sounds & sounds tracks
  24167. if (BABYLON.AudioEngine) {
  24168. this.disposeSounds();
  24169. }
  24170. // VR Helper
  24171. if (this.VRHelper) {
  24172. this.VRHelper.dispose();
  24173. }
  24174. // Detach cameras
  24175. var canvas = this._engine.getRenderingCanvas();
  24176. if (canvas) {
  24177. var index;
  24178. for (index = 0; index < this.cameras.length; index++) {
  24179. this.cameras[index].detachControl(canvas);
  24180. }
  24181. }
  24182. // Release animation groups
  24183. while (this.animationGroups.length) {
  24184. this.animationGroups[0].dispose();
  24185. }
  24186. // Release lights
  24187. while (this.lights.length) {
  24188. this.lights[0].dispose();
  24189. }
  24190. // Release meshes
  24191. while (this.meshes.length) {
  24192. this.meshes[0].dispose(true);
  24193. }
  24194. while (this.transformNodes.length) {
  24195. this.removeTransformNode(this.transformNodes[0]);
  24196. }
  24197. // Release cameras
  24198. while (this.cameras.length) {
  24199. this.cameras[0].dispose();
  24200. }
  24201. // Release materials
  24202. if (this.defaultMaterial) {
  24203. this.defaultMaterial.dispose();
  24204. }
  24205. while (this.multiMaterials.length) {
  24206. this.multiMaterials[0].dispose();
  24207. }
  24208. while (this.materials.length) {
  24209. this.materials[0].dispose();
  24210. }
  24211. // Release particles
  24212. while (this.particleSystems.length) {
  24213. this.particleSystems[0].dispose();
  24214. }
  24215. // Release sprites
  24216. while (this.spriteManagers.length) {
  24217. this.spriteManagers[0].dispose();
  24218. }
  24219. // Release postProcesses
  24220. while (this.postProcesses.length) {
  24221. this.postProcesses[0].dispose();
  24222. }
  24223. // Release layers
  24224. while (this.layers.length) {
  24225. this.layers[0].dispose();
  24226. }
  24227. while (this.effectLayers.length) {
  24228. this.effectLayers[0].dispose();
  24229. }
  24230. // Release textures
  24231. while (this.textures.length) {
  24232. this.textures[0].dispose();
  24233. }
  24234. // Release UBO
  24235. this._sceneUbo.dispose();
  24236. if (this._alternateSceneUbo) {
  24237. this._alternateSceneUbo.dispose();
  24238. }
  24239. // Post-processes
  24240. this.postProcessManager.dispose();
  24241. if (this._postProcessRenderPipelineManager) {
  24242. this._postProcessRenderPipelineManager.dispose();
  24243. }
  24244. // Physics
  24245. if (this._physicsEngine) {
  24246. this.disablePhysicsEngine();
  24247. }
  24248. // Remove from engine
  24249. index = this._engine.scenes.indexOf(this);
  24250. if (index > -1) {
  24251. this._engine.scenes.splice(index, 1);
  24252. }
  24253. this._engine.wipeCaches(true);
  24254. this._isDisposed = true;
  24255. };
  24256. Object.defineProperty(Scene.prototype, "isDisposed", {
  24257. get: function () {
  24258. return this._isDisposed;
  24259. },
  24260. enumerable: true,
  24261. configurable: true
  24262. });
  24263. // Release sounds & sounds tracks
  24264. Scene.prototype.disposeSounds = function () {
  24265. if (!this._mainSoundTrack) {
  24266. return;
  24267. }
  24268. this.mainSoundTrack.dispose();
  24269. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24270. this.soundTracks[scIndex].dispose();
  24271. }
  24272. };
  24273. // Octrees
  24274. Scene.prototype.getWorldExtends = function () {
  24275. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24276. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24277. for (var index = 0; index < this.meshes.length; index++) {
  24278. var mesh = this.meshes[index];
  24279. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24280. continue;
  24281. }
  24282. mesh.computeWorldMatrix(true);
  24283. var boundingInfo = mesh.getBoundingInfo();
  24284. var minBox = boundingInfo.boundingBox.minimumWorld;
  24285. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24286. BABYLON.Tools.CheckExtends(minBox, min, max);
  24287. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24288. }
  24289. return {
  24290. min: min,
  24291. max: max
  24292. };
  24293. };
  24294. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24295. if (maxCapacity === void 0) { maxCapacity = 64; }
  24296. if (maxDepth === void 0) { maxDepth = 2; }
  24297. if (!this._selectionOctree) {
  24298. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24299. }
  24300. var worldExtends = this.getWorldExtends();
  24301. // Update octree
  24302. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24303. return this._selectionOctree;
  24304. };
  24305. // Picking
  24306. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24307. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24308. var result = BABYLON.Ray.Zero();
  24309. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24310. return result;
  24311. };
  24312. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24313. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24314. var engine = this._engine;
  24315. if (!camera) {
  24316. if (!this.activeCamera)
  24317. throw new Error("Active camera not set");
  24318. camera = this.activeCamera;
  24319. }
  24320. var cameraViewport = camera.viewport;
  24321. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24322. // Moving coordinates to local viewport world
  24323. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24324. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24325. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24326. return this;
  24327. };
  24328. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24329. var result = BABYLON.Ray.Zero();
  24330. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24331. return result;
  24332. };
  24333. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24334. if (!BABYLON.PickingInfo) {
  24335. return this;
  24336. }
  24337. var engine = this._engine;
  24338. if (!camera) {
  24339. if (!this.activeCamera)
  24340. throw new Error("Active camera not set");
  24341. camera = this.activeCamera;
  24342. }
  24343. var cameraViewport = camera.viewport;
  24344. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24345. var identity = BABYLON.Matrix.Identity();
  24346. // Moving coordinates to local viewport world
  24347. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24348. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24349. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24350. return this;
  24351. };
  24352. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24353. if (!BABYLON.PickingInfo) {
  24354. return null;
  24355. }
  24356. var pickingInfo = null;
  24357. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24358. var mesh = this.meshes[meshIndex];
  24359. if (predicate) {
  24360. if (!predicate(mesh)) {
  24361. continue;
  24362. }
  24363. }
  24364. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24365. continue;
  24366. }
  24367. var world = mesh.getWorldMatrix();
  24368. var ray = rayFunction(world);
  24369. var result = mesh.intersects(ray, fastCheck);
  24370. if (!result || !result.hit)
  24371. continue;
  24372. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24373. continue;
  24374. pickingInfo = result;
  24375. if (fastCheck) {
  24376. break;
  24377. }
  24378. }
  24379. return pickingInfo || new BABYLON.PickingInfo();
  24380. };
  24381. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24382. if (!BABYLON.PickingInfo) {
  24383. return null;
  24384. }
  24385. var pickingInfos = new Array();
  24386. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24387. var mesh = this.meshes[meshIndex];
  24388. if (predicate) {
  24389. if (!predicate(mesh)) {
  24390. continue;
  24391. }
  24392. }
  24393. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24394. continue;
  24395. }
  24396. var world = mesh.getWorldMatrix();
  24397. var ray = rayFunction(world);
  24398. var result = mesh.intersects(ray, false);
  24399. if (!result || !result.hit)
  24400. continue;
  24401. pickingInfos.push(result);
  24402. }
  24403. return pickingInfos;
  24404. };
  24405. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24406. if (!BABYLON.PickingInfo) {
  24407. return null;
  24408. }
  24409. var pickingInfo = null;
  24410. if (!camera) {
  24411. if (!this.activeCamera) {
  24412. return null;
  24413. }
  24414. camera = this.activeCamera;
  24415. }
  24416. if (this.spriteManagers.length > 0) {
  24417. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24418. var spriteManager = this.spriteManagers[spriteIndex];
  24419. if (!spriteManager.isPickable) {
  24420. continue;
  24421. }
  24422. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24423. if (!result || !result.hit)
  24424. continue;
  24425. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24426. continue;
  24427. pickingInfo = result;
  24428. if (fastCheck) {
  24429. break;
  24430. }
  24431. }
  24432. }
  24433. return pickingInfo || new BABYLON.PickingInfo();
  24434. };
  24435. /** Launch a ray to try to pick a mesh in the scene
  24436. * @param x position on screen
  24437. * @param y position on screen
  24438. * @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
  24439. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24440. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24441. */
  24442. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24443. var _this = this;
  24444. if (!BABYLON.PickingInfo) {
  24445. return null;
  24446. }
  24447. return this._internalPick(function (world) {
  24448. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24449. return _this._tempPickingRay;
  24450. }, predicate, fastCheck);
  24451. };
  24452. /** Launch a ray to try to pick a sprite in the scene
  24453. * @param x position on screen
  24454. * @param y position on screen
  24455. * @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
  24456. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24457. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24458. */
  24459. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24460. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24461. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24462. };
  24463. /** Use the given ray to pick a mesh in the scene
  24464. * @param ray The ray to use to pick meshes
  24465. * @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
  24466. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24467. */
  24468. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24469. var _this = this;
  24470. return this._internalPick(function (world) {
  24471. if (!_this._pickWithRayInverseMatrix) {
  24472. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24473. }
  24474. world.invertToRef(_this._pickWithRayInverseMatrix);
  24475. if (!_this._cachedRayForTransform) {
  24476. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24477. }
  24478. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24479. return _this._cachedRayForTransform;
  24480. }, predicate, fastCheck);
  24481. };
  24482. /**
  24483. * Launch a ray to try to pick a mesh in the scene
  24484. * @param x X position on screen
  24485. * @param y Y position on screen
  24486. * @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
  24487. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24488. */
  24489. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24490. var _this = this;
  24491. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24492. };
  24493. /**
  24494. * Launch a ray to try to pick a mesh in the scene
  24495. * @param ray Ray to use
  24496. * @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
  24497. */
  24498. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24499. var _this = this;
  24500. return this._internalMultiPick(function (world) {
  24501. if (!_this._pickWithRayInverseMatrix) {
  24502. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24503. }
  24504. world.invertToRef(_this._pickWithRayInverseMatrix);
  24505. if (!_this._cachedRayForTransform) {
  24506. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24507. }
  24508. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24509. return _this._cachedRayForTransform;
  24510. }, predicate);
  24511. };
  24512. Scene.prototype.setPointerOverMesh = function (mesh) {
  24513. if (this._pointerOverMesh === mesh) {
  24514. return;
  24515. }
  24516. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24517. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24518. }
  24519. this._pointerOverMesh = mesh;
  24520. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24521. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24522. }
  24523. };
  24524. Scene.prototype.getPointerOverMesh = function () {
  24525. return this._pointerOverMesh;
  24526. };
  24527. Scene.prototype.setPointerOverSprite = function (sprite) {
  24528. if (this._pointerOverSprite === sprite) {
  24529. return;
  24530. }
  24531. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24532. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24533. }
  24534. this._pointerOverSprite = sprite;
  24535. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24536. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24537. }
  24538. };
  24539. Scene.prototype.getPointerOverSprite = function () {
  24540. return this._pointerOverSprite;
  24541. };
  24542. // Physics
  24543. Scene.prototype.getPhysicsEngine = function () {
  24544. return this._physicsEngine;
  24545. };
  24546. /**
  24547. * Enables physics to the current scene
  24548. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24549. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24550. * @return {boolean} was the physics engine initialized
  24551. */
  24552. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24553. if (gravity === void 0) { gravity = null; }
  24554. if (this._physicsEngine) {
  24555. return true;
  24556. }
  24557. try {
  24558. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24559. return true;
  24560. }
  24561. catch (e) {
  24562. BABYLON.Tools.Error(e.message);
  24563. return false;
  24564. }
  24565. };
  24566. Scene.prototype.disablePhysicsEngine = function () {
  24567. if (!this._physicsEngine) {
  24568. return;
  24569. }
  24570. this._physicsEngine.dispose();
  24571. this._physicsEngine = null;
  24572. };
  24573. Scene.prototype.isPhysicsEnabled = function () {
  24574. return this._physicsEngine !== undefined;
  24575. };
  24576. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24577. var mesh = compound.parts[0].mesh;
  24578. if (mesh.physicsImpostor) {
  24579. mesh.physicsImpostor.dispose();
  24580. mesh.physicsImpostor = null;
  24581. }
  24582. };
  24583. // Misc.
  24584. Scene.prototype._rebuildGeometries = function () {
  24585. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24586. var geometry = _a[_i];
  24587. geometry._rebuild();
  24588. }
  24589. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24590. var mesh = _c[_b];
  24591. mesh._rebuild();
  24592. }
  24593. if (this.postProcessManager) {
  24594. this.postProcessManager._rebuild();
  24595. }
  24596. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24597. var layer = _e[_d];
  24598. layer._rebuild();
  24599. }
  24600. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24601. var effectLayer = _g[_f];
  24602. effectLayer._rebuild();
  24603. }
  24604. if (this._boundingBoxRenderer) {
  24605. this._boundingBoxRenderer._rebuild();
  24606. }
  24607. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24608. var system = _j[_h];
  24609. system.rebuild();
  24610. }
  24611. if (this._postProcessRenderPipelineManager) {
  24612. this._postProcessRenderPipelineManager._rebuild();
  24613. }
  24614. };
  24615. Scene.prototype._rebuildTextures = function () {
  24616. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24617. var texture = _a[_i];
  24618. texture._rebuild();
  24619. }
  24620. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24621. };
  24622. /**
  24623. * Creates a default light for the scene.
  24624. * @param replace Whether to replace the existing lights in the scene.
  24625. */
  24626. Scene.prototype.createDefaultLight = function (replace) {
  24627. if (replace === void 0) { replace = false; }
  24628. // Dispose existing light in replace mode.
  24629. if (replace) {
  24630. if (this.lights) {
  24631. for (var i = 0; i < this.lights.length; i++) {
  24632. this.lights[i].dispose();
  24633. }
  24634. }
  24635. }
  24636. // Light
  24637. if (this.lights.length === 0) {
  24638. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24639. }
  24640. };
  24641. /**
  24642. * Creates a default camera for the scene.
  24643. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24644. * @param replace Whether to replace the existing active camera in the scene.
  24645. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24646. */
  24647. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24648. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24649. if (replace === void 0) { replace = false; }
  24650. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24651. // Dispose existing camera in replace mode.
  24652. if (replace) {
  24653. if (this.activeCamera) {
  24654. this.activeCamera.dispose();
  24655. this.activeCamera = null;
  24656. }
  24657. }
  24658. // Camera
  24659. if (!this.activeCamera) {
  24660. var worldExtends = this.getWorldExtends();
  24661. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24662. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24663. var camera;
  24664. var radius = worldSize.length() * 1.5;
  24665. // empty scene scenario!
  24666. if (!isFinite(radius)) {
  24667. radius = 1;
  24668. worldCenter.copyFromFloats(0, 0, 0);
  24669. }
  24670. if (createArcRotateCamera) {
  24671. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24672. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24673. arcRotateCamera.wheelPrecision = 100 / radius;
  24674. camera = arcRotateCamera;
  24675. }
  24676. else {
  24677. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24678. freeCamera.setTarget(worldCenter);
  24679. camera = freeCamera;
  24680. }
  24681. camera.minZ = radius * 0.01;
  24682. camera.maxZ = radius * 1000;
  24683. camera.speed = radius * 0.2;
  24684. this.activeCamera = camera;
  24685. var canvas = this.getEngine().getRenderingCanvas();
  24686. if (attachCameraControls && canvas) {
  24687. camera.attachControl(canvas);
  24688. }
  24689. }
  24690. };
  24691. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24692. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24693. if (replace === void 0) { replace = false; }
  24694. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24695. this.createDefaultLight(replace);
  24696. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24697. };
  24698. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24699. if (pbr === void 0) { pbr = false; }
  24700. if (scale === void 0) { scale = 1000; }
  24701. if (blur === void 0) { blur = 0; }
  24702. if (environmentTexture) {
  24703. this.environmentTexture = environmentTexture;
  24704. }
  24705. if (!this.environmentTexture) {
  24706. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24707. return null;
  24708. }
  24709. // Skybox
  24710. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24711. if (pbr) {
  24712. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24713. hdrSkyboxMaterial.backFaceCulling = false;
  24714. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24715. if (hdrSkyboxMaterial.reflectionTexture) {
  24716. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24717. }
  24718. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24719. hdrSkyboxMaterial.disableLighting = true;
  24720. hdrSkyboxMaterial.twoSidedLighting = true;
  24721. hdrSkybox.infiniteDistance = true;
  24722. hdrSkybox.material = hdrSkyboxMaterial;
  24723. }
  24724. else {
  24725. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24726. skyboxMaterial.backFaceCulling = false;
  24727. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24728. if (skyboxMaterial.reflectionTexture) {
  24729. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24730. }
  24731. skyboxMaterial.disableLighting = true;
  24732. hdrSkybox.infiniteDistance = true;
  24733. hdrSkybox.material = skyboxMaterial;
  24734. }
  24735. return hdrSkybox;
  24736. };
  24737. Scene.prototype.createDefaultEnvironment = function (options) {
  24738. if (BABYLON.EnvironmentHelper) {
  24739. return new BABYLON.EnvironmentHelper(options, this);
  24740. }
  24741. return null;
  24742. };
  24743. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24744. if (webVROptions === void 0) { webVROptions = {}; }
  24745. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24746. };
  24747. // Tags
  24748. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24749. if (tagsQuery === undefined) {
  24750. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24751. return list;
  24752. }
  24753. var listByTags = [];
  24754. forEach = forEach || (function (item) { return; });
  24755. for (var i in list) {
  24756. var item = list[i];
  24757. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24758. listByTags.push(item);
  24759. forEach(item);
  24760. }
  24761. }
  24762. return listByTags;
  24763. };
  24764. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24765. return this._getByTags(this.meshes, tagsQuery, forEach);
  24766. };
  24767. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24768. return this._getByTags(this.cameras, tagsQuery, forEach);
  24769. };
  24770. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24771. return this._getByTags(this.lights, tagsQuery, forEach);
  24772. };
  24773. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24774. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24775. };
  24776. /**
  24777. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24778. * This allowed control for front to back rendering or reversly depending of the special needs.
  24779. *
  24780. * @param renderingGroupId The rendering group id corresponding to its index
  24781. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24782. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24783. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24784. */
  24785. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24786. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24787. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24788. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24789. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24790. };
  24791. /**
  24792. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24793. *
  24794. * @param renderingGroupId The rendering group id corresponding to its index
  24795. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24796. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24797. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24798. */
  24799. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24800. if (depth === void 0) { depth = true; }
  24801. if (stencil === void 0) { stencil = true; }
  24802. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24803. };
  24804. /**
  24805. * Will flag all materials as dirty to trigger new shader compilation
  24806. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24807. */
  24808. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24809. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24810. var material = _a[_i];
  24811. if (predicate && !predicate(material)) {
  24812. continue;
  24813. }
  24814. material.markAsDirty(flag);
  24815. }
  24816. };
  24817. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24818. var _this = this;
  24819. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24820. this._activeRequests.push(request);
  24821. request.onCompleteObservable.add(function (request) {
  24822. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24823. });
  24824. return request;
  24825. };
  24826. /** @ignore */
  24827. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24828. var _this = this;
  24829. return new Promise(function (resolve, reject) {
  24830. _this._loadFile(url, function (data) {
  24831. resolve(data);
  24832. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24833. reject(exception);
  24834. });
  24835. });
  24836. };
  24837. // Statics
  24838. Scene._FOGMODE_NONE = 0;
  24839. Scene._FOGMODE_EXP = 1;
  24840. Scene._FOGMODE_EXP2 = 2;
  24841. Scene._FOGMODE_LINEAR = 3;
  24842. Scene._uniqueIdCounter = 0;
  24843. Scene.MinDeltaTime = 1.0;
  24844. Scene.MaxDeltaTime = 1000.0;
  24845. /** The distance in pixel that you have to move to prevent some events */
  24846. Scene.DragMovementThreshold = 10; // in pixels
  24847. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24848. Scene.LongPressDelay = 500; // in milliseconds
  24849. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24850. Scene.DoubleClickDelay = 300; // in milliseconds
  24851. /** If you need to check double click without raising a single click at first click, enable this flag */
  24852. Scene.ExclusiveDoubleClickMode = false;
  24853. return Scene;
  24854. }());
  24855. BABYLON.Scene = Scene;
  24856. })(BABYLON || (BABYLON = {}));
  24857. //# sourceMappingURL=babylon.scene.js.map
  24858. var BABYLON;
  24859. (function (BABYLON) {
  24860. /**
  24861. * Set of assets to keep when moving a scene into an asset container.
  24862. */
  24863. var KeepAssets = /** @class */ (function () {
  24864. function KeepAssets() {
  24865. /**
  24866. * Cameras to keep.
  24867. */
  24868. this.cameras = new Array();
  24869. /**
  24870. * Lights to keep.
  24871. */
  24872. this.lights = new Array();
  24873. /**
  24874. * Meshes to keep.
  24875. */
  24876. this.meshes = new Array();
  24877. /**
  24878. * Skeletons to keep.
  24879. */
  24880. this.skeletons = new Array();
  24881. /**
  24882. * ParticleSystems to keep.
  24883. */
  24884. this.particleSystems = new Array();
  24885. /**
  24886. * Animations to keep.
  24887. */
  24888. this.animations = new Array();
  24889. /**
  24890. * MultiMaterials to keep.
  24891. */
  24892. this.multiMaterials = new Array();
  24893. /**
  24894. * Materials to keep.
  24895. */
  24896. this.materials = new Array();
  24897. /**
  24898. * MorphTargetManagers to keep.
  24899. */
  24900. this.morphTargetManagers = new Array();
  24901. /**
  24902. * Geometries to keep.
  24903. */
  24904. this.geometries = new Array();
  24905. /**
  24906. * TransformNodes to keep.
  24907. */
  24908. this.transformNodes = new Array();
  24909. /**
  24910. * LensFlareSystems to keep.
  24911. */
  24912. this.lensFlareSystems = new Array();
  24913. /**
  24914. * ShadowGenerators to keep.
  24915. */
  24916. this.shadowGenerators = new Array();
  24917. /**
  24918. * ActionManagers to keep.
  24919. */
  24920. this.actionManagers = new Array();
  24921. /**
  24922. * Sounds to keep.
  24923. */
  24924. this.sounds = new Array();
  24925. }
  24926. return KeepAssets;
  24927. }());
  24928. BABYLON.KeepAssets = KeepAssets;
  24929. /**
  24930. * Container with a set of assets that can be added or removed from a scene.
  24931. */
  24932. var AssetContainer = /** @class */ (function () {
  24933. /**
  24934. * Instantiates an AssetContainer.
  24935. * @param scene The scene the AssetContainer belongs to.
  24936. */
  24937. function AssetContainer(scene) {
  24938. // Objects
  24939. /**
  24940. * Cameras populated in the container.
  24941. */
  24942. this.cameras = new Array();
  24943. /**
  24944. * Lights populated in the container.
  24945. */
  24946. this.lights = new Array();
  24947. /**
  24948. * Meshes populated in the container.
  24949. */
  24950. this.meshes = new Array();
  24951. /**
  24952. * Skeletons populated in the container.
  24953. */
  24954. this.skeletons = new Array();
  24955. /**
  24956. * ParticleSystems populated in the container.
  24957. */
  24958. this.particleSystems = new Array();
  24959. /**
  24960. * Animations populated in the container.
  24961. */
  24962. this.animations = new Array();
  24963. /**
  24964. * MultiMaterials populated in the container.
  24965. */
  24966. this.multiMaterials = new Array();
  24967. /**
  24968. * Materials populated in the container.
  24969. */
  24970. this.materials = new Array();
  24971. /**
  24972. * MorphTargetManagers populated in the container.
  24973. */
  24974. this.morphTargetManagers = new Array();
  24975. /**
  24976. * Geometries populated in the container.
  24977. */
  24978. this.geometries = new Array();
  24979. /**
  24980. * TransformNodes populated in the container.
  24981. */
  24982. this.transformNodes = new Array();
  24983. /**
  24984. * LensFlareSystems populated in the container.
  24985. */
  24986. this.lensFlareSystems = new Array();
  24987. /**
  24988. * ShadowGenerators populated in the container.
  24989. */
  24990. this.shadowGenerators = new Array();
  24991. /**
  24992. * ActionManagers populated in the container.
  24993. */
  24994. this.actionManagers = new Array();
  24995. /**
  24996. * Sounds populated in the container.
  24997. */
  24998. this.sounds = new Array();
  24999. this.scene = scene;
  25000. }
  25001. /**
  25002. * Adds all the assets from the container to the scene.
  25003. */
  25004. AssetContainer.prototype.addAllToScene = function () {
  25005. var _this = this;
  25006. this.cameras.forEach(function (o) {
  25007. _this.scene.addCamera(o);
  25008. });
  25009. this.lights.forEach(function (o) {
  25010. _this.scene.addLight(o);
  25011. });
  25012. this.meshes.forEach(function (o) {
  25013. _this.scene.addMesh(o);
  25014. });
  25015. this.skeletons.forEach(function (o) {
  25016. _this.scene.addSkeleton(o);
  25017. });
  25018. this.particleSystems.forEach(function (o) {
  25019. _this.scene.addParticleSystem(o);
  25020. });
  25021. this.animations.forEach(function (o) {
  25022. _this.scene.addAnimation(o);
  25023. });
  25024. this.multiMaterials.forEach(function (o) {
  25025. _this.scene.addMultiMaterial(o);
  25026. });
  25027. this.materials.forEach(function (o) {
  25028. _this.scene.addMaterial(o);
  25029. });
  25030. this.morphTargetManagers.forEach(function (o) {
  25031. _this.scene.addMorphTargetManager(o);
  25032. });
  25033. this.geometries.forEach(function (o) {
  25034. _this.scene.addGeometry(o);
  25035. });
  25036. this.transformNodes.forEach(function (o) {
  25037. _this.scene.addTransformNode(o);
  25038. });
  25039. this.lensFlareSystems.forEach(function (o) {
  25040. _this.scene.addLensFlareSystem(o);
  25041. });
  25042. this.actionManagers.forEach(function (o) {
  25043. _this.scene.addActionManager(o);
  25044. });
  25045. this.sounds.forEach(function (o) {
  25046. o.play();
  25047. o.autoplay = true;
  25048. _this.scene.mainSoundTrack.AddSound(o);
  25049. });
  25050. };
  25051. /**
  25052. * Removes all the assets in the container from the scene
  25053. */
  25054. AssetContainer.prototype.removeAllFromScene = function () {
  25055. var _this = this;
  25056. this.cameras.forEach(function (o) {
  25057. _this.scene.removeCamera(o);
  25058. });
  25059. this.lights.forEach(function (o) {
  25060. _this.scene.removeLight(o);
  25061. });
  25062. this.meshes.forEach(function (o) {
  25063. _this.scene.removeMesh(o);
  25064. });
  25065. this.skeletons.forEach(function (o) {
  25066. _this.scene.removeSkeleton(o);
  25067. });
  25068. this.particleSystems.forEach(function (o) {
  25069. _this.scene.removeParticleSystem(o);
  25070. });
  25071. this.animations.forEach(function (o) {
  25072. _this.scene.removeAnimation(o);
  25073. });
  25074. this.multiMaterials.forEach(function (o) {
  25075. _this.scene.removeMultiMaterial(o);
  25076. });
  25077. this.materials.forEach(function (o) {
  25078. _this.scene.removeMaterial(o);
  25079. });
  25080. this.morphTargetManagers.forEach(function (o) {
  25081. _this.scene.removeMorphTargetManager(o);
  25082. });
  25083. this.geometries.forEach(function (o) {
  25084. _this.scene.removeGeometry(o);
  25085. });
  25086. this.transformNodes.forEach(function (o) {
  25087. _this.scene.removeTransformNode(o);
  25088. });
  25089. this.lensFlareSystems.forEach(function (o) {
  25090. _this.scene.removeLensFlareSystem(o);
  25091. });
  25092. this.actionManagers.forEach(function (o) {
  25093. _this.scene.removeActionManager(o);
  25094. });
  25095. this.sounds.forEach(function (o) {
  25096. o.stop();
  25097. o.autoplay = false;
  25098. _this.scene.mainSoundTrack.RemoveSound(o);
  25099. });
  25100. };
  25101. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25102. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25103. var asset = sourceAssets_1[_i];
  25104. var move = true;
  25105. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25106. var keepAsset = keepAssets_1[_a];
  25107. if (asset === keepAsset) {
  25108. move = false;
  25109. break;
  25110. }
  25111. }
  25112. if (move) {
  25113. targetAssets.push(asset);
  25114. }
  25115. }
  25116. };
  25117. /**
  25118. * Removes all the assets contained in the scene and adds them to the container.
  25119. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25120. */
  25121. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25122. if (keepAssets === undefined) {
  25123. keepAssets = new KeepAssets();
  25124. }
  25125. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25126. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25127. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25128. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25129. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25130. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25131. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25132. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25133. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25134. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25135. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25136. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25137. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25138. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25139. this.removeAllFromScene();
  25140. };
  25141. return AssetContainer;
  25142. }());
  25143. BABYLON.AssetContainer = AssetContainer;
  25144. })(BABYLON || (BABYLON = {}));
  25145. //# sourceMappingURL=babylon.assetContainer.js.map
  25146. var BABYLON;
  25147. (function (BABYLON) {
  25148. var Buffer = /** @class */ (function () {
  25149. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25150. if (instanced === void 0) { instanced = false; }
  25151. if (engine instanceof BABYLON.Mesh) {
  25152. this._engine = engine.getScene().getEngine();
  25153. }
  25154. else {
  25155. this._engine = engine;
  25156. }
  25157. this._updatable = updatable;
  25158. this._data = data;
  25159. this._strideSize = stride;
  25160. if (!postponeInternalCreation) {
  25161. this.create();
  25162. }
  25163. this._instanced = instanced;
  25164. this._instanceDivisor = instanced ? 1 : 0;
  25165. }
  25166. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25167. // a lot of these parameters are ignored as they are overriden by the buffer
  25168. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25169. };
  25170. // Properties
  25171. Buffer.prototype.isUpdatable = function () {
  25172. return this._updatable;
  25173. };
  25174. Buffer.prototype.getData = function () {
  25175. return this._data;
  25176. };
  25177. Buffer.prototype.getBuffer = function () {
  25178. return this._buffer;
  25179. };
  25180. Buffer.prototype.getStrideSize = function () {
  25181. return this._strideSize;
  25182. };
  25183. Buffer.prototype.getIsInstanced = function () {
  25184. return this._instanced;
  25185. };
  25186. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25187. get: function () {
  25188. return this._instanceDivisor;
  25189. },
  25190. set: function (value) {
  25191. this._instanceDivisor = value;
  25192. if (value == 0) {
  25193. this._instanced = false;
  25194. }
  25195. else {
  25196. this._instanced = true;
  25197. }
  25198. },
  25199. enumerable: true,
  25200. configurable: true
  25201. });
  25202. // Methods
  25203. Buffer.prototype.create = function (data) {
  25204. if (data === void 0) { data = null; }
  25205. if (!data && this._buffer) {
  25206. return; // nothing to do
  25207. }
  25208. data = data || this._data;
  25209. if (!data) {
  25210. return;
  25211. }
  25212. if (!this._buffer) {
  25213. if (this._updatable) {
  25214. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25215. this._data = data;
  25216. }
  25217. else {
  25218. this._buffer = this._engine.createVertexBuffer(data);
  25219. }
  25220. }
  25221. else if (this._updatable) {
  25222. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25223. this._data = data;
  25224. }
  25225. };
  25226. Buffer.prototype._rebuild = function () {
  25227. this._buffer = null;
  25228. this.create(this._data);
  25229. };
  25230. Buffer.prototype.update = function (data) {
  25231. this.create(data);
  25232. };
  25233. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25234. if (!this._buffer) {
  25235. return;
  25236. }
  25237. if (this._updatable) {
  25238. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25239. this._data = null;
  25240. }
  25241. };
  25242. Buffer.prototype.dispose = function () {
  25243. if (!this._buffer) {
  25244. return;
  25245. }
  25246. if (this._engine._releaseBuffer(this._buffer)) {
  25247. this._buffer = null;
  25248. }
  25249. };
  25250. return Buffer;
  25251. }());
  25252. BABYLON.Buffer = Buffer;
  25253. })(BABYLON || (BABYLON = {}));
  25254. //# sourceMappingURL=babylon.buffer.js.map
  25255. var BABYLON;
  25256. (function (BABYLON) {
  25257. var VertexBuffer = /** @class */ (function () {
  25258. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25259. if (!stride) {
  25260. stride = VertexBuffer.DeduceStride(kind);
  25261. }
  25262. if (data instanceof BABYLON.Buffer) {
  25263. if (!stride) {
  25264. stride = data.getStrideSize();
  25265. }
  25266. this._buffer = data;
  25267. this._ownsBuffer = false;
  25268. }
  25269. else {
  25270. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25271. this._ownsBuffer = true;
  25272. }
  25273. this._stride = stride;
  25274. this._offset = offset ? offset : 0;
  25275. this._size = size ? size : stride;
  25276. this._kind = kind;
  25277. }
  25278. VertexBuffer.prototype._rebuild = function () {
  25279. if (!this._buffer) {
  25280. return;
  25281. }
  25282. this._buffer._rebuild();
  25283. };
  25284. /**
  25285. * Returns the kind of the VertexBuffer (string).
  25286. */
  25287. VertexBuffer.prototype.getKind = function () {
  25288. return this._kind;
  25289. };
  25290. // Properties
  25291. /**
  25292. * Boolean : is the VertexBuffer updatable ?
  25293. */
  25294. VertexBuffer.prototype.isUpdatable = function () {
  25295. return this._buffer.isUpdatable();
  25296. };
  25297. /**
  25298. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25299. */
  25300. VertexBuffer.prototype.getData = function () {
  25301. return this._buffer.getData();
  25302. };
  25303. /**
  25304. * Returns the WebGLBuffer associated to the VertexBuffer.
  25305. */
  25306. VertexBuffer.prototype.getBuffer = function () {
  25307. return this._buffer.getBuffer();
  25308. };
  25309. /**
  25310. * Returns the stride of the VertexBuffer (integer).
  25311. */
  25312. VertexBuffer.prototype.getStrideSize = function () {
  25313. return this._stride;
  25314. };
  25315. /**
  25316. * Returns the offset (integer).
  25317. */
  25318. VertexBuffer.prototype.getOffset = function () {
  25319. return this._offset;
  25320. };
  25321. /**
  25322. * Returns the VertexBuffer total size (integer).
  25323. */
  25324. VertexBuffer.prototype.getSize = function () {
  25325. return this._size;
  25326. };
  25327. /**
  25328. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25329. */
  25330. VertexBuffer.prototype.getIsInstanced = function () {
  25331. return this._buffer.getIsInstanced();
  25332. };
  25333. /**
  25334. * Returns the instancing divisor, zero for non-instanced (integer).
  25335. */
  25336. VertexBuffer.prototype.getInstanceDivisor = function () {
  25337. return this._buffer.instanceDivisor;
  25338. };
  25339. // Methods
  25340. /**
  25341. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25342. * Returns the created WebGLBuffer.
  25343. */
  25344. VertexBuffer.prototype.create = function (data) {
  25345. return this._buffer.create(data);
  25346. };
  25347. /**
  25348. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25349. * This function will create a new buffer if the current one is not updatable
  25350. * Returns the updated WebGLBuffer.
  25351. */
  25352. VertexBuffer.prototype.update = function (data) {
  25353. return this._buffer.update(data);
  25354. };
  25355. /**
  25356. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25357. * Returns the directly updated WebGLBuffer.
  25358. */
  25359. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25360. return this._buffer.updateDirectly(data, offset);
  25361. };
  25362. /**
  25363. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25364. */
  25365. VertexBuffer.prototype.dispose = function () {
  25366. if (this._ownsBuffer) {
  25367. this._buffer.dispose();
  25368. }
  25369. };
  25370. Object.defineProperty(VertexBuffer, "PositionKind", {
  25371. get: function () {
  25372. return VertexBuffer._PositionKind;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. Object.defineProperty(VertexBuffer, "NormalKind", {
  25378. get: function () {
  25379. return VertexBuffer._NormalKind;
  25380. },
  25381. enumerable: true,
  25382. configurable: true
  25383. });
  25384. Object.defineProperty(VertexBuffer, "TangentKind", {
  25385. get: function () {
  25386. return VertexBuffer._TangentKind;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Object.defineProperty(VertexBuffer, "UVKind", {
  25392. get: function () {
  25393. return VertexBuffer._UVKind;
  25394. },
  25395. enumerable: true,
  25396. configurable: true
  25397. });
  25398. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25399. get: function () {
  25400. return VertexBuffer._UV2Kind;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25406. get: function () {
  25407. return VertexBuffer._UV3Kind;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25413. get: function () {
  25414. return VertexBuffer._UV4Kind;
  25415. },
  25416. enumerable: true,
  25417. configurable: true
  25418. });
  25419. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25420. get: function () {
  25421. return VertexBuffer._UV5Kind;
  25422. },
  25423. enumerable: true,
  25424. configurable: true
  25425. });
  25426. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25427. get: function () {
  25428. return VertexBuffer._UV6Kind;
  25429. },
  25430. enumerable: true,
  25431. configurable: true
  25432. });
  25433. Object.defineProperty(VertexBuffer, "ColorKind", {
  25434. get: function () {
  25435. return VertexBuffer._ColorKind;
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25441. get: function () {
  25442. return VertexBuffer._MatricesIndicesKind;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25448. get: function () {
  25449. return VertexBuffer._MatricesWeightsKind;
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25455. get: function () {
  25456. return VertexBuffer._MatricesIndicesExtraKind;
  25457. },
  25458. enumerable: true,
  25459. configurable: true
  25460. });
  25461. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25462. get: function () {
  25463. return VertexBuffer._MatricesWeightsExtraKind;
  25464. },
  25465. enumerable: true,
  25466. configurable: true
  25467. });
  25468. /**
  25469. * Deduces the stride given a kind.
  25470. * @param kind The kind string to deduce
  25471. * @returns The deduced stride
  25472. */
  25473. VertexBuffer.DeduceStride = function (kind) {
  25474. switch (kind) {
  25475. case VertexBuffer.PositionKind:
  25476. return 3;
  25477. case VertexBuffer.NormalKind:
  25478. return 3;
  25479. case VertexBuffer.UVKind:
  25480. case VertexBuffer.UV2Kind:
  25481. case VertexBuffer.UV3Kind:
  25482. case VertexBuffer.UV4Kind:
  25483. case VertexBuffer.UV5Kind:
  25484. case VertexBuffer.UV6Kind:
  25485. return 2;
  25486. case VertexBuffer.TangentKind:
  25487. case VertexBuffer.ColorKind:
  25488. return 4;
  25489. case VertexBuffer.MatricesIndicesKind:
  25490. case VertexBuffer.MatricesIndicesExtraKind:
  25491. return 4;
  25492. case VertexBuffer.MatricesWeightsKind:
  25493. case VertexBuffer.MatricesWeightsExtraKind:
  25494. return 4;
  25495. default:
  25496. throw new Error("Invalid kind '" + kind + "'");
  25497. }
  25498. };
  25499. // Enums
  25500. VertexBuffer._PositionKind = "position";
  25501. VertexBuffer._NormalKind = "normal";
  25502. VertexBuffer._TangentKind = "tangent";
  25503. VertexBuffer._UVKind = "uv";
  25504. VertexBuffer._UV2Kind = "uv2";
  25505. VertexBuffer._UV3Kind = "uv3";
  25506. VertexBuffer._UV4Kind = "uv4";
  25507. VertexBuffer._UV5Kind = "uv5";
  25508. VertexBuffer._UV6Kind = "uv6";
  25509. VertexBuffer._ColorKind = "color";
  25510. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25511. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25512. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25513. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25514. return VertexBuffer;
  25515. }());
  25516. BABYLON.VertexBuffer = VertexBuffer;
  25517. })(BABYLON || (BABYLON = {}));
  25518. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25519. var BABYLON;
  25520. (function (BABYLON) {
  25521. /**
  25522. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25523. */
  25524. var DummyInternalTextureTracker = /** @class */ (function () {
  25525. function DummyInternalTextureTracker() {
  25526. /**
  25527. * Gets or set the previous tracker in the list
  25528. */
  25529. this.previous = null;
  25530. /**
  25531. * Gets or set the next tracker in the list
  25532. */
  25533. this.next = null;
  25534. }
  25535. return DummyInternalTextureTracker;
  25536. }());
  25537. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25538. })(BABYLON || (BABYLON = {}));
  25539. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25540. var BABYLON;
  25541. (function (BABYLON) {
  25542. /**
  25543. * Class used to store data associated with WebGL texture data for the engine
  25544. * This class should not be used directly
  25545. */
  25546. var InternalTexture = /** @class */ (function () {
  25547. /**
  25548. * Creates a new InternalTexture
  25549. * @param engine defines the engine to use
  25550. * @param dataSource defines the type of data that will be used
  25551. */
  25552. function InternalTexture(engine, dataSource) {
  25553. /**
  25554. * Observable called when the texture is loaded
  25555. */
  25556. this.onLoadedObservable = new BABYLON.Observable();
  25557. /**
  25558. * Gets or set the previous tracker in the list
  25559. */
  25560. this.previous = null;
  25561. /**
  25562. * Gets or set the next tracker in the list
  25563. */
  25564. this.next = null;
  25565. // Private
  25566. /** @ignore */
  25567. this._initialSlot = -1;
  25568. /** @ignore */
  25569. this._designatedSlot = -1;
  25570. /** @ignore */
  25571. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25572. /** @ignore */
  25573. this._references = 1;
  25574. this._engine = engine;
  25575. this._dataSource = dataSource;
  25576. this._webGLTexture = engine._createTexture();
  25577. }
  25578. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25579. /**
  25580. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25581. */
  25582. get: function () {
  25583. return this._dataSource;
  25584. },
  25585. enumerable: true,
  25586. configurable: true
  25587. });
  25588. /**
  25589. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25590. */
  25591. InternalTexture.prototype.incrementReferences = function () {
  25592. this._references++;
  25593. };
  25594. /**
  25595. * Change the size of the texture (not the size of the content)
  25596. * @param width defines the new width
  25597. * @param height defines the new height
  25598. * @param depth defines the new depth (1 by default)
  25599. */
  25600. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25601. if (depth === void 0) { depth = 1; }
  25602. this.width = width;
  25603. this.height = height;
  25604. this.depth = depth;
  25605. this.baseWidth = width;
  25606. this.baseHeight = height;
  25607. this.baseDepth = depth;
  25608. this._size = width * height * depth;
  25609. };
  25610. /** @ignore */
  25611. InternalTexture.prototype._rebuild = function () {
  25612. var _this = this;
  25613. var proxy;
  25614. this.isReady = false;
  25615. this._cachedCoordinatesMode = null;
  25616. this._cachedWrapU = null;
  25617. this._cachedWrapV = null;
  25618. this._cachedAnisotropicFilteringLevel = null;
  25619. switch (this._dataSource) {
  25620. case InternalTexture.DATASOURCE_TEMP:
  25621. return;
  25622. case InternalTexture.DATASOURCE_URL:
  25623. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25624. _this.isReady = true;
  25625. }, null, this._buffer, undefined, this.format);
  25626. proxy._swapAndDie(this);
  25627. return;
  25628. case InternalTexture.DATASOURCE_RAW:
  25629. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25630. proxy._swapAndDie(this);
  25631. this.isReady = true;
  25632. return;
  25633. case InternalTexture.DATASOURCE_RAW3D:
  25634. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25635. proxy._swapAndDie(this);
  25636. this.isReady = true;
  25637. return;
  25638. case InternalTexture.DATASOURCE_DYNAMIC:
  25639. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25640. proxy._swapAndDie(this);
  25641. // The engine will make sure to update content so no need to flag it as isReady = true
  25642. return;
  25643. case InternalTexture.DATASOURCE_RENDERTARGET:
  25644. var options = new BABYLON.RenderTargetCreationOptions();
  25645. options.generateDepthBuffer = this._generateDepthBuffer;
  25646. options.generateMipMaps = this.generateMipMaps;
  25647. options.generateStencilBuffer = this._generateStencilBuffer;
  25648. options.samplingMode = this.samplingMode;
  25649. options.type = this.type;
  25650. if (this.isCube) {
  25651. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25652. }
  25653. else {
  25654. var size = {
  25655. width: this.width,
  25656. height: this.height
  25657. };
  25658. proxy = this._engine.createRenderTargetTexture(size, options);
  25659. }
  25660. proxy._swapAndDie(this);
  25661. this.isReady = true;
  25662. return;
  25663. case InternalTexture.DATASOURCE_CUBE:
  25664. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25665. _this.isReady = true;
  25666. }, null, this.format, this._extension);
  25667. proxy._swapAndDie(this);
  25668. return;
  25669. case InternalTexture.DATASOURCE_CUBERAW:
  25670. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25671. proxy._swapAndDie(this);
  25672. this.isReady = true;
  25673. return;
  25674. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25675. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25676. if (proxy) {
  25677. proxy._swapAndDie(_this);
  25678. }
  25679. _this.isReady = true;
  25680. }, null, this.format, this._extension);
  25681. return;
  25682. }
  25683. };
  25684. InternalTexture.prototype._swapAndDie = function (target) {
  25685. target._webGLTexture = this._webGLTexture;
  25686. if (this._framebuffer) {
  25687. target._framebuffer = this._framebuffer;
  25688. }
  25689. if (this._depthStencilBuffer) {
  25690. target._depthStencilBuffer = this._depthStencilBuffer;
  25691. }
  25692. if (this._lodTextureHigh) {
  25693. if (target._lodTextureHigh) {
  25694. target._lodTextureHigh.dispose();
  25695. }
  25696. target._lodTextureHigh = this._lodTextureHigh;
  25697. }
  25698. if (this._lodTextureMid) {
  25699. if (target._lodTextureMid) {
  25700. target._lodTextureMid.dispose();
  25701. }
  25702. target._lodTextureMid = this._lodTextureMid;
  25703. }
  25704. if (this._lodTextureLow) {
  25705. if (target._lodTextureLow) {
  25706. target._lodTextureLow.dispose();
  25707. }
  25708. target._lodTextureLow = this._lodTextureLow;
  25709. }
  25710. var cache = this._engine.getLoadedTexturesCache();
  25711. var index = cache.indexOf(this);
  25712. if (index !== -1) {
  25713. cache.splice(index, 1);
  25714. }
  25715. };
  25716. /**
  25717. * Dispose the current allocated resources
  25718. */
  25719. InternalTexture.prototype.dispose = function () {
  25720. if (!this._webGLTexture) {
  25721. return;
  25722. }
  25723. this._references--;
  25724. if (this._references === 0) {
  25725. this._engine._releaseTexture(this);
  25726. this._webGLTexture = null;
  25727. this.previous = null;
  25728. this.next = null;
  25729. }
  25730. };
  25731. /**
  25732. * The source of the texture data is unknown
  25733. */
  25734. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25735. /**
  25736. * Texture data comes from an URL
  25737. */
  25738. InternalTexture.DATASOURCE_URL = 1;
  25739. /**
  25740. * Texture data is only used for temporary storage
  25741. */
  25742. InternalTexture.DATASOURCE_TEMP = 2;
  25743. /**
  25744. * Texture data comes from raw data (ArrayBuffer)
  25745. */
  25746. InternalTexture.DATASOURCE_RAW = 3;
  25747. /**
  25748. * Texture content is dynamic (video or dynamic texture)
  25749. */
  25750. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25751. /**
  25752. * Texture content is generated by rendering to it
  25753. */
  25754. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25755. /**
  25756. * Texture content is part of a multi render target process
  25757. */
  25758. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25759. /**
  25760. * Texture data comes from a cube data file
  25761. */
  25762. InternalTexture.DATASOURCE_CUBE = 7;
  25763. /**
  25764. * Texture data comes from a raw cube data
  25765. */
  25766. InternalTexture.DATASOURCE_CUBERAW = 8;
  25767. /**
  25768. * Texture data come from a prefiltered cube data file
  25769. */
  25770. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25771. /**
  25772. * Texture content is raw 3D data
  25773. */
  25774. InternalTexture.DATASOURCE_RAW3D = 10;
  25775. return InternalTexture;
  25776. }());
  25777. BABYLON.InternalTexture = InternalTexture;
  25778. })(BABYLON || (BABYLON = {}));
  25779. //# sourceMappingURL=babylon.internalTexture.js.map
  25780. var BABYLON;
  25781. (function (BABYLON) {
  25782. var BaseTexture = /** @class */ (function () {
  25783. function BaseTexture(scene) {
  25784. this._hasAlpha = false;
  25785. this.getAlphaFromRGB = false;
  25786. this.level = 1;
  25787. this.coordinatesIndex = 0;
  25788. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25789. /*
  25790. * How a texture is mapped.
  25791. *
  25792. * | Value | Type | Description |
  25793. * | ----- | ----------------------------------- | ----------- |
  25794. * | 0 | EXPLICIT_MODE | |
  25795. * | 1 | SPHERICAL_MODE | |
  25796. * | 2 | PLANAR_MODE | |
  25797. * | 3 | CUBIC_MODE | |
  25798. * | 4 | PROJECTION_MODE | |
  25799. * | 5 | SKYBOX_MODE | |
  25800. * | 6 | INVCUBIC_MODE | |
  25801. * | 7 | EQUIRECTANGULAR_MODE | |
  25802. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25803. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25804. */
  25805. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25806. /*
  25807. * | Value | Type | Description |
  25808. * | ----- | ------------------ | ----------- |
  25809. * | 0 | CLAMP_ADDRESSMODE | |
  25810. * | 1 | WRAP_ADDRESSMODE | |
  25811. * | 2 | MIRROR_ADDRESSMODE | |
  25812. */
  25813. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25814. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25815. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25816. this.isCube = false;
  25817. this.is3D = false;
  25818. this.gammaSpace = true;
  25819. this.invertZ = false;
  25820. this.lodLevelInAlpha = false;
  25821. this.lodGenerationOffset = 0.0;
  25822. this.lodGenerationScale = 0.8;
  25823. this.isRenderTarget = false;
  25824. this.animations = new Array();
  25825. /**
  25826. * An event triggered when the texture is disposed.
  25827. * @type {BABYLON.Observable}
  25828. */
  25829. this.onDisposeObservable = new BABYLON.Observable();
  25830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25831. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25832. if (this._scene) {
  25833. this._scene.textures.push(this);
  25834. }
  25835. this._uid = null;
  25836. }
  25837. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25838. get: function () {
  25839. return this._hasAlpha;
  25840. },
  25841. set: function (value) {
  25842. if (this._hasAlpha === value) {
  25843. return;
  25844. }
  25845. this._hasAlpha = value;
  25846. if (this._scene) {
  25847. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25848. }
  25849. },
  25850. enumerable: true,
  25851. configurable: true
  25852. });
  25853. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25854. get: function () {
  25855. return this._coordinatesMode;
  25856. },
  25857. set: function (value) {
  25858. if (this._coordinatesMode === value) {
  25859. return;
  25860. }
  25861. this._coordinatesMode = value;
  25862. if (this._scene) {
  25863. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25864. }
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(BaseTexture.prototype, "uid", {
  25870. get: function () {
  25871. if (!this._uid) {
  25872. this._uid = BABYLON.Tools.RandomId();
  25873. }
  25874. return this._uid;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. BaseTexture.prototype.toString = function () {
  25880. return this.name;
  25881. };
  25882. BaseTexture.prototype.getClassName = function () {
  25883. return "BaseTexture";
  25884. };
  25885. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25886. set: function (callback) {
  25887. if (this._onDisposeObserver) {
  25888. this.onDisposeObservable.remove(this._onDisposeObserver);
  25889. }
  25890. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25896. get: function () {
  25897. return true;
  25898. },
  25899. enumerable: true,
  25900. configurable: true
  25901. });
  25902. BaseTexture.prototype.getScene = function () {
  25903. return this._scene;
  25904. };
  25905. BaseTexture.prototype.getTextureMatrix = function () {
  25906. return BABYLON.Matrix.IdentityReadOnly;
  25907. };
  25908. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25909. return BABYLON.Matrix.IdentityReadOnly;
  25910. };
  25911. BaseTexture.prototype.getInternalTexture = function () {
  25912. return this._texture;
  25913. };
  25914. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25915. return !this.isBlocking || this.isReady();
  25916. };
  25917. BaseTexture.prototype.isReady = function () {
  25918. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25919. this.delayLoad();
  25920. return false;
  25921. }
  25922. if (this._texture) {
  25923. return this._texture.isReady;
  25924. }
  25925. return false;
  25926. };
  25927. BaseTexture.prototype.getSize = function () {
  25928. if (this._texture && this._texture.width) {
  25929. return new BABYLON.Size(this._texture.width, this._texture.height);
  25930. }
  25931. if (this._texture && this._texture._size) {
  25932. return new BABYLON.Size(this._texture._size, this._texture._size);
  25933. }
  25934. return BABYLON.Size.Zero();
  25935. };
  25936. BaseTexture.prototype.getBaseSize = function () {
  25937. if (!this.isReady() || !this._texture)
  25938. return BABYLON.Size.Zero();
  25939. if (this._texture._size) {
  25940. return new BABYLON.Size(this._texture._size, this._texture._size);
  25941. }
  25942. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25943. };
  25944. BaseTexture.prototype.scale = function (ratio) {
  25945. };
  25946. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25947. get: function () {
  25948. return false;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25954. if (!this._scene) {
  25955. return null;
  25956. }
  25957. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25958. for (var index = 0; index < texturesCache.length; index++) {
  25959. var texturesCacheEntry = texturesCache[index];
  25960. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25961. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25962. texturesCacheEntry.incrementReferences();
  25963. return texturesCacheEntry;
  25964. }
  25965. }
  25966. }
  25967. return null;
  25968. };
  25969. BaseTexture.prototype._rebuild = function () {
  25970. };
  25971. BaseTexture.prototype.delayLoad = function () {
  25972. };
  25973. BaseTexture.prototype.clone = function () {
  25974. return null;
  25975. };
  25976. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25977. get: function () {
  25978. if (!this._texture) {
  25979. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25980. }
  25981. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25982. },
  25983. enumerable: true,
  25984. configurable: true
  25985. });
  25986. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25987. get: function () {
  25988. if (!this._texture) {
  25989. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25990. }
  25991. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25992. },
  25993. enumerable: true,
  25994. configurable: true
  25995. });
  25996. BaseTexture.prototype.readPixels = function (faceIndex) {
  25997. if (faceIndex === void 0) { faceIndex = 0; }
  25998. if (!this._texture) {
  25999. return null;
  26000. }
  26001. var size = this.getSize();
  26002. var scene = this.getScene();
  26003. if (!scene) {
  26004. return null;
  26005. }
  26006. var engine = scene.getEngine();
  26007. if (this._texture.isCube) {
  26008. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26009. }
  26010. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26011. };
  26012. BaseTexture.prototype.releaseInternalTexture = function () {
  26013. if (this._texture) {
  26014. this._texture.dispose();
  26015. this._texture = null;
  26016. }
  26017. };
  26018. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26019. get: function () {
  26020. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26021. return null;
  26022. }
  26023. if (!this._texture._sphericalPolynomial) {
  26024. this._texture._sphericalPolynomial =
  26025. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26026. }
  26027. return this._texture._sphericalPolynomial;
  26028. },
  26029. set: function (value) {
  26030. if (this._texture) {
  26031. this._texture._sphericalPolynomial = value;
  26032. }
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26038. get: function () {
  26039. if (this._texture) {
  26040. return this._texture._lodTextureHigh;
  26041. }
  26042. return null;
  26043. },
  26044. enumerable: true,
  26045. configurable: true
  26046. });
  26047. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26048. get: function () {
  26049. if (this._texture) {
  26050. return this._texture._lodTextureMid;
  26051. }
  26052. return null;
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26058. get: function () {
  26059. if (this._texture) {
  26060. return this._texture._lodTextureLow;
  26061. }
  26062. return null;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. BaseTexture.prototype.dispose = function () {
  26068. if (!this._scene) {
  26069. return;
  26070. }
  26071. // Animations
  26072. this._scene.stopAnimation(this);
  26073. // Remove from scene
  26074. this._scene._removePendingData(this);
  26075. var index = this._scene.textures.indexOf(this);
  26076. if (index >= 0) {
  26077. this._scene.textures.splice(index, 1);
  26078. }
  26079. if (this._texture === undefined) {
  26080. return;
  26081. }
  26082. // Release
  26083. this.releaseInternalTexture();
  26084. // Callback
  26085. this.onDisposeObservable.notifyObservers(this);
  26086. this.onDisposeObservable.clear();
  26087. };
  26088. BaseTexture.prototype.serialize = function () {
  26089. if (!this.name) {
  26090. return null;
  26091. }
  26092. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26093. // Animations
  26094. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26095. return serializationObject;
  26096. };
  26097. BaseTexture.WhenAllReady = function (textures, callback) {
  26098. var numRemaining = textures.length;
  26099. if (numRemaining === 0) {
  26100. callback();
  26101. return;
  26102. }
  26103. var _loop_1 = function () {
  26104. texture = textures[i];
  26105. if (texture.isReady()) {
  26106. if (--numRemaining === 0) {
  26107. callback();
  26108. }
  26109. }
  26110. else {
  26111. onLoadObservable = texture.onLoadObservable;
  26112. var onLoadCallback_1 = function () {
  26113. onLoadObservable.removeCallback(onLoadCallback_1);
  26114. if (--numRemaining === 0) {
  26115. callback();
  26116. }
  26117. };
  26118. onLoadObservable.add(onLoadCallback_1);
  26119. }
  26120. };
  26121. var texture, onLoadObservable;
  26122. for (var i = 0; i < textures.length; i++) {
  26123. _loop_1();
  26124. }
  26125. };
  26126. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26127. __decorate([
  26128. BABYLON.serialize()
  26129. ], BaseTexture.prototype, "name", void 0);
  26130. __decorate([
  26131. BABYLON.serialize("hasAlpha")
  26132. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26133. __decorate([
  26134. BABYLON.serialize()
  26135. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26136. __decorate([
  26137. BABYLON.serialize()
  26138. ], BaseTexture.prototype, "level", void 0);
  26139. __decorate([
  26140. BABYLON.serialize()
  26141. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26142. __decorate([
  26143. BABYLON.serialize("coordinatesMode")
  26144. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26145. __decorate([
  26146. BABYLON.serialize()
  26147. ], BaseTexture.prototype, "wrapU", void 0);
  26148. __decorate([
  26149. BABYLON.serialize()
  26150. ], BaseTexture.prototype, "wrapV", void 0);
  26151. __decorate([
  26152. BABYLON.serialize()
  26153. ], BaseTexture.prototype, "wrapR", void 0);
  26154. __decorate([
  26155. BABYLON.serialize()
  26156. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26157. __decorate([
  26158. BABYLON.serialize()
  26159. ], BaseTexture.prototype, "isCube", void 0);
  26160. __decorate([
  26161. BABYLON.serialize()
  26162. ], BaseTexture.prototype, "is3D", void 0);
  26163. __decorate([
  26164. BABYLON.serialize()
  26165. ], BaseTexture.prototype, "gammaSpace", void 0);
  26166. __decorate([
  26167. BABYLON.serialize()
  26168. ], BaseTexture.prototype, "invertZ", void 0);
  26169. __decorate([
  26170. BABYLON.serialize()
  26171. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26172. __decorate([
  26173. BABYLON.serialize()
  26174. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26175. __decorate([
  26176. BABYLON.serialize()
  26177. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26178. __decorate([
  26179. BABYLON.serialize()
  26180. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26181. return BaseTexture;
  26182. }());
  26183. BABYLON.BaseTexture = BaseTexture;
  26184. })(BABYLON || (BABYLON = {}));
  26185. //# sourceMappingURL=babylon.baseTexture.js.map
  26186. var BABYLON;
  26187. (function (BABYLON) {
  26188. var Texture = /** @class */ (function (_super) {
  26189. __extends(Texture, _super);
  26190. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26191. if (noMipmap === void 0) { noMipmap = false; }
  26192. if (invertY === void 0) { invertY = true; }
  26193. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26194. if (onLoad === void 0) { onLoad = null; }
  26195. if (onError === void 0) { onError = null; }
  26196. if (buffer === void 0) { buffer = null; }
  26197. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26198. var _this = _super.call(this, scene) || this;
  26199. _this.uOffset = 0;
  26200. _this.vOffset = 0;
  26201. _this.uScale = 1.0;
  26202. _this.vScale = 1.0;
  26203. _this.uAng = 0;
  26204. _this.vAng = 0;
  26205. _this.wAng = 0;
  26206. _this._isBlocking = true;
  26207. _this.name = url || "";
  26208. _this.url = url;
  26209. _this._noMipmap = noMipmap;
  26210. _this._invertY = invertY;
  26211. _this._samplingMode = samplingMode;
  26212. _this._buffer = buffer;
  26213. _this._deleteBuffer = deleteBuffer;
  26214. if (format) {
  26215. _this._format = format;
  26216. }
  26217. scene = _this.getScene();
  26218. if (!scene) {
  26219. return _this;
  26220. }
  26221. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26222. var load = function () {
  26223. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26224. _this.onLoadObservable.notifyObservers(_this);
  26225. }
  26226. if (onLoad) {
  26227. onLoad();
  26228. }
  26229. if (!_this.isBlocking && scene) {
  26230. scene.resetCachedMaterial();
  26231. }
  26232. };
  26233. if (!_this.url) {
  26234. _this._delayedOnLoad = load;
  26235. _this._delayedOnError = onError;
  26236. return _this;
  26237. }
  26238. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26239. if (!_this._texture) {
  26240. if (!scene.useDelayedTextureLoading) {
  26241. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26242. if (deleteBuffer) {
  26243. delete _this._buffer;
  26244. }
  26245. }
  26246. else {
  26247. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26248. _this._delayedOnLoad = load;
  26249. _this._delayedOnError = onError;
  26250. }
  26251. }
  26252. else {
  26253. if (_this._texture.isReady) {
  26254. BABYLON.Tools.SetImmediate(function () { return load(); });
  26255. }
  26256. else {
  26257. _this._texture.onLoadedObservable.add(load);
  26258. }
  26259. }
  26260. return _this;
  26261. }
  26262. Object.defineProperty(Texture.prototype, "noMipmap", {
  26263. get: function () {
  26264. return this._noMipmap;
  26265. },
  26266. enumerable: true,
  26267. configurable: true
  26268. });
  26269. Object.defineProperty(Texture.prototype, "isBlocking", {
  26270. get: function () {
  26271. return this._isBlocking;
  26272. },
  26273. set: function (value) {
  26274. this._isBlocking = value;
  26275. },
  26276. enumerable: true,
  26277. configurable: true
  26278. });
  26279. Object.defineProperty(Texture.prototype, "samplingMode", {
  26280. get: function () {
  26281. return this._samplingMode;
  26282. },
  26283. enumerable: true,
  26284. configurable: true
  26285. });
  26286. Texture.prototype.updateURL = function (url) {
  26287. this.url = url;
  26288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26289. this.delayLoad();
  26290. };
  26291. Texture.prototype.delayLoad = function () {
  26292. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26293. return;
  26294. }
  26295. var scene = this.getScene();
  26296. if (!scene) {
  26297. return;
  26298. }
  26299. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26300. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26301. if (!this._texture) {
  26302. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26303. if (this._deleteBuffer) {
  26304. delete this._buffer;
  26305. }
  26306. }
  26307. else {
  26308. if (this._delayedOnLoad) {
  26309. if (this._texture.isReady) {
  26310. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26311. }
  26312. else {
  26313. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26314. }
  26315. }
  26316. }
  26317. this._delayedOnLoad = null;
  26318. this._delayedOnError = null;
  26319. };
  26320. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26321. if (!this._texture) {
  26322. return;
  26323. }
  26324. var scene = this.getScene();
  26325. if (!scene) {
  26326. return;
  26327. }
  26328. this._samplingMode = samplingMode;
  26329. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26330. };
  26331. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26332. x *= this.uScale;
  26333. y *= this.vScale;
  26334. x -= 0.5 * this.uScale;
  26335. y -= 0.5 * this.vScale;
  26336. z -= 0.5;
  26337. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26338. t.x += 0.5 * this.uScale + this.uOffset;
  26339. t.y += 0.5 * this.vScale + this.vOffset;
  26340. t.z += 0.5;
  26341. };
  26342. Texture.prototype.getTextureMatrix = function () {
  26343. var _this = this;
  26344. if (this.uOffset === this._cachedUOffset &&
  26345. this.vOffset === this._cachedVOffset &&
  26346. this.uScale === this._cachedUScale &&
  26347. this.vScale === this._cachedVScale &&
  26348. this.uAng === this._cachedUAng &&
  26349. this.vAng === this._cachedVAng &&
  26350. this.wAng === this._cachedWAng) {
  26351. return this._cachedTextureMatrix;
  26352. }
  26353. this._cachedUOffset = this.uOffset;
  26354. this._cachedVOffset = this.vOffset;
  26355. this._cachedUScale = this.uScale;
  26356. this._cachedVScale = this.vScale;
  26357. this._cachedUAng = this.uAng;
  26358. this._cachedVAng = this.vAng;
  26359. this._cachedWAng = this.wAng;
  26360. if (!this._cachedTextureMatrix) {
  26361. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26362. this._rowGenerationMatrix = new BABYLON.Matrix();
  26363. this._t0 = BABYLON.Vector3.Zero();
  26364. this._t1 = BABYLON.Vector3.Zero();
  26365. this._t2 = BABYLON.Vector3.Zero();
  26366. }
  26367. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26368. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26369. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26370. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26371. this._t1.subtractInPlace(this._t0);
  26372. this._t2.subtractInPlace(this._t0);
  26373. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26374. this._cachedTextureMatrix.m[0] = this._t1.x;
  26375. this._cachedTextureMatrix.m[1] = this._t1.y;
  26376. this._cachedTextureMatrix.m[2] = this._t1.z;
  26377. this._cachedTextureMatrix.m[4] = this._t2.x;
  26378. this._cachedTextureMatrix.m[5] = this._t2.y;
  26379. this._cachedTextureMatrix.m[6] = this._t2.z;
  26380. this._cachedTextureMatrix.m[8] = this._t0.x;
  26381. this._cachedTextureMatrix.m[9] = this._t0.y;
  26382. this._cachedTextureMatrix.m[10] = this._t0.z;
  26383. var scene = this.getScene();
  26384. if (!scene) {
  26385. return this._cachedTextureMatrix;
  26386. }
  26387. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26388. return mat.hasTexture(_this);
  26389. });
  26390. return this._cachedTextureMatrix;
  26391. };
  26392. Texture.prototype.getReflectionTextureMatrix = function () {
  26393. var _this = this;
  26394. var scene = this.getScene();
  26395. if (!scene) {
  26396. return this._cachedTextureMatrix;
  26397. }
  26398. if (this.uOffset === this._cachedUOffset &&
  26399. this.vOffset === this._cachedVOffset &&
  26400. this.uScale === this._cachedUScale &&
  26401. this.vScale === this._cachedVScale &&
  26402. this.coordinatesMode === this._cachedCoordinatesMode) {
  26403. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26404. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26405. return this._cachedTextureMatrix;
  26406. }
  26407. }
  26408. else {
  26409. return this._cachedTextureMatrix;
  26410. }
  26411. }
  26412. if (!this._cachedTextureMatrix) {
  26413. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26414. }
  26415. if (!this._projectionModeMatrix) {
  26416. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26417. }
  26418. this._cachedUOffset = this.uOffset;
  26419. this._cachedVOffset = this.vOffset;
  26420. this._cachedUScale = this.uScale;
  26421. this._cachedVScale = this.vScale;
  26422. this._cachedCoordinatesMode = this.coordinatesMode;
  26423. switch (this.coordinatesMode) {
  26424. case Texture.PLANAR_MODE:
  26425. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26426. this._cachedTextureMatrix[0] = this.uScale;
  26427. this._cachedTextureMatrix[5] = this.vScale;
  26428. this._cachedTextureMatrix[12] = this.uOffset;
  26429. this._cachedTextureMatrix[13] = this.vOffset;
  26430. break;
  26431. case Texture.PROJECTION_MODE:
  26432. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26433. this._projectionModeMatrix.m[0] = 0.5;
  26434. this._projectionModeMatrix.m[5] = -0.5;
  26435. this._projectionModeMatrix.m[10] = 0.0;
  26436. this._projectionModeMatrix.m[12] = 0.5;
  26437. this._projectionModeMatrix.m[13] = 0.5;
  26438. this._projectionModeMatrix.m[14] = 1.0;
  26439. this._projectionModeMatrix.m[15] = 1.0;
  26440. var projectionMatrix = scene.getProjectionMatrix();
  26441. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26442. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26443. break;
  26444. default:
  26445. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26446. break;
  26447. }
  26448. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26449. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26450. });
  26451. return this._cachedTextureMatrix;
  26452. };
  26453. Texture.prototype.clone = function () {
  26454. var _this = this;
  26455. return BABYLON.SerializationHelper.Clone(function () {
  26456. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26457. }, this);
  26458. };
  26459. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26460. get: function () {
  26461. if (!this._onLoadObservable) {
  26462. this._onLoadObservable = new BABYLON.Observable();
  26463. }
  26464. return this._onLoadObservable;
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Texture.prototype.serialize = function () {
  26470. var serializationObject = _super.prototype.serialize.call(this);
  26471. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26472. serializationObject.base64String = this._buffer;
  26473. serializationObject.name = serializationObject.name.replace("data:", "");
  26474. }
  26475. return serializationObject;
  26476. };
  26477. Texture.prototype.getClassName = function () {
  26478. return "Texture";
  26479. };
  26480. Texture.prototype.dispose = function () {
  26481. _super.prototype.dispose.call(this);
  26482. if (this.onLoadObservable) {
  26483. this.onLoadObservable.clear();
  26484. this._onLoadObservable = null;
  26485. }
  26486. this._delayedOnLoad = null;
  26487. this._delayedOnError = null;
  26488. };
  26489. // Statics
  26490. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26491. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26492. if (onLoad === void 0) { onLoad = null; }
  26493. if (onError === void 0) { onError = null; }
  26494. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26495. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26496. };
  26497. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26498. if (parsedTexture.customType) {
  26499. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26500. // Update Sampling Mode
  26501. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26502. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26503. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26504. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26505. }
  26506. }
  26507. return parsedCustomTexture;
  26508. }
  26509. if (parsedTexture.isCube) {
  26510. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26511. }
  26512. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26513. return null;
  26514. }
  26515. var texture = BABYLON.SerializationHelper.Parse(function () {
  26516. var generateMipMaps = true;
  26517. if (parsedTexture.noMipmap) {
  26518. generateMipMaps = false;
  26519. }
  26520. if (parsedTexture.mirrorPlane) {
  26521. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26522. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26523. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26524. return mirrorTexture;
  26525. }
  26526. else if (parsedTexture.isRenderTarget) {
  26527. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26528. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26529. return renderTargetTexture;
  26530. }
  26531. else {
  26532. var texture;
  26533. if (parsedTexture.base64String) {
  26534. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26535. }
  26536. else {
  26537. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26538. }
  26539. return texture;
  26540. }
  26541. }, parsedTexture, scene);
  26542. // Update Sampling Mode
  26543. if (parsedTexture.samplingMode) {
  26544. var sampling = parsedTexture.samplingMode;
  26545. if (texture._samplingMode !== sampling) {
  26546. texture.updateSamplingMode(sampling);
  26547. }
  26548. }
  26549. // Animations
  26550. if (parsedTexture.animations) {
  26551. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26552. var parsedAnimation = parsedTexture.animations[animationIndex];
  26553. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26554. }
  26555. }
  26556. return texture;
  26557. };
  26558. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26559. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26560. if (noMipmap === void 0) { noMipmap = false; }
  26561. if (invertY === void 0) { invertY = true; }
  26562. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26563. if (onLoad === void 0) { onLoad = null; }
  26564. if (onError === void 0) { onError = null; }
  26565. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26566. if (name.substr(0, 5) !== "data:") {
  26567. name = "data:" + name;
  26568. }
  26569. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26570. };
  26571. // Constants
  26572. Texture.NEAREST_SAMPLINGMODE = 1;
  26573. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26574. Texture.BILINEAR_SAMPLINGMODE = 2;
  26575. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26576. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26577. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26578. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26579. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26580. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26581. Texture.NEAREST_LINEAR = 7;
  26582. Texture.NEAREST_NEAREST = 8;
  26583. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26584. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26585. Texture.LINEAR_LINEAR = 11;
  26586. Texture.LINEAR_NEAREST = 12;
  26587. Texture.EXPLICIT_MODE = 0;
  26588. Texture.SPHERICAL_MODE = 1;
  26589. Texture.PLANAR_MODE = 2;
  26590. Texture.CUBIC_MODE = 3;
  26591. Texture.PROJECTION_MODE = 4;
  26592. Texture.SKYBOX_MODE = 5;
  26593. Texture.INVCUBIC_MODE = 6;
  26594. Texture.EQUIRECTANGULAR_MODE = 7;
  26595. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26596. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26597. Texture.CLAMP_ADDRESSMODE = 0;
  26598. Texture.WRAP_ADDRESSMODE = 1;
  26599. Texture.MIRROR_ADDRESSMODE = 2;
  26600. __decorate([
  26601. BABYLON.serialize()
  26602. ], Texture.prototype, "url", void 0);
  26603. __decorate([
  26604. BABYLON.serialize()
  26605. ], Texture.prototype, "uOffset", void 0);
  26606. __decorate([
  26607. BABYLON.serialize()
  26608. ], Texture.prototype, "vOffset", void 0);
  26609. __decorate([
  26610. BABYLON.serialize()
  26611. ], Texture.prototype, "uScale", void 0);
  26612. __decorate([
  26613. BABYLON.serialize()
  26614. ], Texture.prototype, "vScale", void 0);
  26615. __decorate([
  26616. BABYLON.serialize()
  26617. ], Texture.prototype, "uAng", void 0);
  26618. __decorate([
  26619. BABYLON.serialize()
  26620. ], Texture.prototype, "vAng", void 0);
  26621. __decorate([
  26622. BABYLON.serialize()
  26623. ], Texture.prototype, "wAng", void 0);
  26624. __decorate([
  26625. BABYLON.serialize()
  26626. ], Texture.prototype, "isBlocking", null);
  26627. return Texture;
  26628. }(BABYLON.BaseTexture));
  26629. BABYLON.Texture = Texture;
  26630. })(BABYLON || (BABYLON = {}));
  26631. //# sourceMappingURL=babylon.texture.js.map
  26632. var BABYLON;
  26633. (function (BABYLON) {
  26634. var _InstancesBatch = /** @class */ (function () {
  26635. function _InstancesBatch() {
  26636. this.mustReturn = false;
  26637. this.visibleInstances = new Array();
  26638. this.renderSelf = new Array();
  26639. }
  26640. return _InstancesBatch;
  26641. }());
  26642. BABYLON._InstancesBatch = _InstancesBatch;
  26643. var Mesh = /** @class */ (function (_super) {
  26644. __extends(Mesh, _super);
  26645. /**
  26646. * @constructor
  26647. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26648. * @param {Scene} scene The scene to add this mesh to.
  26649. * @param {Node} parent The parent of this mesh, if it has one
  26650. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26651. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26652. * When false, achieved by calling a clone(), also passing False.
  26653. * This will make creation of children, recursive.
  26654. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26655. */
  26656. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26657. if (scene === void 0) { scene = null; }
  26658. if (parent === void 0) { parent = null; }
  26659. if (source === void 0) { source = null; }
  26660. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26661. var _this = _super.call(this, name, scene) || this;
  26662. // Events
  26663. /**
  26664. * An event triggered before rendering the mesh
  26665. * @type {BABYLON.Observable}
  26666. */
  26667. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26668. /**
  26669. * An event triggered after rendering the mesh
  26670. * @type {BABYLON.Observable}
  26671. */
  26672. _this.onAfterRenderObservable = new BABYLON.Observable();
  26673. /**
  26674. * An event triggered before drawing the mesh
  26675. * @type {BABYLON.Observable}
  26676. */
  26677. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26678. // Members
  26679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26680. _this.instances = new Array();
  26681. _this._LODLevels = new Array();
  26682. _this._visibleInstances = {};
  26683. _this._renderIdForInstances = new Array();
  26684. _this._batchCache = new _InstancesBatch();
  26685. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26686. // Use by builder only to know what orientation were the mesh build in.
  26687. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26688. _this.overrideMaterialSideOrientation = null;
  26689. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26690. // Will be used to save a source mesh reference, If any
  26691. _this._source = null;
  26692. scene = _this.getScene();
  26693. if (source) {
  26694. // Source mesh
  26695. _this._source = source;
  26696. // Geometry
  26697. if (source._geometry) {
  26698. source._geometry.applyToMesh(_this);
  26699. }
  26700. // Deep copy
  26701. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26702. // Metadata
  26703. if (source.metadata && source.metadata.clone) {
  26704. _this.metadata = source.metadata.clone();
  26705. }
  26706. else {
  26707. _this.metadata = source.metadata;
  26708. }
  26709. // Tags
  26710. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26711. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26712. }
  26713. // Parent
  26714. _this.parent = source.parent;
  26715. // Pivot
  26716. _this.setPivotMatrix(source.getPivotMatrix());
  26717. _this.id = name + "." + source.id;
  26718. // Material
  26719. _this.material = source.material;
  26720. var index;
  26721. if (!doNotCloneChildren) {
  26722. // Children
  26723. var directDescendants = source.getDescendants(true);
  26724. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26725. var child = directDescendants[index_1];
  26726. if (child.clone) {
  26727. child.clone(name + "." + child.name, _this);
  26728. }
  26729. }
  26730. }
  26731. // Physics clone
  26732. var physicsEngine = _this.getScene().getPhysicsEngine();
  26733. if (clonePhysicsImpostor && physicsEngine) {
  26734. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26735. if (impostor) {
  26736. _this.physicsImpostor = impostor.clone(_this);
  26737. }
  26738. }
  26739. // Particles
  26740. for (index = 0; index < scene.particleSystems.length; index++) {
  26741. var system = scene.particleSystems[index];
  26742. if (system.emitter === source) {
  26743. system.clone(system.name, _this);
  26744. }
  26745. }
  26746. _this.computeWorldMatrix(true);
  26747. }
  26748. // Parent
  26749. if (parent !== null) {
  26750. _this.parent = parent;
  26751. }
  26752. return _this;
  26753. }
  26754. Object.defineProperty(Mesh, "FRONTSIDE", {
  26755. /**
  26756. * Mesh side orientation : usually the external or front surface
  26757. */
  26758. get: function () {
  26759. return Mesh._FRONTSIDE;
  26760. },
  26761. enumerable: true,
  26762. configurable: true
  26763. });
  26764. Object.defineProperty(Mesh, "BACKSIDE", {
  26765. /**
  26766. * Mesh side orientation : usually the internal or back surface
  26767. */
  26768. get: function () {
  26769. return Mesh._BACKSIDE;
  26770. },
  26771. enumerable: true,
  26772. configurable: true
  26773. });
  26774. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26775. /**
  26776. * Mesh side orientation : both internal and external or front and back surfaces
  26777. */
  26778. get: function () {
  26779. return Mesh._DOUBLESIDE;
  26780. },
  26781. enumerable: true,
  26782. configurable: true
  26783. });
  26784. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26785. /**
  26786. * Mesh side orientation : by default, `FRONTSIDE`
  26787. */
  26788. get: function () {
  26789. return Mesh._DEFAULTSIDE;
  26790. },
  26791. enumerable: true,
  26792. configurable: true
  26793. });
  26794. Object.defineProperty(Mesh, "NO_CAP", {
  26795. /**
  26796. * Mesh cap setting : no cap
  26797. */
  26798. get: function () {
  26799. return Mesh._NO_CAP;
  26800. },
  26801. enumerable: true,
  26802. configurable: true
  26803. });
  26804. Object.defineProperty(Mesh, "CAP_START", {
  26805. /**
  26806. * Mesh cap setting : one cap at the beginning of the mesh
  26807. */
  26808. get: function () {
  26809. return Mesh._CAP_START;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. Object.defineProperty(Mesh, "CAP_END", {
  26815. /**
  26816. * Mesh cap setting : one cap at the end of the mesh
  26817. */
  26818. get: function () {
  26819. return Mesh._CAP_END;
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Object.defineProperty(Mesh, "CAP_ALL", {
  26825. /**
  26826. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26827. */
  26828. get: function () {
  26829. return Mesh._CAP_ALL;
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26835. set: function (callback) {
  26836. if (this._onBeforeDrawObserver) {
  26837. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26838. }
  26839. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26840. },
  26841. enumerable: true,
  26842. configurable: true
  26843. });
  26844. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26845. get: function () {
  26846. return this._morphTargetManager;
  26847. },
  26848. set: function (value) {
  26849. if (this._morphTargetManager === value) {
  26850. return;
  26851. }
  26852. this._morphTargetManager = value;
  26853. this._syncGeometryWithMorphTargetManager();
  26854. },
  26855. enumerable: true,
  26856. configurable: true
  26857. });
  26858. Object.defineProperty(Mesh.prototype, "source", {
  26859. get: function () {
  26860. return this._source;
  26861. },
  26862. enumerable: true,
  26863. configurable: true
  26864. });
  26865. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26866. get: function () {
  26867. return this._unIndexed;
  26868. },
  26869. set: function (value) {
  26870. if (this._unIndexed !== value) {
  26871. this._unIndexed = value;
  26872. this._markSubMeshesAsAttributesDirty();
  26873. }
  26874. },
  26875. enumerable: true,
  26876. configurable: true
  26877. });
  26878. // Methods
  26879. /**
  26880. * Returns the string "Mesh".
  26881. */
  26882. Mesh.prototype.getClassName = function () {
  26883. return "Mesh";
  26884. };
  26885. /**
  26886. * Returns a string.
  26887. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26888. */
  26889. Mesh.prototype.toString = function (fullDetails) {
  26890. var ret = _super.prototype.toString.call(this, fullDetails);
  26891. ret += ", n vertices: " + this.getTotalVertices();
  26892. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26893. if (this.animations) {
  26894. for (var i = 0; i < this.animations.length; i++) {
  26895. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26896. }
  26897. }
  26898. if (fullDetails) {
  26899. if (this._geometry) {
  26900. var ib = this.getIndices();
  26901. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26902. if (vb && ib) {
  26903. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26904. }
  26905. }
  26906. else {
  26907. ret += ", flat shading: UNKNOWN";
  26908. }
  26909. }
  26910. return ret;
  26911. };
  26912. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26913. /**
  26914. * True if the mesh has some Levels Of Details (LOD).
  26915. * Returns a boolean.
  26916. */
  26917. get: function () {
  26918. return this._LODLevels.length > 0;
  26919. },
  26920. enumerable: true,
  26921. configurable: true
  26922. });
  26923. /**
  26924. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26925. * @returns an array of {BABYLON.MeshLODLevel}
  26926. */
  26927. Mesh.prototype.getLODLevels = function () {
  26928. return this._LODLevels;
  26929. };
  26930. Mesh.prototype._sortLODLevels = function () {
  26931. this._LODLevels.sort(function (a, b) {
  26932. if (a.distance < b.distance) {
  26933. return 1;
  26934. }
  26935. if (a.distance > b.distance) {
  26936. return -1;
  26937. }
  26938. return 0;
  26939. });
  26940. };
  26941. /**
  26942. * Add a mesh as LOD level triggered at the given distance.
  26943. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26944. * @param {number} distance The distance from the center of the object to show this level
  26945. * @param {Mesh} mesh The mesh to be added as LOD level
  26946. * @return {Mesh} This mesh (for chaining)
  26947. */
  26948. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26949. if (mesh && mesh._masterMesh) {
  26950. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26951. return this;
  26952. }
  26953. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26954. this._LODLevels.push(level);
  26955. if (mesh) {
  26956. mesh._masterMesh = this;
  26957. }
  26958. this._sortLODLevels();
  26959. return this;
  26960. };
  26961. /**
  26962. * Returns the LOD level mesh at the passed distance or null if not found.
  26963. * It is related to the method `addLODLevel(distance, mesh)`.
  26964. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26965. * Returns an object Mesh or `null`.
  26966. */
  26967. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26968. for (var index = 0; index < this._LODLevels.length; index++) {
  26969. var level = this._LODLevels[index];
  26970. if (level.distance === distance) {
  26971. return level.mesh;
  26972. }
  26973. }
  26974. return null;
  26975. };
  26976. /**
  26977. * Remove a mesh from the LOD array
  26978. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26979. * @param {Mesh} mesh The mesh to be removed.
  26980. * @return {Mesh} This mesh (for chaining)
  26981. */
  26982. Mesh.prototype.removeLODLevel = function (mesh) {
  26983. for (var index = 0; index < this._LODLevels.length; index++) {
  26984. if (this._LODLevels[index].mesh === mesh) {
  26985. this._LODLevels.splice(index, 1);
  26986. if (mesh) {
  26987. mesh._masterMesh = null;
  26988. }
  26989. }
  26990. }
  26991. this._sortLODLevels();
  26992. return this;
  26993. };
  26994. /**
  26995. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26996. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26997. */
  26998. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26999. if (!this._LODLevels || this._LODLevels.length === 0) {
  27000. return this;
  27001. }
  27002. var bSphere;
  27003. if (boundingSphere) {
  27004. bSphere = boundingSphere;
  27005. }
  27006. else {
  27007. var boundingInfo = this.getBoundingInfo();
  27008. bSphere = boundingInfo.boundingSphere;
  27009. }
  27010. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27011. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27012. if (this.onLODLevelSelection) {
  27013. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27014. }
  27015. return this;
  27016. }
  27017. for (var index = 0; index < this._LODLevels.length; index++) {
  27018. var level = this._LODLevels[index];
  27019. if (level.distance < distanceToCamera) {
  27020. if (level.mesh) {
  27021. level.mesh._preActivate();
  27022. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27023. }
  27024. if (this.onLODLevelSelection) {
  27025. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27026. }
  27027. return level.mesh;
  27028. }
  27029. }
  27030. if (this.onLODLevelSelection) {
  27031. this.onLODLevelSelection(distanceToCamera, this, this);
  27032. }
  27033. return this;
  27034. };
  27035. Object.defineProperty(Mesh.prototype, "geometry", {
  27036. /**
  27037. * Returns the mesh internal Geometry object.
  27038. */
  27039. get: function () {
  27040. return this._geometry;
  27041. },
  27042. enumerable: true,
  27043. configurable: true
  27044. });
  27045. /**
  27046. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27047. */
  27048. Mesh.prototype.getTotalVertices = function () {
  27049. if (this._geometry === null || this._geometry === undefined) {
  27050. return 0;
  27051. }
  27052. return this._geometry.getTotalVertices();
  27053. };
  27054. /**
  27055. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27056. * 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.
  27057. * You can force the copy with forceCopy === true
  27058. * Returns null if the mesh has no geometry or no vertex buffer.
  27059. * Possible `kind` values :
  27060. * - BABYLON.VertexBuffer.PositionKind
  27061. * - BABYLON.VertexBuffer.UVKind
  27062. * - BABYLON.VertexBuffer.UV2Kind
  27063. * - BABYLON.VertexBuffer.UV3Kind
  27064. * - BABYLON.VertexBuffer.UV4Kind
  27065. * - BABYLON.VertexBuffer.UV5Kind
  27066. * - BABYLON.VertexBuffer.UV6Kind
  27067. * - BABYLON.VertexBuffer.ColorKind
  27068. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27069. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27070. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27071. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27072. */
  27073. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27074. if (!this._geometry) {
  27075. return null;
  27076. }
  27077. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27078. };
  27079. /**
  27080. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27081. * Returns `null` if the mesh has no geometry.
  27082. * Possible `kind` values :
  27083. * - BABYLON.VertexBuffer.PositionKind
  27084. * - BABYLON.VertexBuffer.UVKind
  27085. * - BABYLON.VertexBuffer.UV2Kind
  27086. * - BABYLON.VertexBuffer.UV3Kind
  27087. * - BABYLON.VertexBuffer.UV4Kind
  27088. * - BABYLON.VertexBuffer.UV5Kind
  27089. * - BABYLON.VertexBuffer.UV6Kind
  27090. * - BABYLON.VertexBuffer.ColorKind
  27091. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27092. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27093. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27094. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27095. */
  27096. Mesh.prototype.getVertexBuffer = function (kind) {
  27097. if (!this._geometry) {
  27098. return null;
  27099. }
  27100. return this._geometry.getVertexBuffer(kind);
  27101. };
  27102. /**
  27103. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27104. * Possible `kind` values :
  27105. * - BABYLON.VertexBuffer.PositionKind
  27106. * - BABYLON.VertexBuffer.UVKind
  27107. * - BABYLON.VertexBuffer.UV2Kind
  27108. * - BABYLON.VertexBuffer.UV3Kind
  27109. * - BABYLON.VertexBuffer.UV4Kind
  27110. * - BABYLON.VertexBuffer.UV5Kind
  27111. * - BABYLON.VertexBuffer.UV6Kind
  27112. * - BABYLON.VertexBuffer.ColorKind
  27113. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27114. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27115. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27116. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27117. */
  27118. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27119. if (!this._geometry) {
  27120. if (this._delayInfo) {
  27121. return this._delayInfo.indexOf(kind) !== -1;
  27122. }
  27123. return false;
  27124. }
  27125. return this._geometry.isVerticesDataPresent(kind);
  27126. };
  27127. /**
  27128. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27129. * Possible `kind` values :
  27130. * - BABYLON.VertexBuffer.PositionKind
  27131. * - BABYLON.VertexBuffer.UVKind
  27132. * - BABYLON.VertexBuffer.UV2Kind
  27133. * - BABYLON.VertexBuffer.UV3Kind
  27134. * - BABYLON.VertexBuffer.UV4Kind
  27135. * - BABYLON.VertexBuffer.UV5Kind
  27136. * - BABYLON.VertexBuffer.UV6Kind
  27137. * - BABYLON.VertexBuffer.ColorKind
  27138. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27139. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27140. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27141. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27142. */
  27143. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27144. if (!this._geometry) {
  27145. if (this._delayInfo) {
  27146. return this._delayInfo.indexOf(kind) !== -1;
  27147. }
  27148. return false;
  27149. }
  27150. return this._geometry.isVertexBufferUpdatable(kind);
  27151. };
  27152. /**
  27153. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27154. * Possible `kind` values :
  27155. * - BABYLON.VertexBuffer.PositionKind
  27156. * - BABYLON.VertexBuffer.UVKind
  27157. * - BABYLON.VertexBuffer.UV2Kind
  27158. * - BABYLON.VertexBuffer.UV3Kind
  27159. * - BABYLON.VertexBuffer.UV4Kind
  27160. * - BABYLON.VertexBuffer.UV5Kind
  27161. * - BABYLON.VertexBuffer.UV6Kind
  27162. * - BABYLON.VertexBuffer.ColorKind
  27163. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27164. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27165. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27166. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27167. */
  27168. Mesh.prototype.getVerticesDataKinds = function () {
  27169. if (!this._geometry) {
  27170. var result = new Array();
  27171. if (this._delayInfo) {
  27172. this._delayInfo.forEach(function (kind, index, array) {
  27173. result.push(kind);
  27174. });
  27175. }
  27176. return result;
  27177. }
  27178. return this._geometry.getVerticesDataKinds();
  27179. };
  27180. /**
  27181. * Returns a positive integer : the total number of indices in this mesh geometry.
  27182. * Returns zero if the mesh has no geometry.
  27183. */
  27184. Mesh.prototype.getTotalIndices = function () {
  27185. if (!this._geometry) {
  27186. return 0;
  27187. }
  27188. return this._geometry.getTotalIndices();
  27189. };
  27190. /**
  27191. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27192. * 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.
  27193. * Returns an empty array if the mesh has no geometry.
  27194. */
  27195. Mesh.prototype.getIndices = function (copyWhenShared) {
  27196. if (!this._geometry) {
  27197. return [];
  27198. }
  27199. return this._geometry.getIndices(copyWhenShared);
  27200. };
  27201. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27202. get: function () {
  27203. return this._masterMesh !== null && this._masterMesh !== undefined;
  27204. },
  27205. enumerable: true,
  27206. configurable: true
  27207. });
  27208. /**
  27209. * Determine if the current mesh is ready to be rendered
  27210. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27211. * @returns true if all associated assets are ready (material, textures, shaders)
  27212. */
  27213. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27214. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27216. return false;
  27217. }
  27218. if (!_super.prototype.isReady.call(this)) {
  27219. return false;
  27220. }
  27221. if (!this.subMeshes || this.subMeshes.length === 0) {
  27222. return true;
  27223. }
  27224. var engine = this.getEngine();
  27225. var scene = this.getScene();
  27226. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27227. this.computeWorldMatrix();
  27228. var mat = this.material || scene.defaultMaterial;
  27229. if (mat) {
  27230. if (mat.storeEffectOnSubMeshes) {
  27231. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27232. var subMesh = _a[_i];
  27233. var effectiveMaterial = subMesh.getMaterial();
  27234. if (effectiveMaterial) {
  27235. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27236. return false;
  27237. }
  27238. }
  27239. }
  27240. }
  27241. else {
  27242. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27243. return false;
  27244. }
  27245. }
  27246. }
  27247. // Shadows
  27248. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27249. var light = _c[_b];
  27250. var generator = light.getShadowGenerator();
  27251. if (generator) {
  27252. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27253. var subMesh = _e[_d];
  27254. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27255. return false;
  27256. }
  27257. }
  27258. }
  27259. }
  27260. // LOD
  27261. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27262. var lod = _g[_f];
  27263. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27264. return false;
  27265. }
  27266. }
  27267. return true;
  27268. };
  27269. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27270. /**
  27271. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27272. * This property is pertinent only for updatable parametric shapes.
  27273. */
  27274. get: function () {
  27275. return this._areNormalsFrozen;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. /**
  27281. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27282. * It has no effect at all on other shapes.
  27283. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27284. * Returns the Mesh.
  27285. */
  27286. Mesh.prototype.freezeNormals = function () {
  27287. this._areNormalsFrozen = true;
  27288. return this;
  27289. };
  27290. /**
  27291. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27292. * It has no effect at all on other shapes.
  27293. * It reactivates the mesh normals computation if it was previously frozen.
  27294. * Returns the Mesh.
  27295. */
  27296. Mesh.prototype.unfreezeNormals = function () {
  27297. this._areNormalsFrozen = false;
  27298. return this;
  27299. };
  27300. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27301. /**
  27302. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27303. */
  27304. set: function (count) {
  27305. this._overridenInstanceCount = count;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. // Methods
  27311. Mesh.prototype._preActivate = function () {
  27312. var sceneRenderId = this.getScene().getRenderId();
  27313. if (this._preActivateId === sceneRenderId) {
  27314. return this;
  27315. }
  27316. this._preActivateId = sceneRenderId;
  27317. this._visibleInstances = null;
  27318. return this;
  27319. };
  27320. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27321. if (this._visibleInstances) {
  27322. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27323. }
  27324. return this;
  27325. };
  27326. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27327. if (!this._visibleInstances) {
  27328. this._visibleInstances = {};
  27329. this._visibleInstances.defaultRenderId = renderId;
  27330. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27331. }
  27332. if (!this._visibleInstances[renderId]) {
  27333. this._visibleInstances[renderId] = new Array();
  27334. }
  27335. this._visibleInstances[renderId].push(instance);
  27336. return this;
  27337. };
  27338. /**
  27339. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27340. * This means the mesh underlying bounding box and sphere are recomputed.
  27341. * Returns the Mesh.
  27342. */
  27343. Mesh.prototype.refreshBoundingInfo = function () {
  27344. return this._refreshBoundingInfo(false);
  27345. };
  27346. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27347. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27348. return this;
  27349. }
  27350. var data = this._getPositionData(applySkeleton);
  27351. if (data) {
  27352. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27353. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27354. }
  27355. if (this.subMeshes) {
  27356. for (var index = 0; index < this.subMeshes.length; index++) {
  27357. this.subMeshes[index].refreshBoundingInfo();
  27358. }
  27359. }
  27360. this._updateBoundingInfo();
  27361. return this;
  27362. };
  27363. Mesh.prototype._getPositionData = function (applySkeleton) {
  27364. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27365. if (data && applySkeleton && this.skeleton) {
  27366. data = BABYLON.Tools.Slice(data);
  27367. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27368. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27369. if (matricesWeightsData && matricesIndicesData) {
  27370. var needExtras = this.numBoneInfluencers > 4;
  27371. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27372. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27373. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27374. var tempVector = BABYLON.Tmp.Vector3[0];
  27375. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27376. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27377. var matWeightIdx = 0;
  27378. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27379. finalMatrix.reset();
  27380. var inf;
  27381. var weight;
  27382. for (inf = 0; inf < 4; inf++) {
  27383. weight = matricesWeightsData[matWeightIdx + inf];
  27384. if (weight <= 0)
  27385. break;
  27386. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27387. finalMatrix.addToSelf(tempMatrix);
  27388. }
  27389. if (needExtras) {
  27390. for (inf = 0; inf < 4; inf++) {
  27391. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27392. if (weight <= 0)
  27393. break;
  27394. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27395. finalMatrix.addToSelf(tempMatrix);
  27396. }
  27397. }
  27398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27399. tempVector.toArray(data, index);
  27400. }
  27401. }
  27402. }
  27403. return data;
  27404. };
  27405. Mesh.prototype._createGlobalSubMesh = function (force) {
  27406. var totalVertices = this.getTotalVertices();
  27407. if (!totalVertices || !this.getIndices()) {
  27408. return null;
  27409. }
  27410. // Check if we need to recreate the submeshes
  27411. if (this.subMeshes && this.subMeshes.length > 0) {
  27412. var ib = this.getIndices();
  27413. if (!ib) {
  27414. return null;
  27415. }
  27416. var totalIndices = ib.length;
  27417. var needToRecreate = false;
  27418. if (force) {
  27419. needToRecreate = true;
  27420. }
  27421. else {
  27422. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27423. var submesh = _a[_i];
  27424. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27425. needToRecreate = true;
  27426. break;
  27427. }
  27428. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27429. needToRecreate = true;
  27430. break;
  27431. }
  27432. }
  27433. }
  27434. if (!needToRecreate) {
  27435. return this.subMeshes[0];
  27436. }
  27437. }
  27438. this.releaseSubMeshes();
  27439. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27440. };
  27441. Mesh.prototype.subdivide = function (count) {
  27442. if (count < 1) {
  27443. return;
  27444. }
  27445. var totalIndices = this.getTotalIndices();
  27446. var subdivisionSize = (totalIndices / count) | 0;
  27447. var offset = 0;
  27448. // Ensure that subdivisionSize is a multiple of 3
  27449. while (subdivisionSize % 3 !== 0) {
  27450. subdivisionSize++;
  27451. }
  27452. this.releaseSubMeshes();
  27453. for (var index = 0; index < count; index++) {
  27454. if (offset >= totalIndices) {
  27455. break;
  27456. }
  27457. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27458. offset += subdivisionSize;
  27459. }
  27460. this.synchronizeInstances();
  27461. };
  27462. /**
  27463. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27464. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27465. * The `data` are either a numeric array either a Float32Array.
  27466. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27467. * 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).
  27468. * Note that a new underlying VertexBuffer object is created each call.
  27469. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27470. *
  27471. * Possible `kind` values :
  27472. * - BABYLON.VertexBuffer.PositionKind
  27473. * - BABYLON.VertexBuffer.UVKind
  27474. * - BABYLON.VertexBuffer.UV2Kind
  27475. * - BABYLON.VertexBuffer.UV3Kind
  27476. * - BABYLON.VertexBuffer.UV4Kind
  27477. * - BABYLON.VertexBuffer.UV5Kind
  27478. * - BABYLON.VertexBuffer.UV6Kind
  27479. * - BABYLON.VertexBuffer.ColorKind
  27480. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27481. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27482. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27483. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27484. *
  27485. * Returns the Mesh.
  27486. */
  27487. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27488. if (updatable === void 0) { updatable = false; }
  27489. if (!this._geometry) {
  27490. var vertexData = new BABYLON.VertexData();
  27491. vertexData.set(data, kind);
  27492. var scene = this.getScene();
  27493. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27494. }
  27495. else {
  27496. this._geometry.setVerticesData(kind, data, updatable, stride);
  27497. }
  27498. return this;
  27499. };
  27500. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27501. if (updatable === void 0) { updatable = true; }
  27502. var vb = this.getVertexBuffer(kind);
  27503. if (!vb || vb.isUpdatable() === updatable) {
  27504. return;
  27505. }
  27506. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27507. };
  27508. /**
  27509. * Sets the mesh VertexBuffer.
  27510. * Returns the Mesh.
  27511. */
  27512. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27513. if (!this._geometry) {
  27514. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27515. }
  27516. this._geometry.setVerticesBuffer(buffer);
  27517. return this;
  27518. };
  27519. /**
  27520. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27521. * If the mesh has no geometry, it is simply returned as it is.
  27522. * The `data` are either a numeric array either a Float32Array.
  27523. * No new underlying VertexBuffer object is created.
  27524. * 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.
  27525. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27526. *
  27527. * Possible `kind` values :
  27528. * - BABYLON.VertexBuffer.PositionKind
  27529. * - BABYLON.VertexBuffer.UVKind
  27530. * - BABYLON.VertexBuffer.UV2Kind
  27531. * - BABYLON.VertexBuffer.UV3Kind
  27532. * - BABYLON.VertexBuffer.UV4Kind
  27533. * - BABYLON.VertexBuffer.UV5Kind
  27534. * - BABYLON.VertexBuffer.UV6Kind
  27535. * - BABYLON.VertexBuffer.ColorKind
  27536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27540. *
  27541. * Returns the Mesh.
  27542. */
  27543. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27544. if (!this._geometry) {
  27545. return this;
  27546. }
  27547. if (!makeItUnique) {
  27548. this._geometry.updateVerticesData(kind, data, updateExtends);
  27549. }
  27550. else {
  27551. this.makeGeometryUnique();
  27552. this.updateVerticesData(kind, data, updateExtends, false);
  27553. }
  27554. return this;
  27555. };
  27556. /**
  27557. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27558. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27559. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27560. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27561. * Returns the Mesh.
  27562. */
  27563. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27564. if (computeNormals === void 0) { computeNormals = true; }
  27565. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27566. if (!positions) {
  27567. return this;
  27568. }
  27569. positionFunction(positions);
  27570. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27571. if (computeNormals) {
  27572. var indices = this.getIndices();
  27573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27574. if (!normals) {
  27575. return this;
  27576. }
  27577. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27578. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27579. }
  27580. return this;
  27581. };
  27582. /**
  27583. * Creates a un-shared specific occurence of the geometry for the mesh.
  27584. * Returns the Mesh.
  27585. */
  27586. Mesh.prototype.makeGeometryUnique = function () {
  27587. if (!this._geometry) {
  27588. return this;
  27589. }
  27590. var oldGeometry = this._geometry;
  27591. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27592. oldGeometry.releaseForMesh(this, true);
  27593. geometry.applyToMesh(this);
  27594. return this;
  27595. };
  27596. /**
  27597. * Sets the mesh indices.
  27598. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27599. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27600. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27601. * This method creates a new index buffer each call.
  27602. * Returns the Mesh.
  27603. */
  27604. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27605. if (totalVertices === void 0) { totalVertices = null; }
  27606. if (updatable === void 0) { updatable = false; }
  27607. if (!this._geometry) {
  27608. var vertexData = new BABYLON.VertexData();
  27609. vertexData.indices = indices;
  27610. var scene = this.getScene();
  27611. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27612. }
  27613. else {
  27614. this._geometry.setIndices(indices, totalVertices, updatable);
  27615. }
  27616. return this;
  27617. };
  27618. /**
  27619. * Update the current index buffer
  27620. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27621. * Returns the Mesh.
  27622. */
  27623. Mesh.prototype.updateIndices = function (indices, offset) {
  27624. if (!this._geometry) {
  27625. return this;
  27626. }
  27627. this._geometry.updateIndices(indices, offset);
  27628. return this;
  27629. };
  27630. /**
  27631. * Invert the geometry to move from a right handed system to a left handed one.
  27632. * Returns the Mesh.
  27633. */
  27634. Mesh.prototype.toLeftHanded = function () {
  27635. if (!this._geometry) {
  27636. return this;
  27637. }
  27638. this._geometry.toLeftHanded();
  27639. return this;
  27640. };
  27641. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27642. if (!this._geometry) {
  27643. return this;
  27644. }
  27645. var engine = this.getScene().getEngine();
  27646. // Wireframe
  27647. var indexToBind;
  27648. if (this._unIndexed) {
  27649. indexToBind = null;
  27650. }
  27651. else {
  27652. switch (fillMode) {
  27653. case BABYLON.Material.PointFillMode:
  27654. indexToBind = null;
  27655. break;
  27656. case BABYLON.Material.WireFrameFillMode:
  27657. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27658. break;
  27659. default:
  27660. case BABYLON.Material.TriangleFillMode:
  27661. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27662. break;
  27663. }
  27664. }
  27665. // VBOs
  27666. this._geometry._bind(effect, indexToBind);
  27667. return this;
  27668. };
  27669. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27670. if (alternate === void 0) { alternate = false; }
  27671. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27672. return this;
  27673. }
  27674. this.onBeforeDrawObservable.notifyObservers(this);
  27675. var scene = this.getScene();
  27676. var engine = scene.getEngine();
  27677. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27678. // or triangles as points
  27679. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27680. }
  27681. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27682. // Triangles as wireframe
  27683. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27684. }
  27685. else {
  27686. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27687. }
  27688. if (scene._isAlternateRenderingEnabled && !alternate) {
  27689. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27690. if (!effect || !scene.activeCamera) {
  27691. return this;
  27692. }
  27693. scene._switchToAlternateCameraConfiguration(true);
  27694. this._effectiveMaterial.bindView(effect);
  27695. this._effectiveMaterial.bindViewProjection(effect);
  27696. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27697. this._draw(subMesh, fillMode, instancesCount, true);
  27698. engine.setViewport(scene.activeCamera.viewport);
  27699. scene._switchToAlternateCameraConfiguration(false);
  27700. this._effectiveMaterial.bindView(effect);
  27701. this._effectiveMaterial.bindViewProjection(effect);
  27702. }
  27703. return this;
  27704. };
  27705. /**
  27706. * Registers for this mesh a javascript function called just before the rendering process.
  27707. * This function is passed the current mesh.
  27708. * Return the Mesh.
  27709. */
  27710. Mesh.prototype.registerBeforeRender = function (func) {
  27711. this.onBeforeRenderObservable.add(func);
  27712. return this;
  27713. };
  27714. /**
  27715. * Disposes a previously registered javascript function called before the rendering.
  27716. * This function is passed the current mesh.
  27717. * Returns the Mesh.
  27718. */
  27719. Mesh.prototype.unregisterBeforeRender = function (func) {
  27720. this.onBeforeRenderObservable.removeCallback(func);
  27721. return this;
  27722. };
  27723. /**
  27724. * Registers for this mesh a javascript function called just after the rendering is complete.
  27725. * This function is passed the current mesh.
  27726. * Returns the Mesh.
  27727. */
  27728. Mesh.prototype.registerAfterRender = function (func) {
  27729. this.onAfterRenderObservable.add(func);
  27730. return this;
  27731. };
  27732. /**
  27733. * Disposes a previously registered javascript function called after the rendering.
  27734. * This function is passed the current mesh.
  27735. * Return the Mesh.
  27736. */
  27737. Mesh.prototype.unregisterAfterRender = function (func) {
  27738. this.onAfterRenderObservable.removeCallback(func);
  27739. return this;
  27740. };
  27741. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27742. var scene = this.getScene();
  27743. this._batchCache.mustReturn = false;
  27744. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27745. this._batchCache.visibleInstances[subMeshId] = null;
  27746. if (this._visibleInstances) {
  27747. var currentRenderId = scene.getRenderId();
  27748. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27749. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27750. var selfRenderId = this._renderId;
  27751. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27752. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27753. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27754. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27755. }
  27756. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27757. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27758. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27759. this._batchCache.mustReturn = true;
  27760. return this._batchCache;
  27761. }
  27762. if (currentRenderId !== selfRenderId) {
  27763. this._batchCache.renderSelf[subMeshId] = false;
  27764. }
  27765. }
  27766. this._renderIdForInstances[subMeshId] = currentRenderId;
  27767. }
  27768. return this._batchCache;
  27769. };
  27770. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27771. var visibleInstances = batch.visibleInstances[subMesh._id];
  27772. if (!visibleInstances) {
  27773. return this;
  27774. }
  27775. var matricesCount = visibleInstances.length + 1;
  27776. var bufferSize = matricesCount * 16 * 4;
  27777. var currentInstancesBufferSize = this._instancesBufferSize;
  27778. var instancesBuffer = this._instancesBuffer;
  27779. while (this._instancesBufferSize < bufferSize) {
  27780. this._instancesBufferSize *= 2;
  27781. }
  27782. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27783. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27784. }
  27785. var offset = 0;
  27786. var instancesCount = 0;
  27787. var world = this.getWorldMatrix();
  27788. if (batch.renderSelf[subMesh._id]) {
  27789. world.copyToArray(this._instancesData, offset);
  27790. offset += 16;
  27791. instancesCount++;
  27792. }
  27793. if (visibleInstances) {
  27794. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27795. var instance = visibleInstances[instanceIndex];
  27796. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27797. offset += 16;
  27798. instancesCount++;
  27799. }
  27800. }
  27801. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27802. if (instancesBuffer) {
  27803. instancesBuffer.dispose();
  27804. }
  27805. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27806. this._instancesBuffer = instancesBuffer;
  27807. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27808. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27809. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27810. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27811. }
  27812. else {
  27813. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27814. }
  27815. this._bind(subMesh, effect, fillMode);
  27816. this._draw(subMesh, fillMode, instancesCount);
  27817. engine.unbindInstanceAttributes();
  27818. return this;
  27819. };
  27820. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27821. var scene = this.getScene();
  27822. var engine = scene.getEngine();
  27823. if (hardwareInstancedRendering) {
  27824. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27825. }
  27826. else {
  27827. if (batch.renderSelf[subMesh._id]) {
  27828. // Draw
  27829. if (onBeforeDraw) {
  27830. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27831. }
  27832. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27833. }
  27834. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27835. if (visibleInstancesForSubMesh) {
  27836. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27837. var instance = visibleInstancesForSubMesh[instanceIndex];
  27838. // World
  27839. var world = instance.getWorldMatrix();
  27840. if (onBeforeDraw) {
  27841. onBeforeDraw(true, world, effectiveMaterial);
  27842. }
  27843. // Draw
  27844. this._draw(subMesh, fillMode);
  27845. }
  27846. }
  27847. }
  27848. return this;
  27849. };
  27850. /**
  27851. * Triggers the draw call for the mesh.
  27852. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27853. * Returns the Mesh.
  27854. */
  27855. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27856. this.checkOcclusionQuery();
  27857. if (this._isOccluded) {
  27858. return this;
  27859. }
  27860. var scene = this.getScene();
  27861. // Managing instances
  27862. var batch = this._getInstancesRenderList(subMesh._id);
  27863. if (batch.mustReturn) {
  27864. return this;
  27865. }
  27866. // Checking geometry state
  27867. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27868. return this;
  27869. }
  27870. this.onBeforeRenderObservable.notifyObservers(this);
  27871. var engine = scene.getEngine();
  27872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27873. // Material
  27874. var material = subMesh.getMaterial();
  27875. if (!material) {
  27876. return this;
  27877. }
  27878. this._effectiveMaterial = material;
  27879. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27880. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27881. return this;
  27882. }
  27883. }
  27884. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27885. return this;
  27886. }
  27887. // Alpha mode
  27888. if (enableAlphaMode) {
  27889. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27890. }
  27891. // Outline - step 1
  27892. var savedDepthWrite = engine.getDepthWrite();
  27893. if (this.renderOutline) {
  27894. engine.setDepthWrite(false);
  27895. scene.getOutlineRenderer().render(subMesh, batch);
  27896. engine.setDepthWrite(savedDepthWrite);
  27897. }
  27898. var effect;
  27899. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27900. effect = subMesh.effect;
  27901. }
  27902. else {
  27903. effect = this._effectiveMaterial.getEffect();
  27904. }
  27905. if (!effect) {
  27906. return this;
  27907. }
  27908. var sideOrientation = this.overrideMaterialSideOrientation;
  27909. if (sideOrientation == null) {
  27910. sideOrientation = this._effectiveMaterial.sideOrientation;
  27911. if (this._getWorldMatrixDeterminant() < 0) {
  27912. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27913. }
  27914. }
  27915. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27916. if (this._effectiveMaterial.forceDepthWrite) {
  27917. engine.setDepthWrite(true);
  27918. }
  27919. // Bind
  27920. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27921. if (!hardwareInstancedRendering) {
  27922. this._bind(subMesh, effect, fillMode);
  27923. }
  27924. var world = this.getWorldMatrix();
  27925. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27926. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27927. }
  27928. else {
  27929. this._effectiveMaterial.bind(world, this);
  27930. }
  27931. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27932. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27933. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27934. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27935. }
  27936. // Draw
  27937. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27938. // Unbind
  27939. this._effectiveMaterial.unbind();
  27940. // Outline - step 2
  27941. if (this.renderOutline && savedDepthWrite) {
  27942. engine.setDepthWrite(true);
  27943. engine.setColorWrite(false);
  27944. scene.getOutlineRenderer().render(subMesh, batch);
  27945. engine.setColorWrite(true);
  27946. }
  27947. // Overlay
  27948. if (this.renderOverlay) {
  27949. var currentMode = engine.getAlphaMode();
  27950. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27951. scene.getOutlineRenderer().render(subMesh, batch, true);
  27952. engine.setAlphaMode(currentMode);
  27953. }
  27954. this.onAfterRenderObservable.notifyObservers(this);
  27955. return this;
  27956. };
  27957. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27958. if (isInstance && effectiveMaterial) {
  27959. effectiveMaterial.bindOnlyWorldMatrix(world);
  27960. }
  27961. };
  27962. /**
  27963. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27964. */
  27965. Mesh.prototype.getEmittedParticleSystems = function () {
  27966. var results = new Array();
  27967. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27968. var particleSystem = this.getScene().particleSystems[index];
  27969. if (particleSystem.emitter === this) {
  27970. results.push(particleSystem);
  27971. }
  27972. }
  27973. return results;
  27974. };
  27975. /**
  27976. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27977. */
  27978. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27979. var results = new Array();
  27980. var descendants = this.getDescendants();
  27981. descendants.push(this);
  27982. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27983. var particleSystem = this.getScene().particleSystems[index];
  27984. var emitter = particleSystem.emitter;
  27985. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27986. results.push(particleSystem);
  27987. }
  27988. }
  27989. return results;
  27990. };
  27991. Mesh.prototype._checkDelayState = function () {
  27992. var scene = this.getScene();
  27993. if (this._geometry) {
  27994. this._geometry.load(scene);
  27995. }
  27996. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27998. this._queueLoad(scene);
  27999. }
  28000. return this;
  28001. };
  28002. Mesh.prototype._queueLoad = function (scene) {
  28003. var _this = this;
  28004. scene._addPendingData(this);
  28005. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28006. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28007. if (data instanceof ArrayBuffer) {
  28008. _this._delayLoadingFunction(data, _this);
  28009. }
  28010. else {
  28011. _this._delayLoadingFunction(JSON.parse(data), _this);
  28012. }
  28013. _this.instances.forEach(function (instance) {
  28014. instance._syncSubMeshes();
  28015. });
  28016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28017. scene._removePendingData(_this);
  28018. }, function () { }, scene.database, getBinaryData);
  28019. return this;
  28020. };
  28021. /**
  28022. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28023. */
  28024. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28026. return false;
  28027. }
  28028. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28029. return false;
  28030. }
  28031. this._checkDelayState();
  28032. return true;
  28033. };
  28034. /**
  28035. * Sets the mesh material by the material or multiMaterial `id` property.
  28036. * The material `id` is a string identifying the material or the multiMaterial.
  28037. * This method returns the Mesh.
  28038. */
  28039. Mesh.prototype.setMaterialByID = function (id) {
  28040. var materials = this.getScene().materials;
  28041. var index;
  28042. for (index = materials.length - 1; index > -1; index--) {
  28043. if (materials[index].id === id) {
  28044. this.material = materials[index];
  28045. return this;
  28046. }
  28047. }
  28048. // Multi
  28049. var multiMaterials = this.getScene().multiMaterials;
  28050. for (index = multiMaterials.length - 1; index > -1; index--) {
  28051. if (multiMaterials[index].id === id) {
  28052. this.material = multiMaterials[index];
  28053. return this;
  28054. }
  28055. }
  28056. return this;
  28057. };
  28058. /**
  28059. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28060. */
  28061. Mesh.prototype.getAnimatables = function () {
  28062. var results = new Array();
  28063. if (this.material) {
  28064. results.push(this.material);
  28065. }
  28066. if (this.skeleton) {
  28067. results.push(this.skeleton);
  28068. }
  28069. return results;
  28070. };
  28071. /**
  28072. * Modifies the mesh geometry according to the passed transformation matrix.
  28073. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28074. * The mesh normals are modified accordingly the same transformation.
  28075. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28076. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28077. * Returns the Mesh.
  28078. */
  28079. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28080. // Position
  28081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28082. return this;
  28083. }
  28084. var submeshes = this.subMeshes.splice(0);
  28085. this._resetPointsArrayCache();
  28086. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28087. var temp = new Array();
  28088. var index;
  28089. for (index = 0; index < data.length; index += 3) {
  28090. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28091. }
  28092. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28093. // Normals
  28094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28095. return this;
  28096. }
  28097. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28098. temp = [];
  28099. for (index = 0; index < data.length; index += 3) {
  28100. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28101. }
  28102. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28103. // flip faces?
  28104. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28105. this.flipFaces();
  28106. }
  28107. // Restore submeshes
  28108. this.releaseSubMeshes();
  28109. this.subMeshes = submeshes;
  28110. return this;
  28111. };
  28112. /**
  28113. * Modifies the mesh geometry according to its own current World Matrix.
  28114. * The mesh World Matrix is then reset.
  28115. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28116. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28117. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28118. * Returns the Mesh.
  28119. */
  28120. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28121. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28122. this.scaling.copyFromFloats(1, 1, 1);
  28123. this.position.copyFromFloats(0, 0, 0);
  28124. this.rotation.copyFromFloats(0, 0, 0);
  28125. //only if quaternion is already set
  28126. if (this.rotationQuaternion) {
  28127. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28128. }
  28129. this._worldMatrix = BABYLON.Matrix.Identity();
  28130. return this;
  28131. };
  28132. Object.defineProperty(Mesh.prototype, "_positions", {
  28133. // Cache
  28134. get: function () {
  28135. if (this._geometry) {
  28136. return this._geometry._positions;
  28137. }
  28138. return null;
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Mesh.prototype._resetPointsArrayCache = function () {
  28144. if (this._geometry) {
  28145. this._geometry._resetPointsArrayCache();
  28146. }
  28147. return this;
  28148. };
  28149. Mesh.prototype._generatePointsArray = function () {
  28150. if (this._geometry) {
  28151. return this._geometry._generatePointsArray();
  28152. }
  28153. return false;
  28154. };
  28155. /**
  28156. * Returns a new Mesh object generated from the current mesh properties.
  28157. * This method must not get confused with createInstance().
  28158. * The parameter `name` is a string, the name given to the new mesh.
  28159. * The optional parameter `newParent` can be any Node object (default `null`).
  28160. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28161. * 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.
  28162. */
  28163. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28164. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28165. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28166. };
  28167. /**
  28168. * Disposes the Mesh.
  28169. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28170. * Returns nothing.
  28171. */
  28172. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28173. var _this = this;
  28174. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28175. this.morphTargetManager = null;
  28176. if (this._geometry) {
  28177. this._geometry.releaseForMesh(this, true);
  28178. }
  28179. // Sources
  28180. var meshes = this.getScene().meshes;
  28181. meshes.forEach(function (abstractMesh) {
  28182. var mesh = abstractMesh;
  28183. if (mesh._source && mesh._source === _this) {
  28184. mesh._source = null;
  28185. }
  28186. });
  28187. this._source = null;
  28188. // Instances
  28189. if (this._instancesBuffer) {
  28190. this._instancesBuffer.dispose();
  28191. this._instancesBuffer = null;
  28192. }
  28193. while (this.instances.length) {
  28194. this.instances[0].dispose();
  28195. }
  28196. // Effect layers.
  28197. var effectLayers = this.getScene().effectLayers;
  28198. for (var i = 0; i < effectLayers.length; i++) {
  28199. var effectLayer = effectLayers[i];
  28200. if (effectLayer) {
  28201. effectLayer._disposeMesh(this);
  28202. }
  28203. }
  28204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28205. };
  28206. /**
  28207. * Modifies the mesh geometry according to a displacement map.
  28208. * 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.
  28209. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28210. * This method returns nothing.
  28211. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28212. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28213. * 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.
  28214. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28215. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28216. *
  28217. * Returns the Mesh.
  28218. */
  28219. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28220. var _this = this;
  28221. var scene = this.getScene();
  28222. var onload = function (img) {
  28223. // Getting height map data
  28224. var canvas = document.createElement("canvas");
  28225. var context = canvas.getContext("2d");
  28226. var heightMapWidth = img.width;
  28227. var heightMapHeight = img.height;
  28228. canvas.width = heightMapWidth;
  28229. canvas.height = heightMapHeight;
  28230. context.drawImage(img, 0, 0);
  28231. // Create VertexData from map data
  28232. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28233. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28234. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28235. //execute success callback, if set
  28236. if (onSuccess) {
  28237. onSuccess(_this);
  28238. }
  28239. };
  28240. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28241. return this;
  28242. };
  28243. /**
  28244. * Modifies the mesh geometry according to a displacementMap buffer.
  28245. * 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.
  28246. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28247. * This method returns nothing.
  28248. * 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.
  28249. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28250. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28251. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28252. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28253. *
  28254. * Returns the Mesh.
  28255. */
  28256. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28258. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28259. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28260. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28261. return this;
  28262. }
  28263. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28264. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28265. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28266. var position = BABYLON.Vector3.Zero();
  28267. var normal = BABYLON.Vector3.Zero();
  28268. var uv = BABYLON.Vector2.Zero();
  28269. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28270. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28271. for (var index = 0; index < positions.length; index += 3) {
  28272. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28273. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28274. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28275. // Compute height
  28276. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28277. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28278. var pos = (u + v * heightMapWidth) * 4;
  28279. var r = buffer[pos] / 255.0;
  28280. var g = buffer[pos + 1] / 255.0;
  28281. var b = buffer[pos + 2] / 255.0;
  28282. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28283. normal.normalize();
  28284. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28285. position = position.add(normal);
  28286. position.toArray(positions, index);
  28287. }
  28288. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28289. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28291. return this;
  28292. };
  28293. /**
  28294. * Modify the mesh to get a flat shading rendering.
  28295. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28296. * This method returns the Mesh.
  28297. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28298. */
  28299. Mesh.prototype.convertToFlatShadedMesh = function () {
  28300. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28301. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28302. var kinds = this.getVerticesDataKinds();
  28303. var vbs = {};
  28304. var data = {};
  28305. var newdata = {};
  28306. var updatableNormals = false;
  28307. var kindIndex;
  28308. var kind;
  28309. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28310. kind = kinds[kindIndex];
  28311. var vertexBuffer = this.getVertexBuffer(kind);
  28312. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28313. updatableNormals = vertexBuffer.isUpdatable();
  28314. kinds.splice(kindIndex, 1);
  28315. kindIndex--;
  28316. continue;
  28317. }
  28318. vbs[kind] = vertexBuffer;
  28319. data[kind] = vbs[kind].getData();
  28320. newdata[kind] = [];
  28321. }
  28322. // Save previous submeshes
  28323. var previousSubmeshes = this.subMeshes.slice(0);
  28324. var indices = this.getIndices();
  28325. var totalIndices = this.getTotalIndices();
  28326. // Generating unique vertices per face
  28327. var index;
  28328. for (index = 0; index < totalIndices; index++) {
  28329. var vertexIndex = indices[index];
  28330. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28331. kind = kinds[kindIndex];
  28332. var stride = vbs[kind].getStrideSize();
  28333. for (var offset = 0; offset < stride; offset++) {
  28334. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28335. }
  28336. }
  28337. }
  28338. // Updating faces & normal
  28339. var normals = [];
  28340. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28341. for (index = 0; index < totalIndices; index += 3) {
  28342. indices[index] = index;
  28343. indices[index + 1] = index + 1;
  28344. indices[index + 2] = index + 2;
  28345. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28346. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28347. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28348. var p1p2 = p1.subtract(p2);
  28349. var p3p2 = p3.subtract(p2);
  28350. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28351. // Store same normals for every vertex
  28352. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28353. normals.push(normal.x);
  28354. normals.push(normal.y);
  28355. normals.push(normal.z);
  28356. }
  28357. }
  28358. this.setIndices(indices);
  28359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28360. // Updating vertex buffers
  28361. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28362. kind = kinds[kindIndex];
  28363. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28364. }
  28365. // Updating submeshes
  28366. this.releaseSubMeshes();
  28367. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28368. var previousOne = previousSubmeshes[submeshIndex];
  28369. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28370. }
  28371. this.synchronizeInstances();
  28372. return this;
  28373. };
  28374. /**
  28375. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28376. * In other words, more vertices, no more indices and a single bigger VBO.
  28377. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28378. * Returns the Mesh.
  28379. */
  28380. Mesh.prototype.convertToUnIndexedMesh = function () {
  28381. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28382. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28383. var kinds = this.getVerticesDataKinds();
  28384. var vbs = {};
  28385. var data = {};
  28386. var newdata = {};
  28387. var kindIndex;
  28388. var kind;
  28389. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28390. kind = kinds[kindIndex];
  28391. var vertexBuffer = this.getVertexBuffer(kind);
  28392. vbs[kind] = vertexBuffer;
  28393. data[kind] = vbs[kind].getData();
  28394. newdata[kind] = [];
  28395. }
  28396. // Save previous submeshes
  28397. var previousSubmeshes = this.subMeshes.slice(0);
  28398. var indices = this.getIndices();
  28399. var totalIndices = this.getTotalIndices();
  28400. // Generating unique vertices per face
  28401. var index;
  28402. for (index = 0; index < totalIndices; index++) {
  28403. var vertexIndex = indices[index];
  28404. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28405. kind = kinds[kindIndex];
  28406. var stride = vbs[kind].getStrideSize();
  28407. for (var offset = 0; offset < stride; offset++) {
  28408. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28409. }
  28410. }
  28411. }
  28412. // Updating indices
  28413. for (index = 0; index < totalIndices; index += 3) {
  28414. indices[index] = index;
  28415. indices[index + 1] = index + 1;
  28416. indices[index + 2] = index + 2;
  28417. }
  28418. this.setIndices(indices);
  28419. // Updating vertex buffers
  28420. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28421. kind = kinds[kindIndex];
  28422. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28423. }
  28424. // Updating submeshes
  28425. this.releaseSubMeshes();
  28426. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28427. var previousOne = previousSubmeshes[submeshIndex];
  28428. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28429. }
  28430. this._unIndexed = true;
  28431. this.synchronizeInstances();
  28432. return this;
  28433. };
  28434. /**
  28435. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28436. * This method returns the Mesh.
  28437. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28438. */
  28439. Mesh.prototype.flipFaces = function (flipNormals) {
  28440. if (flipNormals === void 0) { flipNormals = false; }
  28441. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28442. var i;
  28443. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28444. for (i = 0; i < vertex_data.normals.length; i++) {
  28445. vertex_data.normals[i] *= -1;
  28446. }
  28447. }
  28448. if (vertex_data.indices) {
  28449. var temp;
  28450. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28451. // reassign indices
  28452. temp = vertex_data.indices[i + 1];
  28453. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28454. vertex_data.indices[i + 2] = temp;
  28455. }
  28456. }
  28457. vertex_data.applyToMesh(this);
  28458. return this;
  28459. };
  28460. // Instances
  28461. /**
  28462. * Creates a new InstancedMesh object from the mesh model.
  28463. * An instance shares the same properties and the same material than its model.
  28464. * Only these properties of each instance can then be set individually :
  28465. * - position
  28466. * - rotation
  28467. * - rotationQuaternion
  28468. * - setPivotMatrix
  28469. * - scaling
  28470. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28471. * Warning : this method is not supported for Line mesh and LineSystem
  28472. */
  28473. Mesh.prototype.createInstance = function (name) {
  28474. return new BABYLON.InstancedMesh(name, this);
  28475. };
  28476. /**
  28477. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28478. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28479. * This method returns the Mesh.
  28480. */
  28481. Mesh.prototype.synchronizeInstances = function () {
  28482. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28483. var instance = this.instances[instanceIndex];
  28484. instance._syncSubMeshes();
  28485. }
  28486. return this;
  28487. };
  28488. /**
  28489. * Simplify the mesh according to the given array of settings.
  28490. * Function will return immediately and will simplify async. It returns the Mesh.
  28491. * @param settings a collection of simplification settings.
  28492. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28493. * @param type the type of simplification to run.
  28494. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28495. */
  28496. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28497. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28498. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28499. this.getScene().simplificationQueue.addTask({
  28500. settings: settings,
  28501. parallelProcessing: parallelProcessing,
  28502. mesh: this,
  28503. simplificationType: simplificationType,
  28504. successCallback: successCallback
  28505. });
  28506. return this;
  28507. };
  28508. /**
  28509. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28510. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28511. * This should be used together with the simplification to avoid disappearing triangles.
  28512. * Returns the Mesh.
  28513. * @param successCallback an optional success callback to be called after the optimization finished.
  28514. */
  28515. Mesh.prototype.optimizeIndices = function (successCallback) {
  28516. var _this = this;
  28517. var indices = this.getIndices();
  28518. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28519. if (!positions || !indices) {
  28520. return this;
  28521. }
  28522. var vectorPositions = new Array();
  28523. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28524. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28525. }
  28526. var dupes = new Array();
  28527. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28528. var realPos = vectorPositions.length - 1 - iteration;
  28529. var testedPosition = vectorPositions[realPos];
  28530. for (var j = 0; j < realPos; ++j) {
  28531. var againstPosition = vectorPositions[j];
  28532. if (testedPosition.equals(againstPosition)) {
  28533. dupes[realPos] = j;
  28534. break;
  28535. }
  28536. }
  28537. }, function () {
  28538. for (var i = 0; i < indices.length; ++i) {
  28539. indices[i] = dupes[indices[i]] || indices[i];
  28540. }
  28541. //indices are now reordered
  28542. var originalSubMeshes = _this.subMeshes.slice(0);
  28543. _this.setIndices(indices);
  28544. _this.subMeshes = originalSubMeshes;
  28545. if (successCallback) {
  28546. successCallback(_this);
  28547. }
  28548. });
  28549. return this;
  28550. };
  28551. Mesh.prototype.serialize = function (serializationObject) {
  28552. serializationObject.name = this.name;
  28553. serializationObject.id = this.id;
  28554. serializationObject.type = this.getClassName();
  28555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28557. }
  28558. serializationObject.position = this.position.asArray();
  28559. if (this.rotationQuaternion) {
  28560. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28561. }
  28562. else if (this.rotation) {
  28563. serializationObject.rotation = this.rotation.asArray();
  28564. }
  28565. serializationObject.scaling = this.scaling.asArray();
  28566. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28567. serializationObject.isEnabled = this.isEnabled(false);
  28568. serializationObject.isVisible = this.isVisible;
  28569. serializationObject.infiniteDistance = this.infiniteDistance;
  28570. serializationObject.pickable = this.isPickable;
  28571. serializationObject.receiveShadows = this.receiveShadows;
  28572. serializationObject.billboardMode = this.billboardMode;
  28573. serializationObject.visibility = this.visibility;
  28574. serializationObject.checkCollisions = this.checkCollisions;
  28575. serializationObject.isBlocker = this.isBlocker;
  28576. // Parent
  28577. if (this.parent) {
  28578. serializationObject.parentId = this.parent.id;
  28579. }
  28580. // Geometry
  28581. serializationObject.isUnIndexed = this.isUnIndexed;
  28582. var geometry = this._geometry;
  28583. if (geometry) {
  28584. var geometryId = geometry.id;
  28585. serializationObject.geometryId = geometryId;
  28586. // SubMeshes
  28587. serializationObject.subMeshes = [];
  28588. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28589. var subMesh = this.subMeshes[subIndex];
  28590. serializationObject.subMeshes.push({
  28591. materialIndex: subMesh.materialIndex,
  28592. verticesStart: subMesh.verticesStart,
  28593. verticesCount: subMesh.verticesCount,
  28594. indexStart: subMesh.indexStart,
  28595. indexCount: subMesh.indexCount
  28596. });
  28597. }
  28598. }
  28599. // Material
  28600. if (this.material) {
  28601. serializationObject.materialId = this.material.id;
  28602. }
  28603. else {
  28604. this.material = null;
  28605. }
  28606. // Morph targets
  28607. if (this.morphTargetManager) {
  28608. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28609. }
  28610. // Skeleton
  28611. if (this.skeleton) {
  28612. serializationObject.skeletonId = this.skeleton.id;
  28613. }
  28614. // Physics
  28615. //TODO implement correct serialization for physics impostors.
  28616. var impostor = this.getPhysicsImpostor();
  28617. if (impostor) {
  28618. serializationObject.physicsMass = impostor.getParam("mass");
  28619. serializationObject.physicsFriction = impostor.getParam("friction");
  28620. serializationObject.physicsRestitution = impostor.getParam("mass");
  28621. serializationObject.physicsImpostor = impostor.type;
  28622. }
  28623. // Metadata
  28624. if (this.metadata) {
  28625. serializationObject.metadata = this.metadata;
  28626. }
  28627. // Instances
  28628. serializationObject.instances = [];
  28629. for (var index = 0; index < this.instances.length; index++) {
  28630. var instance = this.instances[index];
  28631. var serializationInstance = {
  28632. name: instance.name,
  28633. id: instance.id,
  28634. position: instance.position.asArray(),
  28635. scaling: instance.scaling.asArray()
  28636. };
  28637. if (instance.rotationQuaternion) {
  28638. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28639. }
  28640. else if (instance.rotation) {
  28641. serializationInstance.rotation = instance.rotation.asArray();
  28642. }
  28643. serializationObject.instances.push(serializationInstance);
  28644. // Animations
  28645. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28646. serializationInstance.ranges = instance.serializeAnimationRanges();
  28647. }
  28648. //
  28649. // Animations
  28650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28651. serializationObject.ranges = this.serializeAnimationRanges();
  28652. // Layer mask
  28653. serializationObject.layerMask = this.layerMask;
  28654. // Alpha
  28655. serializationObject.alphaIndex = this.alphaIndex;
  28656. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28657. // Overlay
  28658. serializationObject.overlayAlpha = this.overlayAlpha;
  28659. serializationObject.overlayColor = this.overlayColor.asArray();
  28660. serializationObject.renderOverlay = this.renderOverlay;
  28661. // Fog
  28662. serializationObject.applyFog = this.applyFog;
  28663. // Action Manager
  28664. if (this.actionManager) {
  28665. serializationObject.actions = this.actionManager.serialize(this.name);
  28666. }
  28667. };
  28668. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28669. if (!this.geometry) {
  28670. return;
  28671. }
  28672. this._markSubMeshesAsAttributesDirty();
  28673. var morphTargetManager = this._morphTargetManager;
  28674. if (morphTargetManager && morphTargetManager.vertexCount) {
  28675. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28676. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28677. this.morphTargetManager = null;
  28678. return;
  28679. }
  28680. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28681. var morphTarget = morphTargetManager.getActiveTarget(index);
  28682. var positions = morphTarget.getPositions();
  28683. if (!positions) {
  28684. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28685. return;
  28686. }
  28687. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28688. var normals = morphTarget.getNormals();
  28689. if (normals) {
  28690. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28691. }
  28692. var tangents = morphTarget.getTangents();
  28693. if (tangents) {
  28694. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28695. }
  28696. }
  28697. }
  28698. else {
  28699. var index = 0;
  28700. // Positions
  28701. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28702. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28703. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28704. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28705. }
  28706. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28707. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28708. }
  28709. index++;
  28710. }
  28711. }
  28712. };
  28713. // Statics
  28714. /**
  28715. * Returns a new Mesh object parsed from the source provided.
  28716. * The parameter `parsedMesh` is the source.
  28717. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28718. */
  28719. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28720. var mesh;
  28721. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28722. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28723. }
  28724. else {
  28725. mesh = new Mesh(parsedMesh.name, scene);
  28726. }
  28727. mesh.id = parsedMesh.id;
  28728. if (BABYLON.Tags) {
  28729. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28730. }
  28731. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28732. if (parsedMesh.metadata !== undefined) {
  28733. mesh.metadata = parsedMesh.metadata;
  28734. }
  28735. if (parsedMesh.rotationQuaternion) {
  28736. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28737. }
  28738. else if (parsedMesh.rotation) {
  28739. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28740. }
  28741. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28742. if (parsedMesh.localMatrix) {
  28743. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28744. }
  28745. else if (parsedMesh.pivotMatrix) {
  28746. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28747. }
  28748. mesh.setEnabled(parsedMesh.isEnabled);
  28749. mesh.isVisible = parsedMesh.isVisible;
  28750. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28751. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28752. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28753. if (parsedMesh.applyFog !== undefined) {
  28754. mesh.applyFog = parsedMesh.applyFog;
  28755. }
  28756. if (parsedMesh.pickable !== undefined) {
  28757. mesh.isPickable = parsedMesh.pickable;
  28758. }
  28759. if (parsedMesh.alphaIndex !== undefined) {
  28760. mesh.alphaIndex = parsedMesh.alphaIndex;
  28761. }
  28762. mesh.receiveShadows = parsedMesh.receiveShadows;
  28763. mesh.billboardMode = parsedMesh.billboardMode;
  28764. if (parsedMesh.visibility !== undefined) {
  28765. mesh.visibility = parsedMesh.visibility;
  28766. }
  28767. mesh.checkCollisions = parsedMesh.checkCollisions;
  28768. if (parsedMesh.isBlocker !== undefined) {
  28769. mesh.isBlocker = parsedMesh.isBlocker;
  28770. }
  28771. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28772. // freezeWorldMatrix
  28773. if (parsedMesh.freezeWorldMatrix) {
  28774. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28775. }
  28776. // Parent
  28777. if (parsedMesh.parentId) {
  28778. mesh._waitingParentId = parsedMesh.parentId;
  28779. }
  28780. // Actions
  28781. if (parsedMesh.actions !== undefined) {
  28782. mesh._waitingActions = parsedMesh.actions;
  28783. }
  28784. // Overlay
  28785. if (parsedMesh.overlayAlpha !== undefined) {
  28786. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28787. }
  28788. if (parsedMesh.overlayColor !== undefined) {
  28789. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28790. }
  28791. if (parsedMesh.renderOverlay !== undefined) {
  28792. mesh.renderOverlay = parsedMesh.renderOverlay;
  28793. }
  28794. // Geometry
  28795. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28796. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28797. if (parsedMesh.delayLoadingFile) {
  28798. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28799. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28800. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28801. if (parsedMesh._binaryInfo) {
  28802. mesh._binaryInfo = parsedMesh._binaryInfo;
  28803. }
  28804. mesh._delayInfo = [];
  28805. if (parsedMesh.hasUVs) {
  28806. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28807. }
  28808. if (parsedMesh.hasUVs2) {
  28809. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28810. }
  28811. if (parsedMesh.hasUVs3) {
  28812. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28813. }
  28814. if (parsedMesh.hasUVs4) {
  28815. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28816. }
  28817. if (parsedMesh.hasUVs5) {
  28818. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28819. }
  28820. if (parsedMesh.hasUVs6) {
  28821. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28822. }
  28823. if (parsedMesh.hasColors) {
  28824. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28825. }
  28826. if (parsedMesh.hasMatricesIndices) {
  28827. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28828. }
  28829. if (parsedMesh.hasMatricesWeights) {
  28830. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28831. }
  28832. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28833. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28834. mesh._checkDelayState();
  28835. }
  28836. }
  28837. else {
  28838. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28839. }
  28840. // Material
  28841. if (parsedMesh.materialId) {
  28842. mesh.setMaterialByID(parsedMesh.materialId);
  28843. }
  28844. else {
  28845. mesh.material = null;
  28846. }
  28847. // Morph targets
  28848. if (parsedMesh.morphTargetManagerId > -1) {
  28849. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28850. }
  28851. // Skeleton
  28852. if (parsedMesh.skeletonId > -1) {
  28853. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28854. if (parsedMesh.numBoneInfluencers) {
  28855. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28856. }
  28857. }
  28858. // Animations
  28859. if (parsedMesh.animations) {
  28860. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28861. var parsedAnimation = parsedMesh.animations[animationIndex];
  28862. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28863. }
  28864. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28865. }
  28866. if (parsedMesh.autoAnimate) {
  28867. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28868. }
  28869. // Layer Mask
  28870. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28871. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28872. }
  28873. else {
  28874. mesh.layerMask = 0x0FFFFFFF;
  28875. }
  28876. // Physics
  28877. if (parsedMesh.physicsImpostor) {
  28878. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28879. mass: parsedMesh.physicsMass,
  28880. friction: parsedMesh.physicsFriction,
  28881. restitution: parsedMesh.physicsRestitution
  28882. }, scene);
  28883. }
  28884. // Instances
  28885. if (parsedMesh.instances) {
  28886. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28887. var parsedInstance = parsedMesh.instances[index];
  28888. var instance = mesh.createInstance(parsedInstance.name);
  28889. if (parsedInstance.id) {
  28890. instance.id = parsedInstance.id;
  28891. }
  28892. if (BABYLON.Tags) {
  28893. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28894. }
  28895. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28896. if (parsedInstance.parentId) {
  28897. instance._waitingParentId = parsedInstance.parentId;
  28898. }
  28899. if (parsedInstance.rotationQuaternion) {
  28900. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28901. }
  28902. else if (parsedInstance.rotation) {
  28903. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28904. }
  28905. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28906. instance.checkCollisions = mesh.checkCollisions;
  28907. if (parsedMesh.animations) {
  28908. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28909. parsedAnimation = parsedMesh.animations[animationIndex];
  28910. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28911. }
  28912. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28913. }
  28914. }
  28915. }
  28916. return mesh;
  28917. };
  28918. /**
  28919. * Creates a ribbon mesh.
  28920. * Please consider using the same method from the MeshBuilder class instead.
  28921. * 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.
  28922. *
  28923. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28924. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28925. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28926. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28927. * 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.
  28928. * 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.
  28929. * 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
  28930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28933. */
  28934. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28935. if (closeArray === void 0) { closeArray = false; }
  28936. if (updatable === void 0) { updatable = false; }
  28937. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28938. pathArray: pathArray,
  28939. closeArray: closeArray,
  28940. closePath: closePath,
  28941. offset: offset,
  28942. updatable: updatable,
  28943. sideOrientation: sideOrientation,
  28944. instance: instance
  28945. }, scene);
  28946. };
  28947. /**
  28948. * Creates a plane polygonal mesh. By default, this is a disc.
  28949. * Please consider using the same method from the MeshBuilder class instead.
  28950. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28951. * 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.
  28952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28955. */
  28956. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28957. if (scene === void 0) { scene = null; }
  28958. var options = {
  28959. radius: radius,
  28960. tessellation: tessellation,
  28961. sideOrientation: sideOrientation,
  28962. updatable: updatable
  28963. };
  28964. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28965. };
  28966. /**
  28967. * Creates a box mesh.
  28968. * Please consider using the same method from the MeshBuilder class instead.
  28969. * The parameter `size` sets the size (float) of each box side (default 1).
  28970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28973. */
  28974. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28975. if (scene === void 0) { scene = null; }
  28976. var options = {
  28977. size: size,
  28978. sideOrientation: sideOrientation,
  28979. updatable: updatable
  28980. };
  28981. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28982. };
  28983. /**
  28984. * Creates a sphere mesh.
  28985. * Please consider using the same method from the MeshBuilder class instead.
  28986. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28987. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28991. */
  28992. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28993. var options = {
  28994. segments: segments,
  28995. diameterX: diameter,
  28996. diameterY: diameter,
  28997. diameterZ: diameter,
  28998. sideOrientation: sideOrientation,
  28999. updatable: updatable
  29000. };
  29001. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29002. };
  29003. /**
  29004. * Creates a cylinder or a cone mesh.
  29005. * Please consider using the same method from the MeshBuilder class instead.
  29006. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29007. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29008. * 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.
  29009. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29010. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29014. */
  29015. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29016. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29017. if (scene !== undefined) {
  29018. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29019. updatable = scene;
  29020. }
  29021. scene = subdivisions;
  29022. subdivisions = 1;
  29023. }
  29024. var options = {
  29025. height: height,
  29026. diameterTop: diameterTop,
  29027. diameterBottom: diameterBottom,
  29028. tessellation: tessellation,
  29029. subdivisions: subdivisions,
  29030. sideOrientation: sideOrientation,
  29031. updatable: updatable
  29032. };
  29033. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29034. };
  29035. // Torus (Code from SharpDX.org)
  29036. /**
  29037. * Creates a torus mesh.
  29038. * Please consider using the same method from the MeshBuilder class instead.
  29039. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29040. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29041. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29045. */
  29046. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29047. var options = {
  29048. diameter: diameter,
  29049. thickness: thickness,
  29050. tessellation: tessellation,
  29051. sideOrientation: sideOrientation,
  29052. updatable: updatable
  29053. };
  29054. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29055. };
  29056. /**
  29057. * Creates a torus knot mesh.
  29058. * Please consider using the same method from the MeshBuilder class instead.
  29059. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29060. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29061. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29062. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29066. */
  29067. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29068. var options = {
  29069. radius: radius,
  29070. tube: tube,
  29071. radialSegments: radialSegments,
  29072. tubularSegments: tubularSegments,
  29073. p: p,
  29074. q: q,
  29075. sideOrientation: sideOrientation,
  29076. updatable: updatable
  29077. };
  29078. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29079. };
  29080. /**
  29081. * Creates a line mesh.
  29082. * Please consider using the same method from the MeshBuilder class instead.
  29083. * 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.
  29084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29085. * The parameter `points` is an array successive Vector3.
  29086. * 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
  29087. * When updating an instance, remember that only point positions can change, not the number of points.
  29088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29089. */
  29090. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29091. if (scene === void 0) { scene = null; }
  29092. if (updatable === void 0) { updatable = false; }
  29093. if (instance === void 0) { instance = null; }
  29094. var options = {
  29095. points: points,
  29096. updatable: updatable,
  29097. instance: instance
  29098. };
  29099. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29100. };
  29101. /**
  29102. * Creates a dashed line mesh.
  29103. * Please consider using the same method from the MeshBuilder class instead.
  29104. * 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.
  29105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29106. * The parameter `points` is an array successive Vector3.
  29107. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29108. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29109. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29110. * 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
  29111. * When updating an instance, remember that only point positions can change, not the number of points.
  29112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29113. */
  29114. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29115. if (scene === void 0) { scene = null; }
  29116. var options = {
  29117. points: points,
  29118. dashSize: dashSize,
  29119. gapSize: gapSize,
  29120. dashNb: dashNb,
  29121. updatable: updatable,
  29122. instance: instance
  29123. };
  29124. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29125. };
  29126. /**
  29127. * Creates a polygon mesh.
  29128. * Please consider using the same method from the MeshBuilder class instead.
  29129. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29130. * 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.
  29131. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29133. * Remember you can only change the shape positions, not their number when updating a polygon.
  29134. */
  29135. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29136. var options = {
  29137. shape: shape,
  29138. holes: holes,
  29139. updatable: updatable,
  29140. sideOrientation: sideOrientation
  29141. };
  29142. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29143. };
  29144. /**
  29145. * Creates an extruded polygon mesh, with depth in the Y direction.
  29146. * Please consider using the same method from the MeshBuilder class instead.
  29147. */
  29148. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29149. var options = {
  29150. shape: shape,
  29151. holes: holes,
  29152. depth: depth,
  29153. updatable: updatable,
  29154. sideOrientation: sideOrientation
  29155. };
  29156. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29157. };
  29158. /**
  29159. * Creates an extruded shape mesh.
  29160. * 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.
  29161. * Please consider using the same method from the MeshBuilder class instead.
  29162. *
  29163. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29164. * 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
  29165. * extruded along the Z axis.
  29166. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29167. * 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.
  29168. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29169. * 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
  29170. * 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
  29171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29175. */
  29176. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29177. if (scene === void 0) { scene = null; }
  29178. var options = {
  29179. shape: shape,
  29180. path: path,
  29181. scale: scale,
  29182. rotation: rotation,
  29183. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29184. sideOrientation: sideOrientation,
  29185. instance: instance,
  29186. updatable: updatable
  29187. };
  29188. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29189. };
  29190. /**
  29191. * Creates an custom extruded shape mesh.
  29192. * 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.
  29193. * Please consider using the same method from the MeshBuilder class instead.
  29194. *
  29195. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29196. * 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
  29197. * extruded along the Z axis.
  29198. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29199. * 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
  29200. * and the distance of this point from the begining of the path :
  29201. * ```javascript
  29202. * var rotationFunction = function(i, distance) {
  29203. * // do things
  29204. * return rotationValue; }
  29205. * ```
  29206. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29207. * 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
  29208. * and the distance of this point from the begining of the path :
  29209. * ```javascript
  29210. * var scaleFunction = function(i, distance) {
  29211. * // do things
  29212. * return scaleValue;}
  29213. * ```
  29214. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29215. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29216. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29217. * 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
  29218. * 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
  29219. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29221. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29223. */
  29224. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29225. var options = {
  29226. shape: shape,
  29227. path: path,
  29228. scaleFunction: scaleFunction,
  29229. rotationFunction: rotationFunction,
  29230. ribbonCloseArray: ribbonCloseArray,
  29231. ribbonClosePath: ribbonClosePath,
  29232. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29233. sideOrientation: sideOrientation,
  29234. instance: instance,
  29235. updatable: updatable
  29236. };
  29237. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29238. };
  29239. /**
  29240. * Creates lathe mesh.
  29241. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29242. * Please consider using the same method from the MeshBuilder class instead.
  29243. * 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
  29244. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29245. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29246. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29250. */
  29251. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29252. var options = {
  29253. shape: shape,
  29254. radius: radius,
  29255. tessellation: tessellation,
  29256. sideOrientation: sideOrientation,
  29257. updatable: updatable
  29258. };
  29259. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29260. };
  29261. /**
  29262. * Creates a plane mesh.
  29263. * Please consider using the same method from the MeshBuilder class instead.
  29264. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29268. */
  29269. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29270. var options = {
  29271. size: size,
  29272. width: size,
  29273. height: size,
  29274. sideOrientation: sideOrientation,
  29275. updatable: updatable
  29276. };
  29277. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29278. };
  29279. /**
  29280. * Creates a ground mesh.
  29281. * Please consider using the same method from the MeshBuilder class instead.
  29282. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29283. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29285. */
  29286. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29287. var options = {
  29288. width: width,
  29289. height: height,
  29290. subdivisions: subdivisions,
  29291. updatable: updatable
  29292. };
  29293. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29294. };
  29295. /**
  29296. * Creates a tiled ground mesh.
  29297. * Please consider using the same method from the MeshBuilder class instead.
  29298. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29299. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29300. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29301. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29302. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29303. * numbers of subdivisions on the ground width and height of each tile.
  29304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29305. */
  29306. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29307. var options = {
  29308. xmin: xmin,
  29309. zmin: zmin,
  29310. xmax: xmax,
  29311. zmax: zmax,
  29312. subdivisions: subdivisions,
  29313. precision: precision,
  29314. updatable: updatable
  29315. };
  29316. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29317. };
  29318. /**
  29319. * Creates a ground mesh from a height map.
  29320. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29321. * Please consider using the same method from the MeshBuilder class instead.
  29322. * The parameter `url` sets the URL of the height map image resource.
  29323. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29324. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29325. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29326. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29327. * 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).
  29328. * This function is passed the newly built mesh :
  29329. * ```javascript
  29330. * function(mesh) { // do things
  29331. * return; }
  29332. * ```
  29333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29334. */
  29335. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29336. var options = {
  29337. width: width,
  29338. height: height,
  29339. subdivisions: subdivisions,
  29340. minHeight: minHeight,
  29341. maxHeight: maxHeight,
  29342. updatable: updatable,
  29343. onReady: onReady
  29344. };
  29345. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29346. };
  29347. /**
  29348. * Creates a tube mesh.
  29349. * 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.
  29350. * Please consider using the same method from the MeshBuilder class instead.
  29351. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29352. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29353. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29354. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29355. * 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.
  29356. * It must return a radius value (positive float) :
  29357. * ```javascript
  29358. * var radiusFunction = function(i, distance) {
  29359. * // do things
  29360. * return radius; }
  29361. * ```
  29362. * 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
  29363. * 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
  29364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29367. */
  29368. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29369. var options = {
  29370. path: path,
  29371. radius: radius,
  29372. tessellation: tessellation,
  29373. radiusFunction: radiusFunction,
  29374. arc: 1,
  29375. cap: cap,
  29376. updatable: updatable,
  29377. sideOrientation: sideOrientation,
  29378. instance: instance
  29379. };
  29380. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29381. };
  29382. /**
  29383. * Creates a polyhedron mesh.
  29384. * Please consider using the same method from the MeshBuilder class instead.
  29385. * 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
  29386. * to choose the wanted type.
  29387. * The parameter `size` (positive float, default 1) sets the polygon size.
  29388. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29389. * 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`.
  29390. * 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
  29391. * 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)`).
  29392. * 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
  29393. * 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.
  29394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29397. */
  29398. Mesh.CreatePolyhedron = function (name, options, scene) {
  29399. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29400. };
  29401. /**
  29402. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29403. * Please consider using the same method from the MeshBuilder class instead.
  29404. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29405. * 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`).
  29406. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29407. * 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.
  29408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29411. */
  29412. Mesh.CreateIcoSphere = function (name, options, scene) {
  29413. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29414. };
  29415. /**
  29416. * Creates a decal mesh.
  29417. * Please consider using the same method from the MeshBuilder class instead.
  29418. * 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.
  29419. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29420. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29421. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29422. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29423. */
  29424. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29425. var options = {
  29426. position: position,
  29427. normal: normal,
  29428. size: size,
  29429. angle: angle
  29430. };
  29431. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29432. };
  29433. // Skeletons
  29434. /**
  29435. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29436. */
  29437. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29438. if (!this._sourcePositions) {
  29439. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29440. if (!source) {
  29441. return this._sourcePositions;
  29442. }
  29443. this._sourcePositions = new Float32Array(source);
  29444. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29445. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29446. }
  29447. }
  29448. return this._sourcePositions;
  29449. };
  29450. /**
  29451. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29452. */
  29453. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29454. if (!this._sourceNormals) {
  29455. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29456. if (!source) {
  29457. return this._sourceNormals;
  29458. }
  29459. this._sourceNormals = new Float32Array(source);
  29460. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29461. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29462. }
  29463. }
  29464. return this._sourceNormals;
  29465. };
  29466. /**
  29467. * Updates the vertex buffer by applying transformation from the bones.
  29468. * Returns the Mesh.
  29469. *
  29470. * @param {skeleton} skeleton to apply
  29471. */
  29472. Mesh.prototype.applySkeleton = function (skeleton) {
  29473. if (!this.geometry) {
  29474. return this;
  29475. }
  29476. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29477. return this;
  29478. }
  29479. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29480. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29481. return this;
  29482. }
  29483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29484. return this;
  29485. }
  29486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29487. return this;
  29488. }
  29489. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29490. return this;
  29491. }
  29492. if (!this._sourcePositions) {
  29493. var submeshes = this.subMeshes.slice();
  29494. this.setPositionsForCPUSkinning();
  29495. this.subMeshes = submeshes;
  29496. }
  29497. if (!this._sourceNormals) {
  29498. this.setNormalsForCPUSkinning();
  29499. }
  29500. // positionsData checks for not being Float32Array will only pass at most once
  29501. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29502. if (!positionsData) {
  29503. return this;
  29504. }
  29505. if (!(positionsData instanceof Float32Array)) {
  29506. positionsData = new Float32Array(positionsData);
  29507. }
  29508. // normalsData checks for not being Float32Array will only pass at most once
  29509. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29510. if (!normalsData) {
  29511. return this;
  29512. }
  29513. if (!(normalsData instanceof Float32Array)) {
  29514. normalsData = new Float32Array(normalsData);
  29515. }
  29516. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29517. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29518. if (!matricesWeightsData || !matricesIndicesData) {
  29519. return this;
  29520. }
  29521. var needExtras = this.numBoneInfluencers > 4;
  29522. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29523. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29524. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29525. var tempVector3 = BABYLON.Vector3.Zero();
  29526. var finalMatrix = new BABYLON.Matrix();
  29527. var tempMatrix = new BABYLON.Matrix();
  29528. var matWeightIdx = 0;
  29529. var inf;
  29530. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29531. var weight;
  29532. for (inf = 0; inf < 4; inf++) {
  29533. weight = matricesWeightsData[matWeightIdx + inf];
  29534. if (weight > 0) {
  29535. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29536. finalMatrix.addToSelf(tempMatrix);
  29537. }
  29538. else
  29539. break;
  29540. }
  29541. if (needExtras) {
  29542. for (inf = 0; inf < 4; inf++) {
  29543. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29544. if (weight > 0) {
  29545. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29546. finalMatrix.addToSelf(tempMatrix);
  29547. }
  29548. else
  29549. break;
  29550. }
  29551. }
  29552. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29553. tempVector3.toArray(positionsData, index);
  29554. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29555. tempVector3.toArray(normalsData, index);
  29556. finalMatrix.reset();
  29557. }
  29558. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29559. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29560. return this;
  29561. };
  29562. // Tools
  29563. /**
  29564. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29565. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29566. */
  29567. Mesh.MinMax = function (meshes) {
  29568. var minVector = null;
  29569. var maxVector = null;
  29570. meshes.forEach(function (mesh, index, array) {
  29571. var boundingInfo = mesh.getBoundingInfo();
  29572. var boundingBox = boundingInfo.boundingBox;
  29573. if (!minVector || !maxVector) {
  29574. minVector = boundingBox.minimumWorld;
  29575. maxVector = boundingBox.maximumWorld;
  29576. }
  29577. else {
  29578. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29579. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29580. }
  29581. });
  29582. if (!minVector || !maxVector) {
  29583. return {
  29584. min: BABYLON.Vector3.Zero(),
  29585. max: BABYLON.Vector3.Zero()
  29586. };
  29587. }
  29588. return {
  29589. min: minVector,
  29590. max: maxVector
  29591. };
  29592. };
  29593. /**
  29594. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29595. */
  29596. Mesh.Center = function (meshesOrMinMaxVector) {
  29597. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29599. };
  29600. /**
  29601. * Merge the array of meshes into a single mesh for performance reasons.
  29602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29606. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29607. */
  29608. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29609. if (disposeSource === void 0) { disposeSource = true; }
  29610. var index;
  29611. if (!allow32BitsIndices) {
  29612. var totalVertices = 0;
  29613. // Counting vertices
  29614. for (index = 0; index < meshes.length; index++) {
  29615. if (meshes[index]) {
  29616. totalVertices += meshes[index].getTotalVertices();
  29617. if (totalVertices > 65536) {
  29618. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29619. return null;
  29620. }
  29621. }
  29622. }
  29623. }
  29624. // Merge
  29625. var vertexData = null;
  29626. var otherVertexData;
  29627. var indiceArray = new Array();
  29628. var source = null;
  29629. for (index = 0; index < meshes.length; index++) {
  29630. if (meshes[index]) {
  29631. meshes[index].computeWorldMatrix(true);
  29632. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29633. otherVertexData.transform(meshes[index].getWorldMatrix());
  29634. if (vertexData) {
  29635. vertexData.merge(otherVertexData);
  29636. }
  29637. else {
  29638. vertexData = otherVertexData;
  29639. source = meshes[index];
  29640. }
  29641. if (subdivideWithSubMeshes) {
  29642. indiceArray.push(meshes[index].getTotalIndices());
  29643. }
  29644. }
  29645. }
  29646. source = source;
  29647. if (!meshSubclass) {
  29648. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29649. }
  29650. vertexData.applyToMesh(meshSubclass);
  29651. // Setting properties
  29652. meshSubclass.material = source.material;
  29653. meshSubclass.checkCollisions = source.checkCollisions;
  29654. // Cleaning
  29655. if (disposeSource) {
  29656. for (index = 0; index < meshes.length; index++) {
  29657. if (meshes[index]) {
  29658. meshes[index].dispose();
  29659. }
  29660. }
  29661. }
  29662. // Subdivide
  29663. if (subdivideWithSubMeshes) {
  29664. //-- Suppresions du submesh global
  29665. meshSubclass.releaseSubMeshes();
  29666. index = 0;
  29667. var offset = 0;
  29668. //-- aplique la subdivision en fonction du tableau d'indices
  29669. while (index < indiceArray.length) {
  29670. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29671. offset += indiceArray[index];
  29672. index++;
  29673. }
  29674. }
  29675. return meshSubclass;
  29676. };
  29677. // Consts
  29678. Mesh._FRONTSIDE = 0;
  29679. Mesh._BACKSIDE = 1;
  29680. Mesh._DOUBLESIDE = 2;
  29681. Mesh._DEFAULTSIDE = 0;
  29682. Mesh._NO_CAP = 0;
  29683. Mesh._CAP_START = 1;
  29684. Mesh._CAP_END = 2;
  29685. Mesh._CAP_ALL = 3;
  29686. return Mesh;
  29687. }(BABYLON.AbstractMesh));
  29688. BABYLON.Mesh = Mesh;
  29689. })(BABYLON || (BABYLON = {}));
  29690. //# sourceMappingURL=babylon.mesh.js.map
  29691. var BABYLON;
  29692. (function (BABYLON) {
  29693. var BaseSubMesh = /** @class */ (function () {
  29694. function BaseSubMesh() {
  29695. }
  29696. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29697. get: function () {
  29698. return this._materialEffect;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29704. if (defines === void 0) { defines = null; }
  29705. if (this._materialEffect === effect) {
  29706. if (!effect) {
  29707. this._materialDefines = null;
  29708. }
  29709. return;
  29710. }
  29711. this._materialDefines = defines;
  29712. this._materialEffect = effect;
  29713. };
  29714. return BaseSubMesh;
  29715. }());
  29716. BABYLON.BaseSubMesh = BaseSubMesh;
  29717. var SubMesh = /** @class */ (function (_super) {
  29718. __extends(SubMesh, _super);
  29719. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29720. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29721. var _this = _super.call(this) || this;
  29722. _this.materialIndex = materialIndex;
  29723. _this.verticesStart = verticesStart;
  29724. _this.verticesCount = verticesCount;
  29725. _this.indexStart = indexStart;
  29726. _this.indexCount = indexCount;
  29727. _this._renderId = 0;
  29728. _this._mesh = mesh;
  29729. _this._renderingMesh = renderingMesh || mesh;
  29730. mesh.subMeshes.push(_this);
  29731. _this._trianglePlanes = [];
  29732. _this._id = mesh.subMeshes.length - 1;
  29733. if (createBoundingBox) {
  29734. _this.refreshBoundingInfo();
  29735. mesh.computeWorldMatrix(true);
  29736. }
  29737. return _this;
  29738. }
  29739. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29741. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29742. };
  29743. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29744. get: function () {
  29745. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29746. },
  29747. enumerable: true,
  29748. configurable: true
  29749. });
  29750. /**
  29751. * Returns the submesh BoudingInfo object.
  29752. */
  29753. SubMesh.prototype.getBoundingInfo = function () {
  29754. if (this.IsGlobal) {
  29755. return this._mesh.getBoundingInfo();
  29756. }
  29757. return this._boundingInfo;
  29758. };
  29759. /**
  29760. * Sets the submesh BoundingInfo.
  29761. * Return the SubMesh.
  29762. */
  29763. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29764. this._boundingInfo = boundingInfo;
  29765. return this;
  29766. };
  29767. /**
  29768. * Returns the mesh of the current submesh.
  29769. */
  29770. SubMesh.prototype.getMesh = function () {
  29771. return this._mesh;
  29772. };
  29773. /**
  29774. * Returns the rendering mesh of the submesh.
  29775. */
  29776. SubMesh.prototype.getRenderingMesh = function () {
  29777. return this._renderingMesh;
  29778. };
  29779. /**
  29780. * Returns the submesh material.
  29781. */
  29782. SubMesh.prototype.getMaterial = function () {
  29783. var rootMaterial = this._renderingMesh.material;
  29784. if (rootMaterial === null || rootMaterial === undefined) {
  29785. return this._mesh.getScene().defaultMaterial;
  29786. }
  29787. else if (rootMaterial.getSubMaterial) {
  29788. var multiMaterial = rootMaterial;
  29789. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29790. if (this._currentMaterial !== effectiveMaterial) {
  29791. this._currentMaterial = effectiveMaterial;
  29792. this._materialDefines = null;
  29793. }
  29794. return effectiveMaterial;
  29795. }
  29796. return rootMaterial;
  29797. };
  29798. // Methods
  29799. /**
  29800. * Sets a new updated BoundingInfo object to the submesh.
  29801. * Returns the SubMesh.
  29802. */
  29803. SubMesh.prototype.refreshBoundingInfo = function () {
  29804. this._lastColliderWorldVertices = null;
  29805. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29806. return this;
  29807. }
  29808. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29809. if (!data) {
  29810. this._boundingInfo = this._mesh.getBoundingInfo();
  29811. return this;
  29812. }
  29813. var indices = this._renderingMesh.getIndices();
  29814. var extend;
  29815. //is this the only submesh?
  29816. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29817. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29818. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29819. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29820. }
  29821. else {
  29822. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29823. }
  29824. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29825. return this;
  29826. };
  29827. SubMesh.prototype._checkCollision = function (collider) {
  29828. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29829. return boundingInfo._checkCollision(collider);
  29830. };
  29831. /**
  29832. * Updates the submesh BoundingInfo.
  29833. * Returns the Submesh.
  29834. */
  29835. SubMesh.prototype.updateBoundingInfo = function (world) {
  29836. var boundingInfo = this.getBoundingInfo();
  29837. if (!boundingInfo) {
  29838. this.refreshBoundingInfo();
  29839. boundingInfo = this.getBoundingInfo();
  29840. }
  29841. boundingInfo.update(world);
  29842. return this;
  29843. };
  29844. /**
  29845. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29846. * Boolean returned.
  29847. */
  29848. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29849. var boundingInfo = this.getBoundingInfo();
  29850. if (!boundingInfo) {
  29851. return false;
  29852. }
  29853. return boundingInfo.isInFrustum(frustumPlanes);
  29854. };
  29855. /**
  29856. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29857. * Boolean returned.
  29858. */
  29859. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29860. var boundingInfo = this.getBoundingInfo();
  29861. if (!boundingInfo) {
  29862. return false;
  29863. }
  29864. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29865. };
  29866. /**
  29867. * Renders the submesh.
  29868. * Returns it.
  29869. */
  29870. SubMesh.prototype.render = function (enableAlphaMode) {
  29871. this._renderingMesh.render(this, enableAlphaMode);
  29872. return this;
  29873. };
  29874. /**
  29875. * Returns a new Index Buffer.
  29876. * Type returned : WebGLBuffer.
  29877. */
  29878. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29879. if (!this._linesIndexBuffer) {
  29880. var linesIndices = [];
  29881. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29882. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29883. }
  29884. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29885. this.linesIndexCount = linesIndices.length;
  29886. }
  29887. return this._linesIndexBuffer;
  29888. };
  29889. /**
  29890. * True is the passed Ray intersects the submesh bounding box.
  29891. * Boolean returned.
  29892. */
  29893. SubMesh.prototype.canIntersects = function (ray) {
  29894. var boundingInfo = this.getBoundingInfo();
  29895. if (!boundingInfo) {
  29896. return false;
  29897. }
  29898. return ray.intersectsBox(boundingInfo.boundingBox);
  29899. };
  29900. /**
  29901. * Returns an object IntersectionInfo.
  29902. */
  29903. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29904. var intersectInfo = null;
  29905. // LineMesh first as it's also a Mesh...
  29906. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29907. var lineMesh = this._mesh;
  29908. // Line test
  29909. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29910. var p0 = positions[indices[index]];
  29911. var p1 = positions[indices[index + 1]];
  29912. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29913. if (length < 0) {
  29914. continue;
  29915. }
  29916. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29917. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29918. if (fastCheck) {
  29919. break;
  29920. }
  29921. }
  29922. }
  29923. }
  29924. else {
  29925. // Triangles test
  29926. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29927. var p0 = positions[indices[index]];
  29928. var p1 = positions[indices[index + 1]];
  29929. var p2 = positions[indices[index + 2]];
  29930. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29931. if (currentIntersectInfo) {
  29932. if (currentIntersectInfo.distance < 0) {
  29933. continue;
  29934. }
  29935. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29936. intersectInfo = currentIntersectInfo;
  29937. intersectInfo.faceId = index / 3;
  29938. if (fastCheck) {
  29939. break;
  29940. }
  29941. }
  29942. }
  29943. }
  29944. }
  29945. return intersectInfo;
  29946. };
  29947. SubMesh.prototype._rebuild = function () {
  29948. if (this._linesIndexBuffer) {
  29949. this._linesIndexBuffer = null;
  29950. }
  29951. };
  29952. // Clone
  29953. /**
  29954. * Creates a new Submesh from the passed Mesh.
  29955. */
  29956. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29957. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29958. if (!this.IsGlobal) {
  29959. var boundingInfo = this.getBoundingInfo();
  29960. if (!boundingInfo) {
  29961. return result;
  29962. }
  29963. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29964. }
  29965. return result;
  29966. };
  29967. // Dispose
  29968. /**
  29969. * Disposes the Submesh.
  29970. * Returns nothing.
  29971. */
  29972. SubMesh.prototype.dispose = function () {
  29973. if (this._linesIndexBuffer) {
  29974. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29975. this._linesIndexBuffer = null;
  29976. }
  29977. // Remove from mesh
  29978. var index = this._mesh.subMeshes.indexOf(this);
  29979. this._mesh.subMeshes.splice(index, 1);
  29980. };
  29981. // Statics
  29982. /**
  29983. * Creates a new Submesh from the passed parameters :
  29984. * - materialIndex (integer) : the index of the main mesh material.
  29985. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29986. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29987. * - mesh (Mesh) : the main mesh to create the submesh from.
  29988. * - renderingMesh (optional Mesh) : rendering mesh.
  29989. */
  29990. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29991. var minVertexIndex = Number.MAX_VALUE;
  29992. var maxVertexIndex = -Number.MAX_VALUE;
  29993. renderingMesh = (renderingMesh || mesh);
  29994. var indices = renderingMesh.getIndices();
  29995. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29996. var vertexIndex = indices[index];
  29997. if (vertexIndex < minVertexIndex)
  29998. minVertexIndex = vertexIndex;
  29999. if (vertexIndex > maxVertexIndex)
  30000. maxVertexIndex = vertexIndex;
  30001. }
  30002. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30003. };
  30004. return SubMesh;
  30005. }(BaseSubMesh));
  30006. BABYLON.SubMesh = SubMesh;
  30007. })(BABYLON || (BABYLON = {}));
  30008. //# sourceMappingURL=babylon.subMesh.js.map
  30009. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30010. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30011. s = arguments[i];
  30012. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30013. t[p] = s[p];
  30014. }
  30015. return t;
  30016. };
  30017. var BABYLON;
  30018. (function (BABYLON) {
  30019. /**
  30020. * Manages the defines for the Material.
  30021. */
  30022. var MaterialDefines = /** @class */ (function () {
  30023. function MaterialDefines() {
  30024. this._isDirty = true;
  30025. this._areLightsDirty = true;
  30026. this._areAttributesDirty = true;
  30027. this._areTexturesDirty = true;
  30028. this._areFresnelDirty = true;
  30029. this._areMiscDirty = true;
  30030. this._areImageProcessingDirty = true;
  30031. this._normals = false;
  30032. this._uvs = false;
  30033. this._needNormals = false;
  30034. this._needUVs = false;
  30035. }
  30036. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30037. /**
  30038. * Specifies if the material needs to be re-calculated.
  30039. */
  30040. get: function () {
  30041. return this._isDirty;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. /**
  30047. * Marks the material to indicate that it has been re-calculated.
  30048. */
  30049. MaterialDefines.prototype.markAsProcessed = function () {
  30050. this._isDirty = false;
  30051. this._areAttributesDirty = false;
  30052. this._areTexturesDirty = false;
  30053. this._areFresnelDirty = false;
  30054. this._areLightsDirty = false;
  30055. this._areMiscDirty = false;
  30056. this._areImageProcessingDirty = false;
  30057. };
  30058. /**
  30059. * Marks the material to indicate that it needs to be re-calculated.
  30060. */
  30061. MaterialDefines.prototype.markAsUnprocessed = function () {
  30062. this._isDirty = true;
  30063. };
  30064. /**
  30065. * Marks the material to indicate all of its defines need to be re-calculated.
  30066. */
  30067. MaterialDefines.prototype.markAllAsDirty = function () {
  30068. this._areTexturesDirty = true;
  30069. this._areAttributesDirty = true;
  30070. this._areLightsDirty = true;
  30071. this._areFresnelDirty = true;
  30072. this._areMiscDirty = true;
  30073. this._areImageProcessingDirty = true;
  30074. this._isDirty = true;
  30075. };
  30076. /**
  30077. * Marks the material to indicate that image processing needs to be re-calculated.
  30078. */
  30079. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30080. this._areImageProcessingDirty = true;
  30081. this._isDirty = true;
  30082. };
  30083. /**
  30084. * Marks the material to indicate the lights need to be re-calculated.
  30085. */
  30086. MaterialDefines.prototype.markAsLightDirty = function () {
  30087. this._areLightsDirty = true;
  30088. this._isDirty = true;
  30089. };
  30090. /**
  30091. * Marks the attribute state as changed.
  30092. */
  30093. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30094. this._areAttributesDirty = true;
  30095. this._isDirty = true;
  30096. };
  30097. /**
  30098. * Marks the texture state as changed.
  30099. */
  30100. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30101. this._areTexturesDirty = true;
  30102. this._isDirty = true;
  30103. };
  30104. /**
  30105. * Marks the fresnel state as changed.
  30106. */
  30107. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30108. this._areFresnelDirty = true;
  30109. this._isDirty = true;
  30110. };
  30111. /**
  30112. * Marks the misc state as changed.
  30113. */
  30114. MaterialDefines.prototype.markAsMiscDirty = function () {
  30115. this._areMiscDirty = true;
  30116. this._isDirty = true;
  30117. };
  30118. /**
  30119. * Rebuilds the material defines.
  30120. */
  30121. MaterialDefines.prototype.rebuild = function () {
  30122. if (this._keys) {
  30123. delete this._keys;
  30124. }
  30125. this._keys = [];
  30126. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30127. var key = _a[_i];
  30128. if (key[0] === "_") {
  30129. continue;
  30130. }
  30131. this._keys.push(key);
  30132. }
  30133. };
  30134. /**
  30135. * Specifies if two material defines are equal.
  30136. * @param other - A material define instance to compare to.
  30137. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30138. */
  30139. MaterialDefines.prototype.isEqual = function (other) {
  30140. if (this._keys.length !== other._keys.length) {
  30141. return false;
  30142. }
  30143. for (var index = 0; index < this._keys.length; index++) {
  30144. var prop = this._keys[index];
  30145. if (this[prop] !== other[prop]) {
  30146. return false;
  30147. }
  30148. }
  30149. return true;
  30150. };
  30151. /**
  30152. * Clones this instance's defines to another instance.
  30153. * @param other - material defines to clone values to.
  30154. */
  30155. MaterialDefines.prototype.cloneTo = function (other) {
  30156. if (this._keys.length !== other._keys.length) {
  30157. other._keys = this._keys.slice(0);
  30158. }
  30159. for (var index = 0; index < this._keys.length; index++) {
  30160. var prop = this._keys[index];
  30161. other[prop] = this[prop];
  30162. }
  30163. };
  30164. /**
  30165. * Resets the material define values.
  30166. */
  30167. MaterialDefines.prototype.reset = function () {
  30168. for (var index = 0; index < this._keys.length; index++) {
  30169. var prop = this._keys[index];
  30170. if (typeof (this[prop]) === "number") {
  30171. this[prop] = 0;
  30172. }
  30173. else {
  30174. this[prop] = false;
  30175. }
  30176. }
  30177. };
  30178. /**
  30179. * Converts the material define values to a string.
  30180. * @returns - String of material define information.
  30181. */
  30182. MaterialDefines.prototype.toString = function () {
  30183. var result = "";
  30184. for (var index = 0; index < this._keys.length; index++) {
  30185. var prop = this._keys[index];
  30186. var value = this[prop];
  30187. if (typeof (value) === "number") {
  30188. result += "#define " + prop + " " + this[prop] + "\n";
  30189. }
  30190. else if (value) {
  30191. result += "#define " + prop + "\n";
  30192. }
  30193. }
  30194. return result;
  30195. };
  30196. return MaterialDefines;
  30197. }());
  30198. BABYLON.MaterialDefines = MaterialDefines;
  30199. /**
  30200. * This offers the main features of a material in BJS.
  30201. */
  30202. var Material = /** @class */ (function () {
  30203. /**
  30204. * Creates a material instance.
  30205. * @param name - The name of the material.
  30206. * @param scene - The BJS scene to reference.
  30207. * @param doNotAdd - Specifies if the material should be added to the scene.
  30208. */
  30209. function Material(name, scene, doNotAdd) {
  30210. /**
  30211. * Specifies if the ready state should be checked on each call.
  30212. */
  30213. this.checkReadyOnEveryCall = false;
  30214. /**
  30215. * Specifies if the ready state should be checked once.
  30216. */
  30217. this.checkReadyOnlyOnce = false;
  30218. /**
  30219. * The state of the material.
  30220. */
  30221. this.state = "";
  30222. /**
  30223. * The alpha value of the material.
  30224. */
  30225. this._alpha = 1.0;
  30226. /**
  30227. * Specifies if back face culling is enabled.
  30228. */
  30229. this._backFaceCulling = true;
  30230. /**
  30231. * Specifies if the material should be serialized.
  30232. */
  30233. this.doNotSerialize = false;
  30234. /**
  30235. * Specifies if the effect should be stored on sub meshes.
  30236. */
  30237. this.storeEffectOnSubMeshes = false;
  30238. /**
  30239. * An event triggered when the material is disposed.
  30240. * @type {BABYLON.Observable}
  30241. */
  30242. this.onDisposeObservable = new BABYLON.Observable();
  30243. /**
  30244. * An event triggered when the material is bound.
  30245. * @type {BABYLON.Observable}
  30246. */
  30247. this.onBindObservable = new BABYLON.Observable();
  30248. /**
  30249. * An event triggered when the material is unbound.
  30250. * @type {BABYLON.Observable}
  30251. */
  30252. this.onUnBindObservable = new BABYLON.Observable();
  30253. /**
  30254. * Stores the value of the alpha mode.
  30255. */
  30256. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30257. /**
  30258. * Stores the state of the need depth pre-pass value.
  30259. */
  30260. this._needDepthPrePass = false;
  30261. /**
  30262. * Specifies if depth writing should be disabled.
  30263. */
  30264. this.disableDepthWrite = false;
  30265. /**
  30266. * Specifies if depth writing should be forced.
  30267. */
  30268. this.forceDepthWrite = false;
  30269. /**
  30270. * Specifies if there should be a separate pass for culling.
  30271. */
  30272. this.separateCullingPass = false;
  30273. /**
  30274. * Stores the state specifing if fog should be enabled.
  30275. */
  30276. this._fogEnabled = true;
  30277. /**
  30278. * Stores the size of points.
  30279. */
  30280. this.pointSize = 1.0;
  30281. /**
  30282. * Stores the z offset value.
  30283. */
  30284. this.zOffset = 0;
  30285. /**
  30286. * Specifies if the material was previously ready.
  30287. */
  30288. this._wasPreviouslyReady = false;
  30289. /**
  30290. * Stores the fill mode state.
  30291. */
  30292. this._fillMode = Material.TriangleFillMode;
  30293. this.name = name;
  30294. this.id = name || BABYLON.Tools.RandomId();
  30295. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30296. if (this._scene.useRightHandedSystem) {
  30297. this.sideOrientation = Material.ClockWiseSideOrientation;
  30298. }
  30299. else {
  30300. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30301. }
  30302. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30303. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30304. if (!doNotAdd) {
  30305. this._scene.materials.push(this);
  30306. }
  30307. }
  30308. Object.defineProperty(Material, "TriangleFillMode", {
  30309. /**
  30310. * Returns the triangle fill mode.
  30311. */
  30312. get: function () {
  30313. return Material._TriangleFillMode;
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(Material, "WireFrameFillMode", {
  30319. /**
  30320. * Returns the wireframe mode.
  30321. */
  30322. get: function () {
  30323. return Material._WireFrameFillMode;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. Object.defineProperty(Material, "PointFillMode", {
  30329. /**
  30330. * Returns the point fill mode.
  30331. */
  30332. get: function () {
  30333. return Material._PointFillMode;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(Material, "PointListDrawMode", {
  30339. /**
  30340. * Returns the point list draw mode.
  30341. */
  30342. get: function () {
  30343. return Material._PointListDrawMode;
  30344. },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. Object.defineProperty(Material, "LineListDrawMode", {
  30349. /**
  30350. * Returns the line list draw mode.
  30351. */
  30352. get: function () {
  30353. return Material._LineListDrawMode;
  30354. },
  30355. enumerable: true,
  30356. configurable: true
  30357. });
  30358. Object.defineProperty(Material, "LineLoopDrawMode", {
  30359. /**
  30360. * Returns the line loop draw mode.
  30361. */
  30362. get: function () {
  30363. return Material._LineLoopDrawMode;
  30364. },
  30365. enumerable: true,
  30366. configurable: true
  30367. });
  30368. Object.defineProperty(Material, "LineStripDrawMode", {
  30369. /**
  30370. * Returns the line strip draw mode.
  30371. */
  30372. get: function () {
  30373. return Material._LineStripDrawMode;
  30374. },
  30375. enumerable: true,
  30376. configurable: true
  30377. });
  30378. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30379. /**
  30380. * Returns the triangle strip draw mode.
  30381. */
  30382. get: function () {
  30383. return Material._TriangleStripDrawMode;
  30384. },
  30385. enumerable: true,
  30386. configurable: true
  30387. });
  30388. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30389. /**
  30390. * Returns the triangle fan draw mode.
  30391. */
  30392. get: function () {
  30393. return Material._TriangleFanDrawMode;
  30394. },
  30395. enumerable: true,
  30396. configurable: true
  30397. });
  30398. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30399. /**
  30400. * Returns the clock-wise side orientation.
  30401. */
  30402. get: function () {
  30403. return Material._ClockWiseSideOrientation;
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30409. /**
  30410. * Returns the counter clock-wise side orientation.
  30411. */
  30412. get: function () {
  30413. return Material._CounterClockWiseSideOrientation;
  30414. },
  30415. enumerable: true,
  30416. configurable: true
  30417. });
  30418. Object.defineProperty(Material, "TextureDirtyFlag", {
  30419. /**
  30420. * Returns the dirty texture flag value.
  30421. */
  30422. get: function () {
  30423. return Material._TextureDirtyFlag;
  30424. },
  30425. enumerable: true,
  30426. configurable: true
  30427. });
  30428. Object.defineProperty(Material, "LightDirtyFlag", {
  30429. /**
  30430. * Returns the dirty light flag value.
  30431. */
  30432. get: function () {
  30433. return Material._LightDirtyFlag;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30439. /**
  30440. * Returns the dirty fresnel flag value.
  30441. */
  30442. get: function () {
  30443. return Material._FresnelDirtyFlag;
  30444. },
  30445. enumerable: true,
  30446. configurable: true
  30447. });
  30448. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30449. /**
  30450. * Returns the dirty attributes flag value.
  30451. */
  30452. get: function () {
  30453. return Material._AttributesDirtyFlag;
  30454. },
  30455. enumerable: true,
  30456. configurable: true
  30457. });
  30458. Object.defineProperty(Material, "MiscDirtyFlag", {
  30459. /**
  30460. * Returns the dirty misc flag value.
  30461. */
  30462. get: function () {
  30463. return Material._MiscDirtyFlag;
  30464. },
  30465. enumerable: true,
  30466. configurable: true
  30467. });
  30468. Object.defineProperty(Material.prototype, "alpha", {
  30469. /**
  30470. * Gets the alpha value of the material.
  30471. */
  30472. get: function () {
  30473. return this._alpha;
  30474. },
  30475. /**
  30476. * Sets the alpha value of the material.
  30477. */
  30478. set: function (value) {
  30479. if (this._alpha === value) {
  30480. return;
  30481. }
  30482. this._alpha = value;
  30483. this.markAsDirty(Material.MiscDirtyFlag);
  30484. },
  30485. enumerable: true,
  30486. configurable: true
  30487. });
  30488. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30489. /**
  30490. * Gets the back-face culling state.
  30491. */
  30492. get: function () {
  30493. return this._backFaceCulling;
  30494. },
  30495. /**
  30496. * Sets the back-face culling state.
  30497. */
  30498. set: function (value) {
  30499. if (this._backFaceCulling === value) {
  30500. return;
  30501. }
  30502. this._backFaceCulling = value;
  30503. this.markAsDirty(Material.TextureDirtyFlag);
  30504. },
  30505. enumerable: true,
  30506. configurable: true
  30507. });
  30508. Object.defineProperty(Material.prototype, "onDispose", {
  30509. /**
  30510. * Called during a dispose event.
  30511. */
  30512. set: function (callback) {
  30513. if (this._onDisposeObserver) {
  30514. this.onDisposeObservable.remove(this._onDisposeObserver);
  30515. }
  30516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30517. },
  30518. enumerable: true,
  30519. configurable: true
  30520. });
  30521. Object.defineProperty(Material.prototype, "onBind", {
  30522. /**
  30523. * Called during a bind event.
  30524. */
  30525. set: function (callback) {
  30526. if (this._onBindObserver) {
  30527. this.onBindObservable.remove(this._onBindObserver);
  30528. }
  30529. this._onBindObserver = this.onBindObservable.add(callback);
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. Object.defineProperty(Material.prototype, "alphaMode", {
  30535. /**
  30536. * Gets the value of the alpha mode.
  30537. */
  30538. get: function () {
  30539. return this._alphaMode;
  30540. },
  30541. /**
  30542. * Sets the value of the alpha mode.
  30543. */
  30544. set: function (value) {
  30545. if (this._alphaMode === value) {
  30546. return;
  30547. }
  30548. this._alphaMode = value;
  30549. this.markAsDirty(Material.TextureDirtyFlag);
  30550. },
  30551. enumerable: true,
  30552. configurable: true
  30553. });
  30554. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30555. /**
  30556. * Gets the depth pre-pass value.
  30557. */
  30558. get: function () {
  30559. return this._needDepthPrePass;
  30560. },
  30561. /**
  30562. * Sets the need depth pre-pass value.
  30563. */
  30564. set: function (value) {
  30565. if (this._needDepthPrePass === value) {
  30566. return;
  30567. }
  30568. this._needDepthPrePass = value;
  30569. if (this._needDepthPrePass) {
  30570. this.checkReadyOnEveryCall = true;
  30571. }
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(Material.prototype, "fogEnabled", {
  30577. /**
  30578. * Gets the value of the fog enabled state.
  30579. */
  30580. get: function () {
  30581. return this._fogEnabled;
  30582. },
  30583. /**
  30584. * Sets the state for enabling fog.
  30585. */
  30586. set: function (value) {
  30587. if (this._fogEnabled === value) {
  30588. return;
  30589. }
  30590. this._fogEnabled = value;
  30591. this.markAsDirty(Material.MiscDirtyFlag);
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(Material.prototype, "wireframe", {
  30597. /**
  30598. * Gets a value specifying if wireframe mode is enabled.
  30599. */
  30600. get: function () {
  30601. return this._fillMode === Material.WireFrameFillMode;
  30602. },
  30603. /**
  30604. * Sets the state of wireframe mode.
  30605. */
  30606. set: function (value) {
  30607. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(Material.prototype, "pointsCloud", {
  30613. /**
  30614. * Gets the value specifying if point clouds are enabled.
  30615. */
  30616. get: function () {
  30617. return this._fillMode === Material.PointFillMode;
  30618. },
  30619. /**
  30620. * Sets the state of point cloud mode.
  30621. */
  30622. set: function (value) {
  30623. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30624. },
  30625. enumerable: true,
  30626. configurable: true
  30627. });
  30628. Object.defineProperty(Material.prototype, "fillMode", {
  30629. /**
  30630. * Gets the material fill mode.
  30631. */
  30632. get: function () {
  30633. return this._fillMode;
  30634. },
  30635. /**
  30636. * Sets the material fill mode.
  30637. */
  30638. set: function (value) {
  30639. if (this._fillMode === value) {
  30640. return;
  30641. }
  30642. this._fillMode = value;
  30643. this.markAsDirty(Material.MiscDirtyFlag);
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. /**
  30649. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30650. * subclasses should override adding information pertainent to themselves.
  30651. * @returns - String with material information.
  30652. */
  30653. Material.prototype.toString = function (fullDetails) {
  30654. var ret = "Name: " + this.name;
  30655. if (fullDetails) {
  30656. }
  30657. return ret;
  30658. };
  30659. /**
  30660. * Gets the class name of the material.
  30661. * @returns - String with the class name of the material.
  30662. */
  30663. Material.prototype.getClassName = function () {
  30664. return "Material";
  30665. };
  30666. Object.defineProperty(Material.prototype, "isFrozen", {
  30667. /**
  30668. * Specifies if updates for the material been locked.
  30669. */
  30670. get: function () {
  30671. return this.checkReadyOnlyOnce;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. /**
  30677. * Locks updates for the material.
  30678. */
  30679. Material.prototype.freeze = function () {
  30680. this.checkReadyOnlyOnce = true;
  30681. };
  30682. /**
  30683. * Unlocks updates for the material.
  30684. */
  30685. Material.prototype.unfreeze = function () {
  30686. this.checkReadyOnlyOnce = false;
  30687. };
  30688. /**
  30689. * Specifies if the material is ready to be used.
  30690. * @param mesh - BJS mesh.
  30691. * @param useInstances - Specifies if instances should be used.
  30692. * @returns - Boolean indicating if the material is ready to be used.
  30693. */
  30694. Material.prototype.isReady = function (mesh, useInstances) {
  30695. return true;
  30696. };
  30697. /**
  30698. * Specifies that the submesh is ready to be used.
  30699. * @param mesh - BJS mesh.
  30700. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30701. * @param useInstances - Specifies that instances should be used.
  30702. * @returns - boolean indicating that the submesh is ready or not.
  30703. */
  30704. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30705. return false;
  30706. };
  30707. /**
  30708. * Returns the material effect.
  30709. * @returns - Nullable material effect.
  30710. */
  30711. Material.prototype.getEffect = function () {
  30712. return this._effect;
  30713. };
  30714. /**
  30715. * Returns the BJS scene.
  30716. * @returns - BJS Scene.
  30717. */
  30718. Material.prototype.getScene = function () {
  30719. return this._scene;
  30720. };
  30721. /**
  30722. * Specifies if the material will require alpha blending
  30723. * @returns - Boolean specifying if alpha blending is needed.
  30724. */
  30725. Material.prototype.needAlphaBlending = function () {
  30726. return (this.alpha < 1.0);
  30727. };
  30728. /**
  30729. * Specifies if the mesh will require alpha blending.
  30730. * @param mesh - BJS mesh.
  30731. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30732. */
  30733. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30734. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30735. };
  30736. /**
  30737. * Specifies if this material should be rendered in alpha test mode.
  30738. * @returns - Boolean specifying if an alpha test is needed.
  30739. */
  30740. Material.prototype.needAlphaTesting = function () {
  30741. return false;
  30742. };
  30743. /**
  30744. * Gets the texture used for the alpha test.
  30745. * @returns - Nullable alpha test texture.
  30746. */
  30747. Material.prototype.getAlphaTestTexture = function () {
  30748. return null;
  30749. };
  30750. /**
  30751. * Marks the material to indicate that it needs to be re-calculated.
  30752. */
  30753. Material.prototype.markDirty = function () {
  30754. this._wasPreviouslyReady = false;
  30755. };
  30756. Material.prototype._preBind = function (effect, overrideOrientation) {
  30757. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30758. var engine = this._scene.getEngine();
  30759. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30760. var reverse = orientation === Material.ClockWiseSideOrientation;
  30761. engine.enableEffect(effect ? effect : this._effect);
  30762. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30763. return reverse;
  30764. };
  30765. /**
  30766. * Binds the material to the mesh.
  30767. * @param world - World transformation matrix.
  30768. * @param mesh - Mesh to bind the material to.
  30769. */
  30770. Material.prototype.bind = function (world, mesh) {
  30771. };
  30772. /**
  30773. * Binds the submesh to the material.
  30774. * @param world - World transformation matrix.
  30775. * @param mesh - Mesh containing the submesh.
  30776. * @param subMesh - Submesh to bind the material to.
  30777. */
  30778. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30779. };
  30780. /**
  30781. * Binds the world matrix to the material.
  30782. * @param world - World transformation matrix.
  30783. */
  30784. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30785. };
  30786. /**
  30787. * Binds the scene's uniform buffer to the effect.
  30788. * @param effect - Effect to bind to the scene uniform buffer.
  30789. * @param sceneUbo - Scene uniform buffer.
  30790. */
  30791. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30792. sceneUbo.bindToEffect(effect, "Scene");
  30793. };
  30794. /**
  30795. * Binds the view matrix to the effect.
  30796. * @param effect - Effect to bind the view matrix to.
  30797. */
  30798. Material.prototype.bindView = function (effect) {
  30799. if (!this._useUBO) {
  30800. effect.setMatrix("view", this.getScene().getViewMatrix());
  30801. }
  30802. else {
  30803. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30804. }
  30805. };
  30806. /**
  30807. * Binds the view projection matrix to the effect.
  30808. * @param effect - Effect to bind the view projection matrix to.
  30809. */
  30810. Material.prototype.bindViewProjection = function (effect) {
  30811. if (!this._useUBO) {
  30812. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30813. }
  30814. else {
  30815. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30816. }
  30817. };
  30818. /**
  30819. * Specifies if material alpha testing should be turned on for the mesh.
  30820. * @param mesh - BJS mesh.
  30821. */
  30822. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30823. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30824. };
  30825. /**
  30826. * Processes to execute after binding the material to a mesh.
  30827. * @param mesh - BJS mesh.
  30828. */
  30829. Material.prototype._afterBind = function (mesh) {
  30830. this._scene._cachedMaterial = this;
  30831. if (mesh) {
  30832. this._scene._cachedVisibility = mesh.visibility;
  30833. }
  30834. else {
  30835. this._scene._cachedVisibility = 1;
  30836. }
  30837. if (mesh) {
  30838. this.onBindObservable.notifyObservers(mesh);
  30839. }
  30840. if (this.disableDepthWrite) {
  30841. var engine = this._scene.getEngine();
  30842. this._cachedDepthWriteState = engine.getDepthWrite();
  30843. engine.setDepthWrite(false);
  30844. }
  30845. };
  30846. /**
  30847. * Unbinds the material from the mesh.
  30848. */
  30849. Material.prototype.unbind = function () {
  30850. this.onUnBindObservable.notifyObservers(this);
  30851. if (this.disableDepthWrite) {
  30852. var engine = this._scene.getEngine();
  30853. engine.setDepthWrite(this._cachedDepthWriteState);
  30854. }
  30855. };
  30856. /**
  30857. * Gets the active textures from the material.
  30858. * @returns - Array of textures.
  30859. */
  30860. Material.prototype.getActiveTextures = function () {
  30861. return [];
  30862. };
  30863. /**
  30864. * Specifies if the material uses a texture.
  30865. * @param texture - Texture to check against the material.
  30866. * @returns - Boolean specifying if the material uses the texture.
  30867. */
  30868. Material.prototype.hasTexture = function (texture) {
  30869. return false;
  30870. };
  30871. /**
  30872. * Makes a duplicate of the material, and gives it a new name.
  30873. * @param name - Name to call the duplicated material.
  30874. * @returns - Nullable cloned material
  30875. */
  30876. Material.prototype.clone = function (name) {
  30877. return null;
  30878. };
  30879. /**
  30880. * Gets the meshes bound to the material.
  30881. * @returns - Array of meshes bound to the material.
  30882. */
  30883. Material.prototype.getBindedMeshes = function () {
  30884. var result = new Array();
  30885. for (var index = 0; index < this._scene.meshes.length; index++) {
  30886. var mesh = this._scene.meshes[index];
  30887. if (mesh.material === this) {
  30888. result.push(mesh);
  30889. }
  30890. }
  30891. return result;
  30892. };
  30893. /**
  30894. * Force shader compilation
  30895. * @param mesh - BJS mesh.
  30896. * @param onCompiled - function to execute once the material is compiled.
  30897. * @param options - options to pass to this function.
  30898. */
  30899. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30900. var _this = this;
  30901. var localOptions = __assign({ clipPlane: false }, options);
  30902. var subMesh = new BABYLON.BaseSubMesh();
  30903. var scene = this.getScene();
  30904. var checkReady = function () {
  30905. if (!_this._scene || !_this._scene.getEngine()) {
  30906. return;
  30907. }
  30908. if (subMesh._materialDefines) {
  30909. subMesh._materialDefines._renderId = -1;
  30910. }
  30911. var clipPlaneState = scene.clipPlane;
  30912. if (localOptions.clipPlane) {
  30913. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30914. }
  30915. if (_this.storeEffectOnSubMeshes) {
  30916. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30917. if (onCompiled) {
  30918. onCompiled(_this);
  30919. }
  30920. }
  30921. else {
  30922. setTimeout(checkReady, 16);
  30923. }
  30924. }
  30925. else {
  30926. if (_this.isReady(mesh)) {
  30927. if (onCompiled) {
  30928. onCompiled(_this);
  30929. }
  30930. }
  30931. else {
  30932. setTimeout(checkReady, 16);
  30933. }
  30934. }
  30935. if (localOptions.clipPlane) {
  30936. scene.clipPlane = clipPlaneState;
  30937. }
  30938. };
  30939. checkReady();
  30940. };
  30941. /**
  30942. * Force shader compilation.
  30943. * @param mesh The mesh that will use this material
  30944. * @param options Additional options for compiling the shaders
  30945. * @returns A promise that resolves when the compilation completes
  30946. */
  30947. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30948. var _this = this;
  30949. return new Promise(function (resolve) {
  30950. _this.forceCompilation(mesh, function () {
  30951. resolve();
  30952. }, options);
  30953. });
  30954. };
  30955. /**
  30956. * Marks a define in the material to indicate that it needs to be re-computed.
  30957. * @param flag - Material define flag.
  30958. */
  30959. Material.prototype.markAsDirty = function (flag) {
  30960. if (flag & Material.TextureDirtyFlag) {
  30961. this._markAllSubMeshesAsTexturesDirty();
  30962. }
  30963. if (flag & Material.LightDirtyFlag) {
  30964. this._markAllSubMeshesAsLightsDirty();
  30965. }
  30966. if (flag & Material.FresnelDirtyFlag) {
  30967. this._markAllSubMeshesAsFresnelDirty();
  30968. }
  30969. if (flag & Material.AttributesDirtyFlag) {
  30970. this._markAllSubMeshesAsAttributesDirty();
  30971. }
  30972. if (flag & Material.MiscDirtyFlag) {
  30973. this._markAllSubMeshesAsMiscDirty();
  30974. }
  30975. this.getScene().resetCachedMaterial();
  30976. };
  30977. /**
  30978. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30979. * @param func - function which checks material defines against the submeshes.
  30980. */
  30981. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30983. var mesh = _a[_i];
  30984. if (!mesh.subMeshes) {
  30985. continue;
  30986. }
  30987. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30988. var subMesh = _c[_b];
  30989. if (subMesh.getMaterial() !== this) {
  30990. continue;
  30991. }
  30992. if (!subMesh._materialDefines) {
  30993. continue;
  30994. }
  30995. func(subMesh._materialDefines);
  30996. }
  30997. }
  30998. };
  30999. /**
  31000. * Indicates that image processing needs to be re-calculated for all submeshes.
  31001. */
  31002. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31003. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31004. };
  31005. /**
  31006. * Indicates that textures need to be re-calculated for all submeshes.
  31007. */
  31008. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31009. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31010. };
  31011. /**
  31012. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31013. */
  31014. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31015. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31016. };
  31017. /**
  31018. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31019. */
  31020. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31021. this._markAllSubMeshesAsDirty(function (defines) {
  31022. defines.markAsFresnelDirty();
  31023. defines.markAsMiscDirty();
  31024. });
  31025. };
  31026. /**
  31027. * Indicates that lights need to be re-calculated for all submeshes.
  31028. */
  31029. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31030. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31031. };
  31032. /**
  31033. * Indicates that attributes need to be re-calculated for all submeshes.
  31034. */
  31035. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31036. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31037. };
  31038. /**
  31039. * Indicates that misc needs to be re-calculated for all submeshes.
  31040. */
  31041. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31042. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31043. };
  31044. /**
  31045. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31046. */
  31047. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31048. this._markAllSubMeshesAsDirty(function (defines) {
  31049. defines.markAsTexturesDirty();
  31050. defines.markAsMiscDirty();
  31051. });
  31052. };
  31053. /**
  31054. * Disposes the material.
  31055. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31056. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31057. */
  31058. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31059. // Animations
  31060. this.getScene().stopAnimation(this);
  31061. // Remove from scene
  31062. var index = this._scene.materials.indexOf(this);
  31063. if (index >= 0) {
  31064. this._scene.materials.splice(index, 1);
  31065. }
  31066. // Remove from meshes
  31067. for (index = 0; index < this._scene.meshes.length; index++) {
  31068. var mesh = this._scene.meshes[index];
  31069. if (mesh.material === this) {
  31070. mesh.material = null;
  31071. if (mesh.geometry) {
  31072. var geometry = (mesh.geometry);
  31073. if (this.storeEffectOnSubMeshes) {
  31074. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31075. var subMesh = _a[_i];
  31076. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31077. if (forceDisposeEffect && subMesh._materialEffect) {
  31078. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31079. }
  31080. }
  31081. }
  31082. else {
  31083. geometry._releaseVertexArrayObject(this._effect);
  31084. }
  31085. }
  31086. }
  31087. }
  31088. this._uniformBuffer.dispose();
  31089. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31090. if (forceDisposeEffect && this._effect) {
  31091. if (!this.storeEffectOnSubMeshes) {
  31092. this._scene.getEngine()._releaseEffect(this._effect);
  31093. }
  31094. this._effect = null;
  31095. }
  31096. // Callback
  31097. this.onDisposeObservable.notifyObservers(this);
  31098. this.onDisposeObservable.clear();
  31099. this.onBindObservable.clear();
  31100. this.onUnBindObservable.clear();
  31101. };
  31102. /**
  31103. * Serializes this material.
  31104. * @returns - serialized material object.
  31105. */
  31106. Material.prototype.serialize = function () {
  31107. return BABYLON.SerializationHelper.Serialize(this);
  31108. };
  31109. /**
  31110. * Creates a MultiMaterial from parse MultiMaterial data.
  31111. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31112. * @param scene - BJS scene.
  31113. * @returns - MultiMaterial.
  31114. */
  31115. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31116. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31117. multiMaterial.id = parsedMultiMaterial.id;
  31118. if (BABYLON.Tags) {
  31119. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31120. }
  31121. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31122. var subMatId = parsedMultiMaterial.materials[matIndex];
  31123. if (subMatId) {
  31124. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31125. }
  31126. else {
  31127. multiMaterial.subMaterials.push(null);
  31128. }
  31129. }
  31130. return multiMaterial;
  31131. };
  31132. /**
  31133. * Creates a material from parsed material data.
  31134. * @param parsedMaterial - Parsed material data.
  31135. * @param scene - BJS scene.
  31136. * @param rootUrl - Root URL containing the material information.
  31137. * @returns - Parsed material.
  31138. */
  31139. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31140. if (!parsedMaterial.customType) {
  31141. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31142. }
  31143. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31144. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31145. if (!BABYLON.LegacyPBRMaterial) {
  31146. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31147. return;
  31148. }
  31149. }
  31150. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31151. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31152. ;
  31153. };
  31154. // Triangle views
  31155. Material._TriangleFillMode = 0;
  31156. Material._WireFrameFillMode = 1;
  31157. Material._PointFillMode = 2;
  31158. // Draw modes
  31159. Material._PointListDrawMode = 3;
  31160. Material._LineListDrawMode = 4;
  31161. Material._LineLoopDrawMode = 5;
  31162. Material._LineStripDrawMode = 6;
  31163. Material._TriangleStripDrawMode = 7;
  31164. Material._TriangleFanDrawMode = 8;
  31165. /**
  31166. * Stores the clock-wise side orientation.
  31167. */
  31168. Material._ClockWiseSideOrientation = 0;
  31169. /**
  31170. * Stores the counter clock-wise side orientation.
  31171. */
  31172. Material._CounterClockWiseSideOrientation = 1;
  31173. /**
  31174. * The dirty texture flag value.
  31175. */
  31176. Material._TextureDirtyFlag = 1;
  31177. /**
  31178. * The dirty light flag value.
  31179. */
  31180. Material._LightDirtyFlag = 2;
  31181. /**
  31182. * The dirty fresnel flag value.
  31183. */
  31184. Material._FresnelDirtyFlag = 4;
  31185. /**
  31186. * The dirty attribute flag value.
  31187. */
  31188. Material._AttributesDirtyFlag = 8;
  31189. /**
  31190. * The dirty misc flag value.
  31191. */
  31192. Material._MiscDirtyFlag = 16;
  31193. __decorate([
  31194. BABYLON.serialize()
  31195. ], Material.prototype, "id", void 0);
  31196. __decorate([
  31197. BABYLON.serialize()
  31198. ], Material.prototype, "name", void 0);
  31199. __decorate([
  31200. BABYLON.serialize()
  31201. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31202. __decorate([
  31203. BABYLON.serialize()
  31204. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31205. __decorate([
  31206. BABYLON.serialize()
  31207. ], Material.prototype, "state", void 0);
  31208. __decorate([
  31209. BABYLON.serialize("alpha")
  31210. ], Material.prototype, "_alpha", void 0);
  31211. __decorate([
  31212. BABYLON.serialize("backFaceCulling")
  31213. ], Material.prototype, "_backFaceCulling", void 0);
  31214. __decorate([
  31215. BABYLON.serialize()
  31216. ], Material.prototype, "sideOrientation", void 0);
  31217. __decorate([
  31218. BABYLON.serialize("alphaMode")
  31219. ], Material.prototype, "_alphaMode", void 0);
  31220. __decorate([
  31221. BABYLON.serialize()
  31222. ], Material.prototype, "_needDepthPrePass", void 0);
  31223. __decorate([
  31224. BABYLON.serialize()
  31225. ], Material.prototype, "disableDepthWrite", void 0);
  31226. __decorate([
  31227. BABYLON.serialize()
  31228. ], Material.prototype, "forceDepthWrite", void 0);
  31229. __decorate([
  31230. BABYLON.serialize()
  31231. ], Material.prototype, "separateCullingPass", void 0);
  31232. __decorate([
  31233. BABYLON.serialize("fogEnabled")
  31234. ], Material.prototype, "_fogEnabled", void 0);
  31235. __decorate([
  31236. BABYLON.serialize()
  31237. ], Material.prototype, "pointSize", void 0);
  31238. __decorate([
  31239. BABYLON.serialize()
  31240. ], Material.prototype, "zOffset", void 0);
  31241. __decorate([
  31242. BABYLON.serialize()
  31243. ], Material.prototype, "wireframe", null);
  31244. __decorate([
  31245. BABYLON.serialize()
  31246. ], Material.prototype, "pointsCloud", null);
  31247. __decorate([
  31248. BABYLON.serialize()
  31249. ], Material.prototype, "fillMode", null);
  31250. return Material;
  31251. }());
  31252. BABYLON.Material = Material;
  31253. })(BABYLON || (BABYLON = {}));
  31254. //# sourceMappingURL=babylon.material.js.map
  31255. var BABYLON;
  31256. (function (BABYLON) {
  31257. var UniformBuffer = /** @class */ (function () {
  31258. /**
  31259. * Uniform buffer objects.
  31260. *
  31261. * Handles blocks of uniform on the GPU.
  31262. *
  31263. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31264. *
  31265. * For more information, please refer to :
  31266. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31267. */
  31268. function UniformBuffer(engine, data, dynamic) {
  31269. this._engine = engine;
  31270. this._noUBO = !engine.supportsUniformBuffers;
  31271. this._dynamic = dynamic;
  31272. this._data = data || [];
  31273. this._uniformLocations = {};
  31274. this._uniformSizes = {};
  31275. this._uniformLocationPointer = 0;
  31276. this._needSync = false;
  31277. if (this._noUBO) {
  31278. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31279. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31280. this.updateFloat = this._updateFloatForEffect;
  31281. this.updateFloat2 = this._updateFloat2ForEffect;
  31282. this.updateFloat3 = this._updateFloat3ForEffect;
  31283. this.updateFloat4 = this._updateFloat4ForEffect;
  31284. this.updateMatrix = this._updateMatrixForEffect;
  31285. this.updateVector3 = this._updateVector3ForEffect;
  31286. this.updateVector4 = this._updateVector4ForEffect;
  31287. this.updateColor3 = this._updateColor3ForEffect;
  31288. this.updateColor4 = this._updateColor4ForEffect;
  31289. }
  31290. else {
  31291. this._engine._uniformBuffers.push(this);
  31292. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31293. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31294. this.updateFloat = this._updateFloatForUniform;
  31295. this.updateFloat2 = this._updateFloat2ForUniform;
  31296. this.updateFloat3 = this._updateFloat3ForUniform;
  31297. this.updateFloat4 = this._updateFloat4ForUniform;
  31298. this.updateMatrix = this._updateMatrixForUniform;
  31299. this.updateVector3 = this._updateVector3ForUniform;
  31300. this.updateVector4 = this._updateVector4ForUniform;
  31301. this.updateColor3 = this._updateColor3ForUniform;
  31302. this.updateColor4 = this._updateColor4ForUniform;
  31303. }
  31304. }
  31305. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31306. // Properties
  31307. /**
  31308. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31309. * or just falling back on setUniformXXX calls.
  31310. */
  31311. get: function () {
  31312. return !this._noUBO;
  31313. },
  31314. enumerable: true,
  31315. configurable: true
  31316. });
  31317. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31318. /**
  31319. * Indicates if the WebGL underlying uniform buffer is in sync
  31320. * with the javascript cache data.
  31321. */
  31322. get: function () {
  31323. return !this._needSync;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. /**
  31329. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31330. * Also, a dynamic UniformBuffer will disable cache verification and always
  31331. * update the underlying WebGL uniform buffer to the GPU.
  31332. */
  31333. UniformBuffer.prototype.isDynamic = function () {
  31334. return this._dynamic !== undefined;
  31335. };
  31336. /**
  31337. * The data cache on JS side.
  31338. */
  31339. UniformBuffer.prototype.getData = function () {
  31340. return this._bufferData;
  31341. };
  31342. /**
  31343. * The underlying WebGL Uniform buffer.
  31344. */
  31345. UniformBuffer.prototype.getBuffer = function () {
  31346. return this._buffer;
  31347. };
  31348. /**
  31349. * std140 layout specifies how to align data within an UBO structure.
  31350. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31351. * for specs.
  31352. */
  31353. UniformBuffer.prototype._fillAlignment = function (size) {
  31354. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31355. // and 4x4 matrices
  31356. // TODO : change if other types are used
  31357. var alignment;
  31358. if (size <= 2) {
  31359. alignment = size;
  31360. }
  31361. else {
  31362. alignment = 4;
  31363. }
  31364. if ((this._uniformLocationPointer % alignment) !== 0) {
  31365. var oldPointer = this._uniformLocationPointer;
  31366. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31367. var diff = this._uniformLocationPointer - oldPointer;
  31368. for (var i = 0; i < diff; i++) {
  31369. this._data.push(0);
  31370. }
  31371. }
  31372. };
  31373. /**
  31374. * Adds an uniform in the buffer.
  31375. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31376. * for the layout to be correct !
  31377. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31378. * @param {number|number[]} size Data size, or data directly.
  31379. */
  31380. UniformBuffer.prototype.addUniform = function (name, size) {
  31381. if (this._noUBO) {
  31382. return;
  31383. }
  31384. if (this._uniformLocations[name] !== undefined) {
  31385. // Already existing uniform
  31386. return;
  31387. }
  31388. // This function must be called in the order of the shader layout !
  31389. // size can be the size of the uniform, or data directly
  31390. var data;
  31391. if (size instanceof Array) {
  31392. data = size;
  31393. size = data.length;
  31394. }
  31395. else {
  31396. size = size;
  31397. data = [];
  31398. // Fill with zeros
  31399. for (var i = 0; i < size; i++) {
  31400. data.push(0);
  31401. }
  31402. }
  31403. this._fillAlignment(size);
  31404. this._uniformSizes[name] = size;
  31405. this._uniformLocations[name] = this._uniformLocationPointer;
  31406. this._uniformLocationPointer += size;
  31407. for (var i = 0; i < size; i++) {
  31408. this._data.push(data[i]);
  31409. }
  31410. this._needSync = true;
  31411. };
  31412. /**
  31413. * Wrapper for addUniform.
  31414. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31415. * @param {Matrix} mat A 4x4 matrix.
  31416. */
  31417. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31418. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31419. };
  31420. /**
  31421. * Wrapper for addUniform.
  31422. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31423. * @param {number} x
  31424. * @param {number} y
  31425. */
  31426. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31427. var temp = [x, y];
  31428. this.addUniform(name, temp);
  31429. };
  31430. /**
  31431. * Wrapper for addUniform.
  31432. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31433. * @param {number} x
  31434. * @param {number} y
  31435. * @param {number} z
  31436. */
  31437. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31438. var temp = [x, y, z];
  31439. this.addUniform(name, temp);
  31440. };
  31441. /**
  31442. * Wrapper for addUniform.
  31443. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31444. * @param {Color3} color
  31445. */
  31446. UniformBuffer.prototype.addColor3 = function (name, color) {
  31447. var temp = new Array();
  31448. color.toArray(temp);
  31449. this.addUniform(name, temp);
  31450. };
  31451. /**
  31452. * Wrapper for addUniform.
  31453. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31454. * @param {Color3} color
  31455. * @param {number} alpha
  31456. */
  31457. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31458. var temp = new Array();
  31459. color.toArray(temp);
  31460. temp.push(alpha);
  31461. this.addUniform(name, temp);
  31462. };
  31463. /**
  31464. * Wrapper for addUniform.
  31465. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31466. * @param {Vector3} vector
  31467. */
  31468. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31469. var temp = new Array();
  31470. vector.toArray(temp);
  31471. this.addUniform(name, temp);
  31472. };
  31473. /**
  31474. * Wrapper for addUniform.
  31475. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31476. */
  31477. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31478. this.addUniform(name, 12);
  31479. };
  31480. /**
  31481. * Wrapper for addUniform.
  31482. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31483. */
  31484. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31485. this.addUniform(name, 8);
  31486. };
  31487. /**
  31488. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31489. */
  31490. UniformBuffer.prototype.create = function () {
  31491. if (this._noUBO) {
  31492. return;
  31493. }
  31494. if (this._buffer) {
  31495. return; // nothing to do
  31496. }
  31497. // See spec, alignment must be filled as a vec4
  31498. this._fillAlignment(4);
  31499. this._bufferData = new Float32Array(this._data);
  31500. this._rebuild();
  31501. this._needSync = true;
  31502. };
  31503. UniformBuffer.prototype._rebuild = function () {
  31504. if (this._noUBO) {
  31505. return;
  31506. }
  31507. if (this._dynamic) {
  31508. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31509. }
  31510. else {
  31511. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31512. }
  31513. };
  31514. /**
  31515. * Updates the WebGL Uniform Buffer on the GPU.
  31516. * If the `dynamic` flag is set to true, no cache comparison is done.
  31517. * Otherwise, the buffer will be updated only if the cache differs.
  31518. */
  31519. UniformBuffer.prototype.update = function () {
  31520. if (!this._buffer) {
  31521. this.create();
  31522. return;
  31523. }
  31524. if (!this._dynamic && !this._needSync) {
  31525. return;
  31526. }
  31527. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31528. this._needSync = false;
  31529. };
  31530. /**
  31531. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31532. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31533. * @param {number[]|Float32Array} data Flattened data
  31534. * @param {number} size Size of the data.
  31535. */
  31536. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31537. var location = this._uniformLocations[uniformName];
  31538. if (location === undefined) {
  31539. if (this._buffer) {
  31540. // Cannot add an uniform if the buffer is already created
  31541. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31542. return;
  31543. }
  31544. this.addUniform(uniformName, size);
  31545. location = this._uniformLocations[uniformName];
  31546. }
  31547. if (!this._buffer) {
  31548. this.create();
  31549. }
  31550. if (!this._dynamic) {
  31551. // Cache for static uniform buffers
  31552. var changed = false;
  31553. for (var i = 0; i < size; i++) {
  31554. if (this._bufferData[location + i] !== data[i]) {
  31555. changed = true;
  31556. this._bufferData[location + i] = data[i];
  31557. }
  31558. }
  31559. this._needSync = this._needSync || changed;
  31560. }
  31561. else {
  31562. // No cache for dynamic
  31563. for (var i = 0; i < size; i++) {
  31564. this._bufferData[location + i] = data[i];
  31565. }
  31566. }
  31567. };
  31568. // Update methods
  31569. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31570. // To match std140, matrix must be realigned
  31571. for (var i = 0; i < 3; i++) {
  31572. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31573. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31574. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31575. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31576. }
  31577. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31578. };
  31579. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31580. this._currentEffect.setMatrix3x3(name, matrix);
  31581. };
  31582. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31583. this._currentEffect.setMatrix2x2(name, matrix);
  31584. };
  31585. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31586. // To match std140, matrix must be realigned
  31587. for (var i = 0; i < 2; i++) {
  31588. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31589. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31590. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31591. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31592. }
  31593. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31594. };
  31595. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31596. this._currentEffect.setFloat(name, x);
  31597. };
  31598. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31599. UniformBuffer._tempBuffer[0] = x;
  31600. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31601. };
  31602. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31603. if (suffix === void 0) { suffix = ""; }
  31604. this._currentEffect.setFloat2(name + suffix, x, y);
  31605. };
  31606. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31607. if (suffix === void 0) { suffix = ""; }
  31608. UniformBuffer._tempBuffer[0] = x;
  31609. UniformBuffer._tempBuffer[1] = y;
  31610. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31611. };
  31612. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31613. if (suffix === void 0) { suffix = ""; }
  31614. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31615. };
  31616. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31617. if (suffix === void 0) { suffix = ""; }
  31618. UniformBuffer._tempBuffer[0] = x;
  31619. UniformBuffer._tempBuffer[1] = y;
  31620. UniformBuffer._tempBuffer[2] = z;
  31621. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31622. };
  31623. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31624. if (suffix === void 0) { suffix = ""; }
  31625. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31626. };
  31627. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31628. if (suffix === void 0) { suffix = ""; }
  31629. UniformBuffer._tempBuffer[0] = x;
  31630. UniformBuffer._tempBuffer[1] = y;
  31631. UniformBuffer._tempBuffer[2] = z;
  31632. UniformBuffer._tempBuffer[3] = w;
  31633. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31634. };
  31635. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31636. this._currentEffect.setMatrix(name, mat);
  31637. };
  31638. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31639. this.updateUniform(name, mat.toArray(), 16);
  31640. };
  31641. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31642. this._currentEffect.setVector3(name, vector);
  31643. };
  31644. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31645. vector.toArray(UniformBuffer._tempBuffer);
  31646. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31647. };
  31648. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31649. this._currentEffect.setVector4(name, vector);
  31650. };
  31651. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31652. vector.toArray(UniformBuffer._tempBuffer);
  31653. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31654. };
  31655. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31656. if (suffix === void 0) { suffix = ""; }
  31657. this._currentEffect.setColor3(name + suffix, color);
  31658. };
  31659. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31660. if (suffix === void 0) { suffix = ""; }
  31661. color.toArray(UniformBuffer._tempBuffer);
  31662. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31663. };
  31664. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31665. if (suffix === void 0) { suffix = ""; }
  31666. this._currentEffect.setColor4(name + suffix, color, alpha);
  31667. };
  31668. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31669. if (suffix === void 0) { suffix = ""; }
  31670. color.toArray(UniformBuffer._tempBuffer);
  31671. UniformBuffer._tempBuffer[3] = alpha;
  31672. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31673. };
  31674. /**
  31675. * Sets a sampler uniform on the effect.
  31676. * @param {string} name Name of the sampler.
  31677. * @param {Texture} texture
  31678. */
  31679. UniformBuffer.prototype.setTexture = function (name, texture) {
  31680. this._currentEffect.setTexture(name, texture);
  31681. };
  31682. /**
  31683. * Directly updates the value of the uniform in the cache AND on the GPU.
  31684. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31685. * @param {number[]|Float32Array} data Flattened data
  31686. */
  31687. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31688. this.updateUniform(uniformName, data, data.length);
  31689. this.update();
  31690. };
  31691. /**
  31692. * Binds this uniform buffer to an effect.
  31693. * @param {Effect} effect
  31694. * @param {string} name Name of the uniform block in the shader.
  31695. */
  31696. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31697. this._currentEffect = effect;
  31698. if (this._noUBO || !this._buffer) {
  31699. return;
  31700. }
  31701. effect.bindUniformBuffer(this._buffer, name);
  31702. };
  31703. /**
  31704. * Disposes the uniform buffer.
  31705. */
  31706. UniformBuffer.prototype.dispose = function () {
  31707. if (this._noUBO) {
  31708. return;
  31709. }
  31710. var index = this._engine._uniformBuffers.indexOf(this);
  31711. if (index !== -1) {
  31712. this._engine._uniformBuffers.splice(index, 1);
  31713. }
  31714. if (!this._buffer) {
  31715. return;
  31716. }
  31717. if (this._engine._releaseBuffer(this._buffer)) {
  31718. this._buffer = null;
  31719. }
  31720. };
  31721. // Pool for avoiding memory leaks
  31722. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31723. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31724. return UniformBuffer;
  31725. }());
  31726. BABYLON.UniformBuffer = UniformBuffer;
  31727. })(BABYLON || (BABYLON = {}));
  31728. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31729. var BABYLON;
  31730. (function (BABYLON) {
  31731. var VertexData = /** @class */ (function () {
  31732. function VertexData() {
  31733. }
  31734. VertexData.prototype.set = function (data, kind) {
  31735. switch (kind) {
  31736. case BABYLON.VertexBuffer.PositionKind:
  31737. this.positions = data;
  31738. break;
  31739. case BABYLON.VertexBuffer.NormalKind:
  31740. this.normals = data;
  31741. break;
  31742. case BABYLON.VertexBuffer.TangentKind:
  31743. this.tangents = data;
  31744. break;
  31745. case BABYLON.VertexBuffer.UVKind:
  31746. this.uvs = data;
  31747. break;
  31748. case BABYLON.VertexBuffer.UV2Kind:
  31749. this.uvs2 = data;
  31750. break;
  31751. case BABYLON.VertexBuffer.UV3Kind:
  31752. this.uvs3 = data;
  31753. break;
  31754. case BABYLON.VertexBuffer.UV4Kind:
  31755. this.uvs4 = data;
  31756. break;
  31757. case BABYLON.VertexBuffer.UV5Kind:
  31758. this.uvs5 = data;
  31759. break;
  31760. case BABYLON.VertexBuffer.UV6Kind:
  31761. this.uvs6 = data;
  31762. break;
  31763. case BABYLON.VertexBuffer.ColorKind:
  31764. this.colors = data;
  31765. break;
  31766. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31767. this.matricesIndices = data;
  31768. break;
  31769. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31770. this.matricesWeights = data;
  31771. break;
  31772. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31773. this.matricesIndicesExtra = data;
  31774. break;
  31775. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31776. this.matricesWeightsExtra = data;
  31777. break;
  31778. }
  31779. };
  31780. /**
  31781. * Associates the vertexData to the passed Mesh.
  31782. * Sets it as updatable or not (default `false`).
  31783. * Returns the VertexData.
  31784. */
  31785. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31786. this._applyTo(mesh, updatable);
  31787. return this;
  31788. };
  31789. /**
  31790. * Associates the vertexData to the passed Geometry.
  31791. * Sets it as updatable or not (default `false`).
  31792. * Returns the VertexData.
  31793. */
  31794. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31795. this._applyTo(geometry, updatable);
  31796. return this;
  31797. };
  31798. /**
  31799. * Updates the associated mesh.
  31800. * Returns the VertexData.
  31801. */
  31802. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31803. this._update(mesh);
  31804. return this;
  31805. };
  31806. /**
  31807. * Updates the associated geometry.
  31808. * Returns the VertexData.
  31809. */
  31810. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31811. this._update(geometry);
  31812. return this;
  31813. };
  31814. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31815. if (updatable === void 0) { updatable = false; }
  31816. if (this.positions) {
  31817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31818. }
  31819. if (this.normals) {
  31820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31821. }
  31822. if (this.tangents) {
  31823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31824. }
  31825. if (this.uvs) {
  31826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31827. }
  31828. if (this.uvs2) {
  31829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31830. }
  31831. if (this.uvs3) {
  31832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31833. }
  31834. if (this.uvs4) {
  31835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31836. }
  31837. if (this.uvs5) {
  31838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31839. }
  31840. if (this.uvs6) {
  31841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31842. }
  31843. if (this.colors) {
  31844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31845. }
  31846. if (this.matricesIndices) {
  31847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31848. }
  31849. if (this.matricesWeights) {
  31850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31851. }
  31852. if (this.matricesIndicesExtra) {
  31853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31854. }
  31855. if (this.matricesWeightsExtra) {
  31856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31857. }
  31858. if (this.indices) {
  31859. meshOrGeometry.setIndices(this.indices, null, updatable);
  31860. }
  31861. return this;
  31862. };
  31863. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31864. if (this.positions) {
  31865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31866. }
  31867. if (this.normals) {
  31868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31869. }
  31870. if (this.tangents) {
  31871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31872. }
  31873. if (this.uvs) {
  31874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31875. }
  31876. if (this.uvs2) {
  31877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31878. }
  31879. if (this.uvs3) {
  31880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31881. }
  31882. if (this.uvs4) {
  31883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31884. }
  31885. if (this.uvs5) {
  31886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31887. }
  31888. if (this.uvs6) {
  31889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31890. }
  31891. if (this.colors) {
  31892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31893. }
  31894. if (this.matricesIndices) {
  31895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31896. }
  31897. if (this.matricesWeights) {
  31898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31899. }
  31900. if (this.matricesIndicesExtra) {
  31901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31902. }
  31903. if (this.matricesWeightsExtra) {
  31904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31905. }
  31906. if (this.indices) {
  31907. meshOrGeometry.setIndices(this.indices, null);
  31908. }
  31909. return this;
  31910. };
  31911. /**
  31912. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31913. * Returns the VertexData.
  31914. */
  31915. VertexData.prototype.transform = function (matrix) {
  31916. var transformed = BABYLON.Vector3.Zero();
  31917. var index;
  31918. if (this.positions) {
  31919. var position = BABYLON.Vector3.Zero();
  31920. for (index = 0; index < this.positions.length; index += 3) {
  31921. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31922. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31923. this.positions[index] = transformed.x;
  31924. this.positions[index + 1] = transformed.y;
  31925. this.positions[index + 2] = transformed.z;
  31926. }
  31927. }
  31928. if (this.normals) {
  31929. var normal = BABYLON.Vector3.Zero();
  31930. for (index = 0; index < this.normals.length; index += 3) {
  31931. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31932. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31933. this.normals[index] = transformed.x;
  31934. this.normals[index + 1] = transformed.y;
  31935. this.normals[index + 2] = transformed.z;
  31936. }
  31937. }
  31938. if (this.tangents) {
  31939. var tangent = BABYLON.Vector4.Zero();
  31940. var tangentTransformed = BABYLON.Vector4.Zero();
  31941. for (index = 0; index < this.tangents.length; index += 4) {
  31942. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31943. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31944. this.tangents[index] = tangentTransformed.x;
  31945. this.tangents[index + 1] = tangentTransformed.y;
  31946. this.tangents[index + 2] = tangentTransformed.z;
  31947. this.tangents[index + 3] = tangentTransformed.w;
  31948. }
  31949. }
  31950. return this;
  31951. };
  31952. /**
  31953. * Merges the passed VertexData into the current one.
  31954. * Returns the modified VertexData.
  31955. */
  31956. VertexData.prototype.merge = function (other) {
  31957. this._validate();
  31958. other._validate();
  31959. if (!this.normals !== !other.normals ||
  31960. !this.tangents !== !other.tangents ||
  31961. !this.uvs !== !other.uvs ||
  31962. !this.uvs2 !== !other.uvs2 ||
  31963. !this.uvs3 !== !other.uvs3 ||
  31964. !this.uvs4 !== !other.uvs4 ||
  31965. !this.uvs5 !== !other.uvs5 ||
  31966. !this.uvs6 !== !other.uvs6 ||
  31967. !this.colors !== !other.colors ||
  31968. !this.matricesIndices !== !other.matricesIndices ||
  31969. !this.matricesWeights !== !other.matricesWeights ||
  31970. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31971. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31972. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31973. }
  31974. if (other.indices) {
  31975. if (!this.indices) {
  31976. this.indices = [];
  31977. }
  31978. var offset = this.positions ? this.positions.length / 3 : 0;
  31979. for (var index = 0; index < other.indices.length; index++) {
  31980. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31981. this.indices.push(other.indices[index] + offset);
  31982. }
  31983. }
  31984. this.positions = this._mergeElement(this.positions, other.positions);
  31985. this.normals = this._mergeElement(this.normals, other.normals);
  31986. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31987. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31988. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31989. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31990. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31991. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31992. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31993. this.colors = this._mergeElement(this.colors, other.colors);
  31994. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31995. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31996. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31997. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31998. return this;
  31999. };
  32000. VertexData.prototype._mergeElement = function (source, other) {
  32001. if (!source) {
  32002. return other;
  32003. }
  32004. if (!other) {
  32005. return source;
  32006. }
  32007. var len = other.length + source.length;
  32008. var isSrcTypedArray = source instanceof Float32Array;
  32009. var isOthTypedArray = other instanceof Float32Array;
  32010. // use non-loop method when the source is Float32Array
  32011. if (isSrcTypedArray) {
  32012. var ret32 = new Float32Array(len);
  32013. ret32.set(source);
  32014. ret32.set(other, source.length);
  32015. return ret32;
  32016. // source is number[], when other is also use concat
  32017. }
  32018. else if (!isOthTypedArray) {
  32019. return source.concat(other);
  32020. // source is a number[], but other is a Float32Array, loop required
  32021. }
  32022. else {
  32023. var ret = source.slice(0); // copy source to a separate array
  32024. for (var i = 0, len = other.length; i < len; i++) {
  32025. ret.push(other[i]);
  32026. }
  32027. return ret;
  32028. }
  32029. };
  32030. VertexData.prototype._validate = function () {
  32031. if (!this.positions) {
  32032. throw new Error("Positions are required");
  32033. }
  32034. var getElementCount = function (kind, values) {
  32035. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32036. if ((values.length % stride) !== 0) {
  32037. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32038. }
  32039. return values.length / stride;
  32040. };
  32041. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32042. var validateElementCount = function (kind, values) {
  32043. var elementCount = getElementCount(kind, values);
  32044. if (elementCount !== positionsElementCount) {
  32045. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32046. }
  32047. };
  32048. if (this.normals)
  32049. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32050. if (this.tangents)
  32051. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32052. if (this.uvs)
  32053. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32054. if (this.uvs2)
  32055. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32056. if (this.uvs3)
  32057. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32058. if (this.uvs4)
  32059. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32060. if (this.uvs5)
  32061. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32062. if (this.uvs6)
  32063. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32064. if (this.colors)
  32065. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32066. if (this.matricesIndices)
  32067. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32068. if (this.matricesWeights)
  32069. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32070. if (this.matricesIndicesExtra)
  32071. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32072. if (this.matricesWeightsExtra)
  32073. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32074. };
  32075. /**
  32076. * Serializes the VertexData.
  32077. * Returns a serialized object.
  32078. */
  32079. VertexData.prototype.serialize = function () {
  32080. var serializationObject = this.serialize();
  32081. if (this.positions) {
  32082. serializationObject.positions = this.positions;
  32083. }
  32084. if (this.normals) {
  32085. serializationObject.normals = this.normals;
  32086. }
  32087. if (this.tangents) {
  32088. serializationObject.tangents = this.tangents;
  32089. }
  32090. if (this.uvs) {
  32091. serializationObject.uvs = this.uvs;
  32092. }
  32093. if (this.uvs2) {
  32094. serializationObject.uvs2 = this.uvs2;
  32095. }
  32096. if (this.uvs3) {
  32097. serializationObject.uvs3 = this.uvs3;
  32098. }
  32099. if (this.uvs4) {
  32100. serializationObject.uvs4 = this.uvs4;
  32101. }
  32102. if (this.uvs5) {
  32103. serializationObject.uvs5 = this.uvs5;
  32104. }
  32105. if (this.uvs6) {
  32106. serializationObject.uvs6 = this.uvs6;
  32107. }
  32108. if (this.colors) {
  32109. serializationObject.colors = this.colors;
  32110. }
  32111. if (this.matricesIndices) {
  32112. serializationObject.matricesIndices = this.matricesIndices;
  32113. serializationObject.matricesIndices._isExpanded = true;
  32114. }
  32115. if (this.matricesWeights) {
  32116. serializationObject.matricesWeights = this.matricesWeights;
  32117. }
  32118. if (this.matricesIndicesExtra) {
  32119. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32120. serializationObject.matricesIndicesExtra._isExpanded = true;
  32121. }
  32122. if (this.matricesWeightsExtra) {
  32123. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32124. }
  32125. serializationObject.indices = this.indices;
  32126. return serializationObject;
  32127. };
  32128. // Statics
  32129. /**
  32130. * Returns the object VertexData associated to the passed mesh.
  32131. */
  32132. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32133. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32134. };
  32135. /**
  32136. * Returns the object VertexData associated to the passed geometry.
  32137. */
  32138. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32139. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32140. };
  32141. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32142. var result = new VertexData();
  32143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32144. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32145. }
  32146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32147. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32148. }
  32149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32150. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32151. }
  32152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32153. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32154. }
  32155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32156. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32157. }
  32158. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32159. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32160. }
  32161. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32162. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32163. }
  32164. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32165. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32166. }
  32167. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32168. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32169. }
  32170. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32171. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32172. }
  32173. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32174. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32175. }
  32176. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32177. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32178. }
  32179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32180. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32181. }
  32182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32183. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32184. }
  32185. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32186. return result;
  32187. };
  32188. /**
  32189. * Creates the vertexData of the Ribbon.
  32190. */
  32191. VertexData.CreateRibbon = function (options) {
  32192. var pathArray = options.pathArray;
  32193. var closeArray = options.closeArray || false;
  32194. var closePath = options.closePath || false;
  32195. var invertUV = options.invertUV || false;
  32196. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32197. var offset = options.offset || defaultOffset;
  32198. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32200. var customUV = options.uvs;
  32201. var customColors = options.colors;
  32202. var positions = [];
  32203. var indices = [];
  32204. var normals = [];
  32205. var uvs = [];
  32206. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32207. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32208. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32209. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32210. var minlg; // minimal length among all paths from pathArray
  32211. var lg = []; // array of path lengths : nb of vertex per path
  32212. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32213. var p; // path iterator
  32214. var i; // point iterator
  32215. var j; // point iterator
  32216. // if single path in pathArray
  32217. if (pathArray.length < 2) {
  32218. var ar1 = [];
  32219. var ar2 = [];
  32220. for (i = 0; i < pathArray[0].length - offset; i++) {
  32221. ar1.push(pathArray[0][i]);
  32222. ar2.push(pathArray[0][i + offset]);
  32223. }
  32224. pathArray = [ar1, ar2];
  32225. }
  32226. // positions and horizontal distances (u)
  32227. var idc = 0;
  32228. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32229. var path;
  32230. var l;
  32231. minlg = pathArray[0].length;
  32232. var vectlg;
  32233. var dist;
  32234. for (p = 0; p < pathArray.length; p++) {
  32235. uTotalDistance[p] = 0;
  32236. us[p] = [0];
  32237. path = pathArray[p];
  32238. l = path.length;
  32239. minlg = (minlg < l) ? minlg : l;
  32240. j = 0;
  32241. while (j < l) {
  32242. positions.push(path[j].x, path[j].y, path[j].z);
  32243. if (j > 0) {
  32244. vectlg = path[j].subtract(path[j - 1]).length();
  32245. dist = vectlg + uTotalDistance[p];
  32246. us[p].push(dist);
  32247. uTotalDistance[p] = dist;
  32248. }
  32249. j++;
  32250. }
  32251. if (closePath) {
  32252. j--;
  32253. positions.push(path[0].x, path[0].y, path[0].z);
  32254. vectlg = path[j].subtract(path[0]).length();
  32255. dist = vectlg + uTotalDistance[p];
  32256. us[p].push(dist);
  32257. uTotalDistance[p] = dist;
  32258. }
  32259. lg[p] = l + closePathCorr;
  32260. idx[p] = idc;
  32261. idc += (l + closePathCorr);
  32262. }
  32263. // vertical distances (v)
  32264. var path1;
  32265. var path2;
  32266. var vertex1 = null;
  32267. var vertex2 = null;
  32268. for (i = 0; i < minlg + closePathCorr; i++) {
  32269. vTotalDistance[i] = 0;
  32270. vs[i] = [0];
  32271. for (p = 0; p < pathArray.length - 1; p++) {
  32272. path1 = pathArray[p];
  32273. path2 = pathArray[p + 1];
  32274. if (i === minlg) {
  32275. vertex1 = path1[0];
  32276. vertex2 = path2[0];
  32277. }
  32278. else {
  32279. vertex1 = path1[i];
  32280. vertex2 = path2[i];
  32281. }
  32282. vectlg = vertex2.subtract(vertex1).length();
  32283. dist = vectlg + vTotalDistance[i];
  32284. vs[i].push(dist);
  32285. vTotalDistance[i] = dist;
  32286. }
  32287. if (closeArray && vertex2 && vertex1) {
  32288. path1 = pathArray[p];
  32289. path2 = pathArray[0];
  32290. if (i === minlg) {
  32291. vertex2 = path2[0];
  32292. }
  32293. vectlg = vertex2.subtract(vertex1).length();
  32294. dist = vectlg + vTotalDistance[i];
  32295. vTotalDistance[i] = dist;
  32296. }
  32297. }
  32298. // uvs
  32299. var u;
  32300. var v;
  32301. if (customUV) {
  32302. for (p = 0; p < customUV.length; p++) {
  32303. uvs.push(customUV[p].x, customUV[p].y);
  32304. }
  32305. }
  32306. else {
  32307. for (p = 0; p < pathArray.length; p++) {
  32308. for (i = 0; i < minlg + closePathCorr; i++) {
  32309. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32310. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32311. if (invertUV) {
  32312. uvs.push(v, u);
  32313. }
  32314. else {
  32315. uvs.push(u, v);
  32316. }
  32317. }
  32318. }
  32319. }
  32320. // indices
  32321. p = 0; // path index
  32322. var pi = 0; // positions array index
  32323. var l1 = lg[p] - 1; // path1 length
  32324. var l2 = lg[p + 1] - 1; // path2 length
  32325. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32326. var shft = idx[1] - idx[0]; // shift
  32327. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32328. while (pi <= min && p < path1nb) {
  32329. // 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
  32330. indices.push(pi, pi + shft, pi + 1);
  32331. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32332. pi += 1;
  32333. if (pi === min) {
  32334. p++;
  32335. if (p === lg.length - 1) {
  32336. shft = idx[0] - idx[p];
  32337. l1 = lg[p] - 1;
  32338. l2 = lg[0] - 1;
  32339. }
  32340. else {
  32341. shft = idx[p + 1] - idx[p];
  32342. l1 = lg[p] - 1;
  32343. l2 = lg[p + 1] - 1;
  32344. }
  32345. pi = idx[p];
  32346. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32347. }
  32348. }
  32349. // normals
  32350. VertexData.ComputeNormals(positions, indices, normals);
  32351. if (closePath) {
  32352. var indexFirst = 0;
  32353. var indexLast = 0;
  32354. for (p = 0; p < pathArray.length; p++) {
  32355. indexFirst = idx[p] * 3;
  32356. if (p + 1 < pathArray.length) {
  32357. indexLast = (idx[p + 1] - 1) * 3;
  32358. }
  32359. else {
  32360. indexLast = normals.length - 3;
  32361. }
  32362. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32363. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32364. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32365. normals[indexLast] = normals[indexFirst];
  32366. normals[indexLast + 1] = normals[indexFirst + 1];
  32367. normals[indexLast + 2] = normals[indexFirst + 2];
  32368. }
  32369. }
  32370. // sides
  32371. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32372. // Colors
  32373. var colors = null;
  32374. if (customColors) {
  32375. colors = new Float32Array(customColors.length * 4);
  32376. for (var c = 0; c < customColors.length; c++) {
  32377. colors[c * 4] = customColors[c].r;
  32378. colors[c * 4 + 1] = customColors[c].g;
  32379. colors[c * 4 + 2] = customColors[c].b;
  32380. colors[c * 4 + 3] = customColors[c].a;
  32381. }
  32382. }
  32383. // Result
  32384. var vertexData = new VertexData();
  32385. var positions32 = new Float32Array(positions);
  32386. var normals32 = new Float32Array(normals);
  32387. var uvs32 = new Float32Array(uvs);
  32388. vertexData.indices = indices;
  32389. vertexData.positions = positions32;
  32390. vertexData.normals = normals32;
  32391. vertexData.uvs = uvs32;
  32392. if (colors) {
  32393. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32394. }
  32395. if (closePath) {
  32396. vertexData._idx = idx;
  32397. }
  32398. return vertexData;
  32399. };
  32400. /**
  32401. * Creates the VertexData of the Box.
  32402. */
  32403. VertexData.CreateBox = function (options) {
  32404. var normalsSource = [
  32405. new BABYLON.Vector3(0, 0, 1),
  32406. new BABYLON.Vector3(0, 0, -1),
  32407. new BABYLON.Vector3(1, 0, 0),
  32408. new BABYLON.Vector3(-1, 0, 0),
  32409. new BABYLON.Vector3(0, 1, 0),
  32410. new BABYLON.Vector3(0, -1, 0)
  32411. ];
  32412. var indices = [];
  32413. var positions = [];
  32414. var normals = [];
  32415. var uvs = [];
  32416. var width = options.width || options.size || 1;
  32417. var height = options.height || options.size || 1;
  32418. var depth = options.depth || options.size || 1;
  32419. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32420. var faceUV = options.faceUV || new Array(6);
  32421. var faceColors = options.faceColors;
  32422. var colors = [];
  32423. // default face colors and UV if undefined
  32424. for (var f = 0; f < 6; f++) {
  32425. if (faceUV[f] === undefined) {
  32426. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32427. }
  32428. if (faceColors && faceColors[f] === undefined) {
  32429. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32430. }
  32431. }
  32432. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32433. // Create each face in turn.
  32434. for (var index = 0; index < normalsSource.length; index++) {
  32435. var normal = normalsSource[index];
  32436. // Get two vectors perpendicular to the face normal and to each other.
  32437. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32438. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32439. // Six indices (two triangles) per face.
  32440. var verticesLength = positions.length / 3;
  32441. indices.push(verticesLength);
  32442. indices.push(verticesLength + 1);
  32443. indices.push(verticesLength + 2);
  32444. indices.push(verticesLength);
  32445. indices.push(verticesLength + 2);
  32446. indices.push(verticesLength + 3);
  32447. // Four vertices per face.
  32448. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32449. positions.push(vertex.x, vertex.y, vertex.z);
  32450. normals.push(normal.x, normal.y, normal.z);
  32451. uvs.push(faceUV[index].z, faceUV[index].w);
  32452. if (faceColors) {
  32453. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32454. }
  32455. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32456. positions.push(vertex.x, vertex.y, vertex.z);
  32457. normals.push(normal.x, normal.y, normal.z);
  32458. uvs.push(faceUV[index].x, faceUV[index].w);
  32459. if (faceColors) {
  32460. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32461. }
  32462. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32463. positions.push(vertex.x, vertex.y, vertex.z);
  32464. normals.push(normal.x, normal.y, normal.z);
  32465. uvs.push(faceUV[index].x, faceUV[index].y);
  32466. if (faceColors) {
  32467. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32468. }
  32469. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32470. positions.push(vertex.x, vertex.y, vertex.z);
  32471. normals.push(normal.x, normal.y, normal.z);
  32472. uvs.push(faceUV[index].z, faceUV[index].y);
  32473. if (faceColors) {
  32474. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32475. }
  32476. }
  32477. // sides
  32478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32479. // Result
  32480. var vertexData = new VertexData();
  32481. vertexData.indices = indices;
  32482. vertexData.positions = positions;
  32483. vertexData.normals = normals;
  32484. vertexData.uvs = uvs;
  32485. if (faceColors) {
  32486. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32487. vertexData.colors = totalColors;
  32488. }
  32489. return vertexData;
  32490. };
  32491. /**
  32492. * Creates the VertexData of the Sphere.
  32493. */
  32494. VertexData.CreateSphere = function (options) {
  32495. var segments = options.segments || 32;
  32496. var diameterX = options.diameterX || options.diameter || 1;
  32497. var diameterY = options.diameterY || options.diameter || 1;
  32498. var diameterZ = options.diameterZ || options.diameter || 1;
  32499. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32500. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32501. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32502. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32503. var totalZRotationSteps = 2 + segments;
  32504. var totalYRotationSteps = 2 * totalZRotationSteps;
  32505. var indices = [];
  32506. var positions = [];
  32507. var normals = [];
  32508. var uvs = [];
  32509. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32510. var normalizedZ = zRotationStep / totalZRotationSteps;
  32511. var angleZ = normalizedZ * Math.PI * slice;
  32512. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32513. var normalizedY = yRotationStep / totalYRotationSteps;
  32514. var angleY = normalizedY * Math.PI * 2 * arc;
  32515. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32516. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32517. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32518. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32519. var vertex = complete.multiply(radius);
  32520. var normal = complete.divide(radius).normalize();
  32521. positions.push(vertex.x, vertex.y, vertex.z);
  32522. normals.push(normal.x, normal.y, normal.z);
  32523. uvs.push(normalizedY, normalizedZ);
  32524. }
  32525. if (zRotationStep > 0) {
  32526. var verticesCount = positions.length / 3;
  32527. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32528. indices.push((firstIndex));
  32529. indices.push((firstIndex + 1));
  32530. indices.push(firstIndex + totalYRotationSteps + 1);
  32531. indices.push((firstIndex + totalYRotationSteps + 1));
  32532. indices.push((firstIndex + 1));
  32533. indices.push((firstIndex + totalYRotationSteps + 2));
  32534. }
  32535. }
  32536. }
  32537. // Sides
  32538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32539. // Result
  32540. var vertexData = new VertexData();
  32541. vertexData.indices = indices;
  32542. vertexData.positions = positions;
  32543. vertexData.normals = normals;
  32544. vertexData.uvs = uvs;
  32545. return vertexData;
  32546. };
  32547. /**
  32548. * Creates the VertexData of the Cylinder or Cone.
  32549. */
  32550. VertexData.CreateCylinder = function (options) {
  32551. var height = options.height || 2;
  32552. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32553. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32554. var tessellation = options.tessellation || 24;
  32555. var subdivisions = options.subdivisions || 1;
  32556. var hasRings = options.hasRings ? true : false;
  32557. var enclose = options.enclose ? true : false;
  32558. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32559. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32560. var faceUV = options.faceUV || new Array(3);
  32561. var faceColors = options.faceColors;
  32562. // default face colors and UV if undefined
  32563. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32564. var ringNb = (hasRings) ? subdivisions : 1;
  32565. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32566. var f;
  32567. for (f = 0; f < surfaceNb; f++) {
  32568. if (faceColors && faceColors[f] === undefined) {
  32569. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32570. }
  32571. }
  32572. for (f = 0; f < surfaceNb; f++) {
  32573. if (faceUV && faceUV[f] === undefined) {
  32574. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32575. }
  32576. }
  32577. var indices = new Array();
  32578. var positions = new Array();
  32579. var normals = new Array();
  32580. var uvs = new Array();
  32581. var colors = new Array();
  32582. var angle_step = Math.PI * 2 * arc / tessellation;
  32583. var angle;
  32584. var h;
  32585. var radius;
  32586. var tan = (diameterBottom - diameterTop) / 2 / height;
  32587. var ringVertex = BABYLON.Vector3.Zero();
  32588. var ringNormal = BABYLON.Vector3.Zero();
  32589. var ringFirstVertex = BABYLON.Vector3.Zero();
  32590. var ringFirstNormal = BABYLON.Vector3.Zero();
  32591. var quadNormal = BABYLON.Vector3.Zero();
  32592. var Y = BABYLON.Axis.Y;
  32593. // positions, normals, uvs
  32594. var i;
  32595. var j;
  32596. var r;
  32597. var ringIdx = 1;
  32598. var s = 1; // surface index
  32599. var cs = 0;
  32600. var v = 0;
  32601. for (i = 0; i <= subdivisions; i++) {
  32602. h = i / subdivisions;
  32603. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32604. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32605. for (r = 0; r < ringIdx; r++) {
  32606. if (hasRings) {
  32607. s += r;
  32608. }
  32609. if (enclose) {
  32610. s += 2 * r;
  32611. }
  32612. for (j = 0; j <= tessellation; j++) {
  32613. angle = j * angle_step;
  32614. // position
  32615. ringVertex.x = Math.cos(-angle) * radius;
  32616. ringVertex.y = -height / 2 + h * height;
  32617. ringVertex.z = Math.sin(-angle) * radius;
  32618. // normal
  32619. if (diameterTop === 0 && i === subdivisions) {
  32620. // if no top cap, reuse former normals
  32621. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32622. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32623. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32624. }
  32625. else {
  32626. ringNormal.x = ringVertex.x;
  32627. ringNormal.z = ringVertex.z;
  32628. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32629. ringNormal.normalize();
  32630. }
  32631. // keep first ring vertex values for enclose
  32632. if (j === 0) {
  32633. ringFirstVertex.copyFrom(ringVertex);
  32634. ringFirstNormal.copyFrom(ringNormal);
  32635. }
  32636. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32637. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32638. if (hasRings) {
  32639. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32640. }
  32641. else {
  32642. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32643. }
  32644. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32645. if (faceColors) {
  32646. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32647. }
  32648. }
  32649. // if enclose, add four vertices and their dedicated normals
  32650. if (arc !== 1 && enclose) {
  32651. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32652. positions.push(0, ringVertex.y, 0);
  32653. positions.push(0, ringVertex.y, 0);
  32654. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32655. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32656. quadNormal.normalize();
  32657. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32658. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32659. quadNormal.normalize();
  32660. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32661. if (hasRings) {
  32662. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32663. }
  32664. else {
  32665. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32666. }
  32667. uvs.push(faceUV[s + 1].x, v);
  32668. uvs.push(faceUV[s + 1].z, v);
  32669. if (hasRings) {
  32670. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32671. }
  32672. else {
  32673. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32674. }
  32675. uvs.push(faceUV[s + 2].x, v);
  32676. uvs.push(faceUV[s + 2].z, v);
  32677. if (faceColors) {
  32678. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32679. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32680. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32681. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32682. }
  32683. }
  32684. if (cs !== s) {
  32685. cs = s;
  32686. }
  32687. }
  32688. }
  32689. // indices
  32690. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32691. var s;
  32692. i = 0;
  32693. for (s = 0; s < subdivisions; s++) {
  32694. var i0 = 0;
  32695. var i1 = 0;
  32696. var i2 = 0;
  32697. var i3 = 0;
  32698. for (j = 0; j < tessellation; j++) {
  32699. i0 = i * (e + 1) + j;
  32700. i1 = (i + 1) * (e + 1) + j;
  32701. i2 = i * (e + 1) + (j + 1);
  32702. i3 = (i + 1) * (e + 1) + (j + 1);
  32703. indices.push(i0, i1, i2);
  32704. indices.push(i3, i2, i1);
  32705. }
  32706. if (arc !== 1 && enclose) {
  32707. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32708. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32709. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32710. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32711. }
  32712. i = (hasRings) ? (i + 2) : (i + 1);
  32713. }
  32714. // Caps
  32715. var createCylinderCap = function (isTop) {
  32716. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32717. if (radius === 0) {
  32718. return;
  32719. }
  32720. // Cap positions, normals & uvs
  32721. var angle;
  32722. var circleVector;
  32723. var i;
  32724. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32725. var c = null;
  32726. if (faceColors) {
  32727. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32728. }
  32729. // cap center
  32730. var vbase = positions.length / 3;
  32731. var offset = isTop ? height / 2 : -height / 2;
  32732. var center = new BABYLON.Vector3(0, offset, 0);
  32733. positions.push(center.x, center.y, center.z);
  32734. normals.push(0, isTop ? 1 : -1, 0);
  32735. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32736. if (c) {
  32737. colors.push(c.r, c.g, c.b, c.a);
  32738. }
  32739. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32740. for (i = 0; i <= tessellation; i++) {
  32741. angle = Math.PI * 2 * i * arc / tessellation;
  32742. var cos = Math.cos(-angle);
  32743. var sin = Math.sin(-angle);
  32744. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32745. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32746. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32747. normals.push(0, isTop ? 1 : -1, 0);
  32748. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32749. if (c) {
  32750. colors.push(c.r, c.g, c.b, c.a);
  32751. }
  32752. }
  32753. // Cap indices
  32754. for (i = 0; i < tessellation; i++) {
  32755. if (!isTop) {
  32756. indices.push(vbase);
  32757. indices.push(vbase + (i + 1));
  32758. indices.push(vbase + (i + 2));
  32759. }
  32760. else {
  32761. indices.push(vbase);
  32762. indices.push(vbase + (i + 2));
  32763. indices.push(vbase + (i + 1));
  32764. }
  32765. }
  32766. };
  32767. // add caps to geometry
  32768. createCylinderCap(false);
  32769. createCylinderCap(true);
  32770. // Sides
  32771. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32772. var vertexData = new VertexData();
  32773. vertexData.indices = indices;
  32774. vertexData.positions = positions;
  32775. vertexData.normals = normals;
  32776. vertexData.uvs = uvs;
  32777. if (faceColors) {
  32778. vertexData.colors = colors;
  32779. }
  32780. return vertexData;
  32781. };
  32782. /**
  32783. * Creates the VertexData of the Torus.
  32784. */
  32785. VertexData.CreateTorus = function (options) {
  32786. var indices = [];
  32787. var positions = [];
  32788. var normals = [];
  32789. var uvs = [];
  32790. var diameter = options.diameter || 1;
  32791. var thickness = options.thickness || 0.5;
  32792. var tessellation = options.tessellation || 16;
  32793. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32794. var stride = tessellation + 1;
  32795. for (var i = 0; i <= tessellation; i++) {
  32796. var u = i / tessellation;
  32797. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32798. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32799. for (var j = 0; j <= tessellation; j++) {
  32800. var v = 1 - j / tessellation;
  32801. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32802. var dx = Math.cos(innerAngle);
  32803. var dy = Math.sin(innerAngle);
  32804. // Create a vertex.
  32805. var normal = new BABYLON.Vector3(dx, dy, 0);
  32806. var position = normal.scale(thickness / 2);
  32807. var textureCoordinate = new BABYLON.Vector2(u, v);
  32808. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32809. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32810. positions.push(position.x, position.y, position.z);
  32811. normals.push(normal.x, normal.y, normal.z);
  32812. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32813. // And create indices for two triangles.
  32814. var nextI = (i + 1) % stride;
  32815. var nextJ = (j + 1) % stride;
  32816. indices.push(i * stride + j);
  32817. indices.push(i * stride + nextJ);
  32818. indices.push(nextI * stride + j);
  32819. indices.push(i * stride + nextJ);
  32820. indices.push(nextI * stride + nextJ);
  32821. indices.push(nextI * stride + j);
  32822. }
  32823. }
  32824. // Sides
  32825. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32826. // Result
  32827. var vertexData = new VertexData();
  32828. vertexData.indices = indices;
  32829. vertexData.positions = positions;
  32830. vertexData.normals = normals;
  32831. vertexData.uvs = uvs;
  32832. return vertexData;
  32833. };
  32834. /**
  32835. * Creates the VertexData of the LineSystem.
  32836. */
  32837. VertexData.CreateLineSystem = function (options) {
  32838. var indices = [];
  32839. var positions = [];
  32840. var lines = options.lines;
  32841. var colors = options.colors;
  32842. var vertexColors = [];
  32843. var idx = 0;
  32844. for (var l = 0; l < lines.length; l++) {
  32845. var points = lines[l];
  32846. for (var index = 0; index < points.length; index++) {
  32847. positions.push(points[index].x, points[index].y, points[index].z);
  32848. if (colors) {
  32849. var color = colors[l];
  32850. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32851. }
  32852. if (index > 0) {
  32853. indices.push(idx - 1);
  32854. indices.push(idx);
  32855. }
  32856. idx++;
  32857. }
  32858. }
  32859. var vertexData = new VertexData();
  32860. vertexData.indices = indices;
  32861. vertexData.positions = positions;
  32862. if (colors) {
  32863. vertexData.colors = vertexColors;
  32864. }
  32865. return vertexData;
  32866. };
  32867. /**
  32868. * Create the VertexData of the DashedLines.
  32869. */
  32870. VertexData.CreateDashedLines = function (options) {
  32871. var dashSize = options.dashSize || 3;
  32872. var gapSize = options.gapSize || 1;
  32873. var dashNb = options.dashNb || 200;
  32874. var points = options.points;
  32875. var positions = new Array();
  32876. var indices = new Array();
  32877. var curvect = BABYLON.Vector3.Zero();
  32878. var lg = 0;
  32879. var nb = 0;
  32880. var shft = 0;
  32881. var dashshft = 0;
  32882. var curshft = 0;
  32883. var idx = 0;
  32884. var i = 0;
  32885. for (i = 0; i < points.length - 1; i++) {
  32886. points[i + 1].subtractToRef(points[i], curvect);
  32887. lg += curvect.length();
  32888. }
  32889. shft = lg / dashNb;
  32890. dashshft = dashSize * shft / (dashSize + gapSize);
  32891. for (i = 0; i < points.length - 1; i++) {
  32892. points[i + 1].subtractToRef(points[i], curvect);
  32893. nb = Math.floor(curvect.length() / shft);
  32894. curvect.normalize();
  32895. for (var j = 0; j < nb; j++) {
  32896. curshft = shft * j;
  32897. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32898. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32899. indices.push(idx, idx + 1);
  32900. idx += 2;
  32901. }
  32902. }
  32903. // Result
  32904. var vertexData = new VertexData();
  32905. vertexData.positions = positions;
  32906. vertexData.indices = indices;
  32907. return vertexData;
  32908. };
  32909. /**
  32910. * Creates the VertexData of the Ground.
  32911. */
  32912. VertexData.CreateGround = function (options) {
  32913. var indices = [];
  32914. var positions = [];
  32915. var normals = [];
  32916. var uvs = [];
  32917. var row, col;
  32918. var width = options.width || 1;
  32919. var height = options.height || 1;
  32920. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32921. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32922. for (row = 0; row <= subdivisionsY; row++) {
  32923. for (col = 0; col <= subdivisionsX; col++) {
  32924. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32925. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32926. positions.push(position.x, position.y, position.z);
  32927. normals.push(normal.x, normal.y, normal.z);
  32928. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32929. }
  32930. }
  32931. for (row = 0; row < subdivisionsY; row++) {
  32932. for (col = 0; col < subdivisionsX; col++) {
  32933. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32934. indices.push(col + 1 + row * (subdivisionsX + 1));
  32935. indices.push(col + row * (subdivisionsX + 1));
  32936. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32937. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32938. indices.push(col + row * (subdivisionsX + 1));
  32939. }
  32940. }
  32941. // Result
  32942. var vertexData = new VertexData();
  32943. vertexData.indices = indices;
  32944. vertexData.positions = positions;
  32945. vertexData.normals = normals;
  32946. vertexData.uvs = uvs;
  32947. return vertexData;
  32948. };
  32949. /**
  32950. * Creates the VertexData of the TiledGround.
  32951. */
  32952. VertexData.CreateTiledGround = function (options) {
  32953. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32954. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32955. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32956. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32957. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32958. var precision = options.precision || { w: 1, h: 1 };
  32959. var indices = new Array();
  32960. var positions = new Array();
  32961. var normals = new Array();
  32962. var uvs = new Array();
  32963. var row, col, tileRow, tileCol;
  32964. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32965. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32966. precision.w = (precision.w < 1) ? 1 : precision.w;
  32967. precision.h = (precision.h < 1) ? 1 : precision.h;
  32968. var tileSize = {
  32969. 'w': (xmax - xmin) / subdivisions.w,
  32970. 'h': (zmax - zmin) / subdivisions.h
  32971. };
  32972. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32973. // Indices
  32974. var base = positions.length / 3;
  32975. var rowLength = precision.w + 1;
  32976. for (row = 0; row < precision.h; row++) {
  32977. for (col = 0; col < precision.w; col++) {
  32978. var square = [
  32979. base + col + row * rowLength,
  32980. base + (col + 1) + row * rowLength,
  32981. base + (col + 1) + (row + 1) * rowLength,
  32982. base + col + (row + 1) * rowLength
  32983. ];
  32984. indices.push(square[1]);
  32985. indices.push(square[2]);
  32986. indices.push(square[3]);
  32987. indices.push(square[0]);
  32988. indices.push(square[1]);
  32989. indices.push(square[3]);
  32990. }
  32991. }
  32992. // Position, normals and uvs
  32993. var position = BABYLON.Vector3.Zero();
  32994. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32995. for (row = 0; row <= precision.h; row++) {
  32996. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32997. for (col = 0; col <= precision.w; col++) {
  32998. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32999. position.y = 0;
  33000. positions.push(position.x, position.y, position.z);
  33001. normals.push(normal.x, normal.y, normal.z);
  33002. uvs.push(col / precision.w, row / precision.h);
  33003. }
  33004. }
  33005. }
  33006. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33007. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33008. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33009. }
  33010. }
  33011. // Result
  33012. var vertexData = new VertexData();
  33013. vertexData.indices = indices;
  33014. vertexData.positions = positions;
  33015. vertexData.normals = normals;
  33016. vertexData.uvs = uvs;
  33017. return vertexData;
  33018. };
  33019. /**
  33020. * Creates the VertexData of the Ground designed from a heightmap.
  33021. */
  33022. VertexData.CreateGroundFromHeightMap = function (options) {
  33023. var indices = [];
  33024. var positions = [];
  33025. var normals = [];
  33026. var uvs = [];
  33027. var row, col;
  33028. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33029. // Vertices
  33030. for (row = 0; row <= options.subdivisions; row++) {
  33031. for (col = 0; col <= options.subdivisions; col++) {
  33032. 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));
  33033. // Compute height
  33034. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33035. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33036. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33037. var r = options.buffer[pos] / 255.0;
  33038. var g = options.buffer[pos + 1] / 255.0;
  33039. var b = options.buffer[pos + 2] / 255.0;
  33040. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33041. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33042. // Add vertex
  33043. positions.push(position.x, position.y, position.z);
  33044. normals.push(0, 0, 0);
  33045. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33046. }
  33047. }
  33048. // Indices
  33049. for (row = 0; row < options.subdivisions; row++) {
  33050. for (col = 0; col < options.subdivisions; col++) {
  33051. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33052. indices.push(col + 1 + row * (options.subdivisions + 1));
  33053. indices.push(col + row * (options.subdivisions + 1));
  33054. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33055. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33056. indices.push(col + row * (options.subdivisions + 1));
  33057. }
  33058. }
  33059. // Normals
  33060. VertexData.ComputeNormals(positions, indices, normals);
  33061. // Result
  33062. var vertexData = new VertexData();
  33063. vertexData.indices = indices;
  33064. vertexData.positions = positions;
  33065. vertexData.normals = normals;
  33066. vertexData.uvs = uvs;
  33067. return vertexData;
  33068. };
  33069. /**
  33070. * Creates the VertexData of the Plane.
  33071. */
  33072. VertexData.CreatePlane = function (options) {
  33073. var indices = [];
  33074. var positions = [];
  33075. var normals = [];
  33076. var uvs = [];
  33077. var width = options.width || options.size || 1;
  33078. var height = options.height || options.size || 1;
  33079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33080. // Vertices
  33081. var halfWidth = width / 2.0;
  33082. var halfHeight = height / 2.0;
  33083. positions.push(-halfWidth, -halfHeight, 0);
  33084. normals.push(0, 0, -1.0);
  33085. uvs.push(0.0, 0.0);
  33086. positions.push(halfWidth, -halfHeight, 0);
  33087. normals.push(0, 0, -1.0);
  33088. uvs.push(1.0, 0.0);
  33089. positions.push(halfWidth, halfHeight, 0);
  33090. normals.push(0, 0, -1.0);
  33091. uvs.push(1.0, 1.0);
  33092. positions.push(-halfWidth, halfHeight, 0);
  33093. normals.push(0, 0, -1.0);
  33094. uvs.push(0.0, 1.0);
  33095. // Indices
  33096. indices.push(0);
  33097. indices.push(1);
  33098. indices.push(2);
  33099. indices.push(0);
  33100. indices.push(2);
  33101. indices.push(3);
  33102. // Sides
  33103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33104. // Result
  33105. var vertexData = new VertexData();
  33106. vertexData.indices = indices;
  33107. vertexData.positions = positions;
  33108. vertexData.normals = normals;
  33109. vertexData.uvs = uvs;
  33110. return vertexData;
  33111. };
  33112. /**
  33113. * Creates the VertexData of the Disc or regular Polygon.
  33114. */
  33115. VertexData.CreateDisc = function (options) {
  33116. var positions = new Array();
  33117. var indices = new Array();
  33118. var normals = new Array();
  33119. var uvs = new Array();
  33120. var radius = options.radius || 0.5;
  33121. var tessellation = options.tessellation || 64;
  33122. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33124. // positions and uvs
  33125. positions.push(0, 0, 0); // disc center first
  33126. uvs.push(0.5, 0.5);
  33127. var theta = Math.PI * 2 * arc;
  33128. var step = theta / tessellation;
  33129. for (var a = 0; a < theta; a += step) {
  33130. var x = Math.cos(a);
  33131. var y = Math.sin(a);
  33132. var u = (x + 1) / 2;
  33133. var v = (1 - y) / 2;
  33134. positions.push(radius * x, radius * y, 0);
  33135. uvs.push(u, v);
  33136. }
  33137. if (arc === 1) {
  33138. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33139. uvs.push(uvs[2], uvs[3]);
  33140. }
  33141. //indices
  33142. var vertexNb = positions.length / 3;
  33143. for (var i = 1; i < vertexNb - 1; i++) {
  33144. indices.push(i + 1, 0, i);
  33145. }
  33146. // result
  33147. VertexData.ComputeNormals(positions, indices, normals);
  33148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33149. var vertexData = new VertexData();
  33150. vertexData.indices = indices;
  33151. vertexData.positions = positions;
  33152. vertexData.normals = normals;
  33153. vertexData.uvs = uvs;
  33154. return vertexData;
  33155. };
  33156. /**
  33157. * Re-creates the VertexData of the Polygon for sideOrientation.
  33158. */
  33159. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33160. var faceUV = fUV || new Array(3);
  33161. var faceColors = fColors;
  33162. var colors = [];
  33163. // default face colors and UV if undefined
  33164. for (var f = 0; f < 3; f++) {
  33165. if (faceUV[f] === undefined) {
  33166. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33167. }
  33168. if (faceColors && faceColors[f] === undefined) {
  33169. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33170. }
  33171. }
  33172. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33173. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33174. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33175. var indices = polygon.getIndices();
  33176. // set face colours and textures
  33177. var idx = 0;
  33178. var face = 0;
  33179. for (var index = 0; index < normals.length; index += 3) {
  33180. //Edge Face no. 1
  33181. if (Math.abs(normals[index + 1]) < 0.001) {
  33182. face = 1;
  33183. }
  33184. //Top Face no. 0
  33185. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33186. face = 0;
  33187. }
  33188. //Bottom Face no. 2
  33189. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33190. face = 2;
  33191. }
  33192. idx = index / 3;
  33193. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33194. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33195. if (faceColors) {
  33196. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33197. }
  33198. }
  33199. // sides
  33200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33201. // Result
  33202. var vertexData = new VertexData();
  33203. vertexData.indices = indices;
  33204. vertexData.positions = positions;
  33205. vertexData.normals = normals;
  33206. vertexData.uvs = uvs;
  33207. if (faceColors) {
  33208. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33209. vertexData.colors = totalColors;
  33210. }
  33211. return vertexData;
  33212. };
  33213. /**
  33214. * Creates the VertexData of the IcoSphere.
  33215. */
  33216. VertexData.CreateIcoSphere = function (options) {
  33217. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33218. var radius = options.radius || 1;
  33219. var flat = (options.flat === undefined) ? true : options.flat;
  33220. var subdivisions = options.subdivisions || 4;
  33221. var radiusX = options.radiusX || radius;
  33222. var radiusY = options.radiusY || radius;
  33223. var radiusZ = options.radiusZ || radius;
  33224. var t = (1 + Math.sqrt(5)) / 2;
  33225. // 12 vertex x,y,z
  33226. var ico_vertices = [
  33227. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33228. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33229. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33230. ];
  33231. // index of 3 vertex makes a face of icopshere
  33232. var ico_indices = [
  33233. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33234. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33235. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33236. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33237. ];
  33238. // vertex for uv have aliased position, not for UV
  33239. var vertices_unalias_id = [
  33240. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33241. // vertex alias
  33242. 0,
  33243. 2,
  33244. 3,
  33245. 3,
  33246. 3,
  33247. 4,
  33248. 7,
  33249. 8,
  33250. 9,
  33251. 9,
  33252. 10,
  33253. 11 // 23: B + 12
  33254. ];
  33255. // uv as integer step (not pixels !)
  33256. var ico_vertexuv = [
  33257. 5, 1, 3, 1, 6, 4, 0, 0,
  33258. 5, 3, 4, 2, 2, 2, 4, 0,
  33259. 2, 0, 1, 1, 6, 0, 6, 2,
  33260. // vertex alias (for same vertex on different faces)
  33261. 0, 4,
  33262. 3, 3,
  33263. 4, 4,
  33264. 3, 1,
  33265. 4, 2,
  33266. 4, 4,
  33267. 0, 2,
  33268. 1, 1,
  33269. 2, 2,
  33270. 3, 3,
  33271. 1, 3,
  33272. 2, 4 // 23: B + 12
  33273. ];
  33274. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33275. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33276. // First island of uv mapping
  33277. // v = 4h 3+ 2
  33278. // v = 3h 9+ 4
  33279. // v = 2h 9+ 5 B
  33280. // v = 1h 9 1 0
  33281. // v = 0h 3 8 7 A
  33282. // u = 0 1 2 3 4 5 6 *a
  33283. // Second island of uv mapping
  33284. // v = 4h 0+ B+ 4+
  33285. // v = 3h A+ 2+
  33286. // v = 2h 7+ 6 3+
  33287. // v = 1h 8+ 3+
  33288. // v = 0h
  33289. // u = 0 1 2 3 4 5 6 *a
  33290. // Face layout on texture UV mapping
  33291. // ============
  33292. // \ 4 /\ 16 / ======
  33293. // \ / \ / /\ 11 /
  33294. // \/ 7 \/ / \ /
  33295. // ======= / 10 \/
  33296. // /\ 17 /\ =======
  33297. // / \ / \ \ 15 /\
  33298. // / 8 \/ 12 \ \ / \
  33299. // ============ \/ 6 \
  33300. // \ 18 /\ ============
  33301. // \ / \ \ 5 /\ 0 /
  33302. // \/ 13 \ \ / \ /
  33303. // ======= \/ 1 \/
  33304. // =============
  33305. // /\ 19 /\ 2 /\
  33306. // / \ / \ / \
  33307. // / 14 \/ 9 \/ 3 \
  33308. // ===================
  33309. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33310. var ustep = 138 / 1024;
  33311. var vstep = 239 / 1024;
  33312. var uoffset = 60 / 1024;
  33313. var voffset = 26 / 1024;
  33314. // Second island should have margin, not to touch the first island
  33315. // avoid any borderline artefact in pixel rounding
  33316. var island_u_offset = -40 / 1024;
  33317. var island_v_offset = +20 / 1024;
  33318. // face is either island 0 or 1 :
  33319. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33320. var island = [
  33321. 0, 0, 0, 0, 1,
  33322. 0, 0, 1, 1, 0,
  33323. 0, 0, 1, 1, 0,
  33324. 0, 1, 1, 1, 0 // 15 - 19
  33325. ];
  33326. var indices = new Array();
  33327. var positions = new Array();
  33328. var normals = new Array();
  33329. var uvs = new Array();
  33330. var current_indice = 0;
  33331. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33332. var face_vertex_pos = new Array(3);
  33333. var face_vertex_uv = new Array(3);
  33334. var v012;
  33335. for (v012 = 0; v012 < 3; v012++) {
  33336. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33337. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33338. }
  33339. // create all with normals
  33340. for (var face = 0; face < 20; face++) {
  33341. // 3 vertex per face
  33342. for (v012 = 0; v012 < 3; v012++) {
  33343. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33344. var v_id = ico_indices[3 * face + v012];
  33345. // vertex have 3D position (x,y,z)
  33346. 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]);
  33347. // Normalize to get normal, then scale to radius
  33348. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33349. // uv Coordinates from vertex ID
  33350. 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);
  33351. }
  33352. // Subdivide the face (interpolate pos, norm, uv)
  33353. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33354. // - norm is linear interpolation of vertex corner normal
  33355. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33356. // - uv is linear interpolation
  33357. //
  33358. // Topology is as below for sub-divide by 2
  33359. // vertex shown as v0,v1,v2
  33360. // interp index is i1 to progress in range [v0,v1[
  33361. // interp index is i2 to progress in range [v0,v2[
  33362. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33363. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33364. //
  33365. //
  33366. // i2 v2
  33367. // ^ ^
  33368. // / / \
  33369. // / / \
  33370. // / / \
  33371. // / / (0,1) \
  33372. // / #---------\
  33373. // / / \ (0,0)'/ \
  33374. // / / \ / \
  33375. // / / \ / \
  33376. // / / (0,0) \ / (1,0) \
  33377. // / #---------#---------\
  33378. // v0 v1
  33379. //
  33380. // --------------------> i1
  33381. //
  33382. // interp of (i1,i2):
  33383. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33384. // along i1 : lerp(x0,x1, i1/(S-i2))
  33385. //
  33386. // centroid of triangle is needed to get help normal computation
  33387. // (c1,c2) are used for centroid location
  33388. var interp_vertex = function (i1, i2, c1, c2) {
  33389. // vertex is interpolated from
  33390. // - face_vertex_pos[0..2]
  33391. // - face_vertex_uv[0..2]
  33392. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33393. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33394. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33395. pos_interp.normalize();
  33396. var vertex_normal;
  33397. if (flat) {
  33398. // in flat mode, recalculate normal as face centroid normal
  33399. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33400. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33401. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33402. }
  33403. else {
  33404. // in smooth mode, recalculate normal from each single vertex position
  33405. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33406. }
  33407. // Vertex normal need correction due to X,Y,Z radius scaling
  33408. vertex_normal.x /= radiusX;
  33409. vertex_normal.y /= radiusY;
  33410. vertex_normal.z /= radiusZ;
  33411. vertex_normal.normalize();
  33412. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33413. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33414. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33415. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33416. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33417. uvs.push(uv_interp.x, uv_interp.y);
  33418. // push each vertex has member of a face
  33419. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33420. indices.push(current_indice);
  33421. current_indice++;
  33422. };
  33423. for (var i2 = 0; i2 < subdivisions; i2++) {
  33424. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33425. // face : (i1,i2) for /\ :
  33426. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33427. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33428. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33429. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33430. if (i1 + i2 + 1 < subdivisions) {
  33431. // face : (i1,i2)' for \/ :
  33432. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33433. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33434. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33435. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33436. }
  33437. }
  33438. }
  33439. }
  33440. // Sides
  33441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33442. // Result
  33443. var vertexData = new VertexData();
  33444. vertexData.indices = indices;
  33445. vertexData.positions = positions;
  33446. vertexData.normals = normals;
  33447. vertexData.uvs = uvs;
  33448. return vertexData;
  33449. };
  33450. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33451. /**
  33452. * Creates the VertexData of the Polyhedron.
  33453. */
  33454. VertexData.CreatePolyhedron = function (options) {
  33455. // provided polyhedron types :
  33456. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33457. // 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)
  33458. var polyhedra = [];
  33459. 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]] };
  33460. 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]] };
  33461. polyhedra[2] = {
  33462. 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]],
  33463. 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]]
  33464. };
  33465. polyhedra[3] = {
  33466. 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]],
  33467. 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]]
  33468. };
  33469. polyhedra[4] = {
  33470. 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]],
  33471. 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]]
  33472. };
  33473. 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]] };
  33474. 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]] };
  33475. 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]] };
  33476. 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]] };
  33477. 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]] };
  33478. 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]] };
  33479. 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]] };
  33480. 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]] };
  33481. 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]] };
  33482. polyhedra[14] = {
  33483. 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]],
  33484. 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]]
  33485. };
  33486. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33487. var size = options.size;
  33488. var sizeX = options.sizeX || size || 1;
  33489. var sizeY = options.sizeY || size || 1;
  33490. var sizeZ = options.sizeZ || size || 1;
  33491. var data = options.custom || polyhedra[type];
  33492. var nbfaces = data.face.length;
  33493. var faceUV = options.faceUV || new Array(nbfaces);
  33494. var faceColors = options.faceColors;
  33495. var flat = (options.flat === undefined) ? true : options.flat;
  33496. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33497. var positions = new Array();
  33498. var indices = new Array();
  33499. var normals = new Array();
  33500. var uvs = new Array();
  33501. var colors = new Array();
  33502. var index = 0;
  33503. var faceIdx = 0; // face cursor in the array "indexes"
  33504. var indexes = new Array();
  33505. var i = 0;
  33506. var f = 0;
  33507. var u, v, ang, x, y, tmp;
  33508. // default face colors and UV if undefined
  33509. if (flat) {
  33510. for (f = 0; f < nbfaces; f++) {
  33511. if (faceColors && faceColors[f] === undefined) {
  33512. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33513. }
  33514. if (faceUV && faceUV[f] === undefined) {
  33515. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33516. }
  33517. }
  33518. }
  33519. if (!flat) {
  33520. for (i = 0; i < data.vertex.length; i++) {
  33521. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33522. uvs.push(0, 0);
  33523. }
  33524. for (f = 0; f < nbfaces; f++) {
  33525. for (i = 0; i < data.face[f].length - 2; i++) {
  33526. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33527. }
  33528. }
  33529. }
  33530. else {
  33531. for (f = 0; f < nbfaces; f++) {
  33532. var fl = data.face[f].length; // number of vertices of the current face
  33533. ang = 2 * Math.PI / fl;
  33534. x = 0.5 * Math.tan(ang / 2);
  33535. y = 0.5;
  33536. // positions, uvs, colors
  33537. for (i = 0; i < fl; i++) {
  33538. // positions
  33539. 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);
  33540. indexes.push(index);
  33541. index++;
  33542. // uvs
  33543. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33544. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33545. uvs.push(u, v);
  33546. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33547. y = x * Math.sin(ang) + y * Math.cos(ang);
  33548. x = tmp;
  33549. // colors
  33550. if (faceColors) {
  33551. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33552. }
  33553. }
  33554. // indices from indexes
  33555. for (i = 0; i < fl - 2; i++) {
  33556. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33557. }
  33558. faceIdx += fl;
  33559. }
  33560. }
  33561. VertexData.ComputeNormals(positions, indices, normals);
  33562. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33563. var vertexData = new VertexData();
  33564. vertexData.positions = positions;
  33565. vertexData.indices = indices;
  33566. vertexData.normals = normals;
  33567. vertexData.uvs = uvs;
  33568. if (faceColors && flat) {
  33569. vertexData.colors = colors;
  33570. }
  33571. return vertexData;
  33572. };
  33573. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33574. /**
  33575. * Creates the VertexData of the Torus Knot.
  33576. */
  33577. VertexData.CreateTorusKnot = function (options) {
  33578. var indices = new Array();
  33579. var positions = new Array();
  33580. var normals = new Array();
  33581. var uvs = new Array();
  33582. var radius = options.radius || 2;
  33583. var tube = options.tube || 0.5;
  33584. var radialSegments = options.radialSegments || 32;
  33585. var tubularSegments = options.tubularSegments || 32;
  33586. var p = options.p || 2;
  33587. var q = options.q || 3;
  33588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33589. // Helper
  33590. var getPos = function (angle) {
  33591. var cu = Math.cos(angle);
  33592. var su = Math.sin(angle);
  33593. var quOverP = q / p * angle;
  33594. var cs = Math.cos(quOverP);
  33595. var tx = radius * (2 + cs) * 0.5 * cu;
  33596. var ty = radius * (2 + cs) * su * 0.5;
  33597. var tz = radius * Math.sin(quOverP) * 0.5;
  33598. return new BABYLON.Vector3(tx, ty, tz);
  33599. };
  33600. // Vertices
  33601. var i;
  33602. var j;
  33603. for (i = 0; i <= radialSegments; i++) {
  33604. var modI = i % radialSegments;
  33605. var u = modI / radialSegments * 2 * p * Math.PI;
  33606. var p1 = getPos(u);
  33607. var p2 = getPos(u + 0.01);
  33608. var tang = p2.subtract(p1);
  33609. var n = p2.add(p1);
  33610. var bitan = BABYLON.Vector3.Cross(tang, n);
  33611. n = BABYLON.Vector3.Cross(bitan, tang);
  33612. bitan.normalize();
  33613. n.normalize();
  33614. for (j = 0; j < tubularSegments; j++) {
  33615. var modJ = j % tubularSegments;
  33616. var v = modJ / tubularSegments * 2 * Math.PI;
  33617. var cx = -tube * Math.cos(v);
  33618. var cy = tube * Math.sin(v);
  33619. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33620. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33621. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33622. uvs.push(i / radialSegments);
  33623. uvs.push(j / tubularSegments);
  33624. }
  33625. }
  33626. for (i = 0; i < radialSegments; i++) {
  33627. for (j = 0; j < tubularSegments; j++) {
  33628. var jNext = (j + 1) % tubularSegments;
  33629. var a = i * tubularSegments + j;
  33630. var b = (i + 1) * tubularSegments + j;
  33631. var c = (i + 1) * tubularSegments + jNext;
  33632. var d = i * tubularSegments + jNext;
  33633. indices.push(d);
  33634. indices.push(b);
  33635. indices.push(a);
  33636. indices.push(d);
  33637. indices.push(c);
  33638. indices.push(b);
  33639. }
  33640. }
  33641. // Normals
  33642. VertexData.ComputeNormals(positions, indices, normals);
  33643. // Sides
  33644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33645. // Result
  33646. var vertexData = new VertexData();
  33647. vertexData.indices = indices;
  33648. vertexData.positions = positions;
  33649. vertexData.normals = normals;
  33650. vertexData.uvs = uvs;
  33651. return vertexData;
  33652. };
  33653. // Tools
  33654. /**
  33655. * @param {any} - positions (number[] or Float32Array)
  33656. * @param {any} - indices (number[] or Uint16Array)
  33657. * @param {any} - normals (number[] or Float32Array)
  33658. * options (optional) :
  33659. * facetPositions : optional array of facet positions (vector3)
  33660. * facetNormals : optional array of facet normals (vector3)
  33661. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33662. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33663. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33664. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33665. * bInfo : optional bounding info, required for facetPartitioning computation
  33666. * useRightHandedSystem: optional boolean to for right handed system computation
  33667. * depthSort : optional boolean to enable the facet depth sort computation
  33668. * distanceTo : optional Vector3 to compute the facet depth from this location
  33669. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33670. */
  33671. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33672. // temporary scalar variables
  33673. var index = 0; // facet index
  33674. var p1p2x = 0.0; // p1p2 vector x coordinate
  33675. var p1p2y = 0.0; // p1p2 vector y coordinate
  33676. var p1p2z = 0.0; // p1p2 vector z coordinate
  33677. var p3p2x = 0.0; // p3p2 vector x coordinate
  33678. var p3p2y = 0.0; // p3p2 vector y coordinate
  33679. var p3p2z = 0.0; // p3p2 vector z coordinate
  33680. var faceNormalx = 0.0; // facet normal x coordinate
  33681. var faceNormaly = 0.0; // facet normal y coordinate
  33682. var faceNormalz = 0.0; // facet normal z coordinate
  33683. var length = 0.0; // facet normal length before normalization
  33684. var v1x = 0; // vector1 x index in the positions array
  33685. var v1y = 0; // vector1 y index in the positions array
  33686. var v1z = 0; // vector1 z index in the positions array
  33687. var v2x = 0; // vector2 x index in the positions array
  33688. var v2y = 0; // vector2 y index in the positions array
  33689. var v2z = 0; // vector2 z index in the positions array
  33690. var v3x = 0; // vector3 x index in the positions array
  33691. var v3y = 0; // vector3 y index in the positions array
  33692. var v3z = 0; // vector3 z index in the positions array
  33693. var computeFacetNormals = false;
  33694. var computeFacetPositions = false;
  33695. var computeFacetPartitioning = false;
  33696. var computeDepthSort = false;
  33697. var faceNormalSign = 1;
  33698. var ratio = 0;
  33699. var distanceTo = null;
  33700. if (options) {
  33701. computeFacetNormals = (options.facetNormals) ? true : false;
  33702. computeFacetPositions = (options.facetPositions) ? true : false;
  33703. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33704. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33705. ratio = options.ratio || 0;
  33706. computeDepthSort = (options.depthSort) ? true : false;
  33707. distanceTo = (options.distanceTo);
  33708. if (computeDepthSort) {
  33709. if (distanceTo === undefined) {
  33710. distanceTo = BABYLON.Vector3.Zero();
  33711. }
  33712. var depthSortedFacets = options.depthSortedFacets;
  33713. }
  33714. }
  33715. // facetPartitioning reinit if needed
  33716. var xSubRatio = 0;
  33717. var ySubRatio = 0;
  33718. var zSubRatio = 0;
  33719. var subSq = 0;
  33720. if (computeFacetPartitioning && options && options.bbSize) {
  33721. var ox = 0; // X partitioning index for facet position
  33722. var oy = 0; // Y partinioning index for facet position
  33723. var oz = 0; // Z partinioning index for facet position
  33724. var b1x = 0; // X partitioning index for facet v1 vertex
  33725. var b1y = 0; // Y partitioning index for facet v1 vertex
  33726. var b1z = 0; // z partitioning index for facet v1 vertex
  33727. var b2x = 0; // X partitioning index for facet v2 vertex
  33728. var b2y = 0; // Y partitioning index for facet v2 vertex
  33729. var b2z = 0; // Z partitioning index for facet v2 vertex
  33730. var b3x = 0; // X partitioning index for facet v3 vertex
  33731. var b3y = 0; // Y partitioning index for facet v3 vertex
  33732. var b3z = 0; // Z partitioning index for facet v3 vertex
  33733. var block_idx_o = 0; // facet barycenter block index
  33734. var block_idx_v1 = 0; // v1 vertex block index
  33735. var block_idx_v2 = 0; // v2 vertex block index
  33736. var block_idx_v3 = 0; // v3 vertex block index
  33737. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33738. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33739. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33740. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33741. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33742. subSq = options.subDiv.max * options.subDiv.max;
  33743. options.facetPartitioning.length = 0;
  33744. }
  33745. // reset the normals
  33746. for (index = 0; index < positions.length; index++) {
  33747. normals[index] = 0.0;
  33748. }
  33749. // Loop : 1 indice triplet = 1 facet
  33750. var nbFaces = (indices.length / 3) | 0;
  33751. for (index = 0; index < nbFaces; index++) {
  33752. // get the indexes of the coordinates of each vertex of the facet
  33753. v1x = indices[index * 3] * 3;
  33754. v1y = v1x + 1;
  33755. v1z = v1x + 2;
  33756. v2x = indices[index * 3 + 1] * 3;
  33757. v2y = v2x + 1;
  33758. v2z = v2x + 2;
  33759. v3x = indices[index * 3 + 2] * 3;
  33760. v3y = v3x + 1;
  33761. v3z = v3x + 2;
  33762. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33763. p1p2y = positions[v1y] - positions[v2y];
  33764. p1p2z = positions[v1z] - positions[v2z];
  33765. p3p2x = positions[v3x] - positions[v2x];
  33766. p3p2y = positions[v3y] - positions[v2y];
  33767. p3p2z = positions[v3z] - positions[v2z];
  33768. // compute the face normal with the cross product
  33769. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33770. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33771. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33772. // normalize this normal and store it in the array facetData
  33773. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33774. length = (length === 0) ? 1.0 : length;
  33775. faceNormalx /= length;
  33776. faceNormaly /= length;
  33777. faceNormalz /= length;
  33778. if (computeFacetNormals && options) {
  33779. options.facetNormals[index].x = faceNormalx;
  33780. options.facetNormals[index].y = faceNormaly;
  33781. options.facetNormals[index].z = faceNormalz;
  33782. }
  33783. if (computeFacetPositions && options) {
  33784. // compute and the facet barycenter coordinates in the array facetPositions
  33785. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33786. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33787. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33788. }
  33789. if (computeFacetPartitioning && options) {
  33790. // store the facet indexes in arrays in the main facetPartitioning array :
  33791. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33792. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33793. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33794. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33795. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33796. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33797. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33798. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33799. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33800. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33801. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33802. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33803. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33804. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33805. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33806. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33807. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33808. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33809. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33810. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33811. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33812. // push each facet index in each block containing the vertex
  33813. options.facetPartitioning[block_idx_v1].push(index);
  33814. if (block_idx_v2 != block_idx_v1) {
  33815. options.facetPartitioning[block_idx_v2].push(index);
  33816. }
  33817. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33818. options.facetPartitioning[block_idx_v3].push(index);
  33819. }
  33820. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33821. options.facetPartitioning[block_idx_o].push(index);
  33822. }
  33823. }
  33824. if (computeDepthSort && options && options.facetPositions) {
  33825. var dsf = depthSortedFacets[index];
  33826. dsf.ind = index * 3;
  33827. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33828. }
  33829. // compute the normals anyway
  33830. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33831. normals[v1y] += faceNormaly;
  33832. normals[v1z] += faceNormalz;
  33833. normals[v2x] += faceNormalx;
  33834. normals[v2y] += faceNormaly;
  33835. normals[v2z] += faceNormalz;
  33836. normals[v3x] += faceNormalx;
  33837. normals[v3y] += faceNormaly;
  33838. normals[v3z] += faceNormalz;
  33839. }
  33840. // last normalization of each normal
  33841. for (index = 0; index < normals.length / 3; index++) {
  33842. faceNormalx = normals[index * 3];
  33843. faceNormaly = normals[index * 3 + 1];
  33844. faceNormalz = normals[index * 3 + 2];
  33845. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33846. length = (length === 0) ? 1.0 : length;
  33847. faceNormalx /= length;
  33848. faceNormaly /= length;
  33849. faceNormalz /= length;
  33850. normals[index * 3] = faceNormalx;
  33851. normals[index * 3 + 1] = faceNormaly;
  33852. normals[index * 3 + 2] = faceNormalz;
  33853. }
  33854. };
  33855. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33856. var li = indices.length;
  33857. var ln = normals.length;
  33858. var i;
  33859. var n;
  33860. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33861. switch (sideOrientation) {
  33862. case BABYLON.Mesh.FRONTSIDE:
  33863. // nothing changed
  33864. break;
  33865. case BABYLON.Mesh.BACKSIDE:
  33866. var tmp;
  33867. // indices
  33868. for (i = 0; i < li; i += 3) {
  33869. tmp = indices[i];
  33870. indices[i] = indices[i + 2];
  33871. indices[i + 2] = tmp;
  33872. }
  33873. // normals
  33874. for (n = 0; n < ln; n++) {
  33875. normals[n] = -normals[n];
  33876. }
  33877. break;
  33878. case BABYLON.Mesh.DOUBLESIDE:
  33879. // positions
  33880. var lp = positions.length;
  33881. var l = lp / 3;
  33882. for (var p = 0; p < lp; p++) {
  33883. positions[lp + p] = positions[p];
  33884. }
  33885. // indices
  33886. for (i = 0; i < li; i += 3) {
  33887. indices[i + li] = indices[i + 2] + l;
  33888. indices[i + 1 + li] = indices[i + 1] + l;
  33889. indices[i + 2 + li] = indices[i] + l;
  33890. }
  33891. // normals
  33892. for (n = 0; n < ln; n++) {
  33893. normals[ln + n] = -normals[n];
  33894. }
  33895. // uvs
  33896. var lu = uvs.length;
  33897. var u = 0;
  33898. for (u = 0; u < lu; u++) {
  33899. uvs[u + lu] = uvs[u];
  33900. }
  33901. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33902. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33903. u = 0;
  33904. for (i = 0; i < lu / 2; i++) {
  33905. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33906. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33907. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33908. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33909. u += 2;
  33910. }
  33911. break;
  33912. }
  33913. };
  33914. /**
  33915. * Creates a new VertexData from the imported parameters.
  33916. */
  33917. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33918. var vertexData = new VertexData();
  33919. // positions
  33920. var positions = parsedVertexData.positions;
  33921. if (positions) {
  33922. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33923. }
  33924. // normals
  33925. var normals = parsedVertexData.normals;
  33926. if (normals) {
  33927. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33928. }
  33929. // tangents
  33930. var tangents = parsedVertexData.tangents;
  33931. if (tangents) {
  33932. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33933. }
  33934. // uvs
  33935. var uvs = parsedVertexData.uvs;
  33936. if (uvs) {
  33937. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33938. }
  33939. // uv2s
  33940. var uv2s = parsedVertexData.uv2s;
  33941. if (uv2s) {
  33942. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33943. }
  33944. // uv3s
  33945. var uv3s = parsedVertexData.uv3s;
  33946. if (uv3s) {
  33947. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33948. }
  33949. // uv4s
  33950. var uv4s = parsedVertexData.uv4s;
  33951. if (uv4s) {
  33952. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33953. }
  33954. // uv5s
  33955. var uv5s = parsedVertexData.uv5s;
  33956. if (uv5s) {
  33957. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33958. }
  33959. // uv6s
  33960. var uv6s = parsedVertexData.uv6s;
  33961. if (uv6s) {
  33962. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33963. }
  33964. // colors
  33965. var colors = parsedVertexData.colors;
  33966. if (colors) {
  33967. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33968. }
  33969. // matricesIndices
  33970. var matricesIndices = parsedVertexData.matricesIndices;
  33971. if (matricesIndices) {
  33972. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33973. }
  33974. // matricesWeights
  33975. var matricesWeights = parsedVertexData.matricesWeights;
  33976. if (matricesWeights) {
  33977. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33978. }
  33979. // indices
  33980. var indices = parsedVertexData.indices;
  33981. if (indices) {
  33982. vertexData.indices = indices;
  33983. }
  33984. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33985. };
  33986. return VertexData;
  33987. }());
  33988. BABYLON.VertexData = VertexData;
  33989. })(BABYLON || (BABYLON = {}));
  33990. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33991. var BABYLON;
  33992. (function (BABYLON) {
  33993. /**
  33994. * Class used to store geometry data (vertex buffers + index buffer)
  33995. */
  33996. var Geometry = /** @class */ (function () {
  33997. /**
  33998. * Creates a new geometry
  33999. * @param id defines the unique ID
  34000. * @param scene defines the hosting scene
  34001. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34002. * @param updatable defines if geometry must be updatable (false by default)
  34003. * @param mesh defines the mesh that will be associated with the geometry
  34004. */
  34005. function Geometry(id, scene, vertexData, updatable, mesh) {
  34006. if (updatable === void 0) { updatable = false; }
  34007. if (mesh === void 0) { mesh = null; }
  34008. /**
  34009. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34010. */
  34011. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34012. this._totalVertices = 0;
  34013. this._isDisposed = false;
  34014. this._indexBufferIsUpdatable = false;
  34015. this.id = id;
  34016. this._engine = scene.getEngine();
  34017. this._meshes = [];
  34018. this._scene = scene;
  34019. //Init vertex buffer cache
  34020. this._vertexBuffers = {};
  34021. this._indices = [];
  34022. this._updatable = updatable;
  34023. // vertexData
  34024. if (vertexData) {
  34025. this.setAllVerticesData(vertexData, updatable);
  34026. }
  34027. else {
  34028. this._totalVertices = 0;
  34029. this._indices = [];
  34030. }
  34031. if (this._engine.getCaps().vertexArrayObject) {
  34032. this._vertexArrayObjects = {};
  34033. }
  34034. // applyToMesh
  34035. if (mesh) {
  34036. if (mesh.getClassName() === "LinesMesh") {
  34037. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34038. this.updateExtend();
  34039. }
  34040. this.applyToMesh(mesh);
  34041. mesh.computeWorldMatrix(true);
  34042. }
  34043. }
  34044. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34045. /**
  34046. * 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
  34047. */
  34048. get: function () {
  34049. return this._boundingBias;
  34050. },
  34051. /**
  34052. * 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
  34053. */
  34054. set: function (value) {
  34055. if (this._boundingBias && this._boundingBias.equals(value)) {
  34056. return;
  34057. }
  34058. this._boundingBias = value.clone();
  34059. this.updateBoundingInfo(true, null);
  34060. },
  34061. enumerable: true,
  34062. configurable: true
  34063. });
  34064. /**
  34065. * Static function used to attach a new empty geometry to a mesh
  34066. * @param mesh defines the mesh to attach the geometry to
  34067. * @returns the new {BABYLON.Geometry}
  34068. */
  34069. Geometry.CreateGeometryForMesh = function (mesh) {
  34070. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34071. geometry.applyToMesh(mesh);
  34072. return geometry;
  34073. };
  34074. Object.defineProperty(Geometry.prototype, "extend", {
  34075. /**
  34076. * Gets the current extend of the geometry
  34077. */
  34078. get: function () {
  34079. return this._extend;
  34080. },
  34081. enumerable: true,
  34082. configurable: true
  34083. });
  34084. /**
  34085. * Gets the hosting scene
  34086. * @returns the hosting {BABYLON.Scene}
  34087. */
  34088. Geometry.prototype.getScene = function () {
  34089. return this._scene;
  34090. };
  34091. /**
  34092. * Gets the hosting engine
  34093. * @returns the hosting {BABYLON.Engine}
  34094. */
  34095. Geometry.prototype.getEngine = function () {
  34096. return this._engine;
  34097. };
  34098. /**
  34099. * Defines if the geometry is ready to use
  34100. * @returns true if the geometry is ready to be used
  34101. */
  34102. Geometry.prototype.isReady = function () {
  34103. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34104. };
  34105. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34106. /**
  34107. * Gets a value indicating that the geometry should not be serialized
  34108. */
  34109. get: function () {
  34110. for (var index = 0; index < this._meshes.length; index++) {
  34111. if (!this._meshes[index].doNotSerialize) {
  34112. return false;
  34113. }
  34114. }
  34115. return true;
  34116. },
  34117. enumerable: true,
  34118. configurable: true
  34119. });
  34120. /** @ignore */
  34121. Geometry.prototype._rebuild = function () {
  34122. if (this._vertexArrayObjects) {
  34123. this._vertexArrayObjects = {};
  34124. }
  34125. // Index buffer
  34126. if (this._meshes.length !== 0 && this._indices) {
  34127. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34128. }
  34129. // Vertex buffers
  34130. for (var key in this._vertexBuffers) {
  34131. var vertexBuffer = this._vertexBuffers[key];
  34132. vertexBuffer._rebuild();
  34133. }
  34134. };
  34135. /**
  34136. * Affects all gemetry data in one call
  34137. * @param vertexData defines the geometry data
  34138. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34139. */
  34140. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34141. vertexData.applyToGeometry(this, updatable);
  34142. this.notifyUpdate();
  34143. };
  34144. /**
  34145. * Set specific vertex data
  34146. * @param kind defines the data kind (Position, normal, etc...)
  34147. * @param data defines the vertex data to use
  34148. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34149. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34150. */
  34151. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34152. if (updatable === void 0) { updatable = false; }
  34153. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34154. this.setVerticesBuffer(buffer);
  34155. };
  34156. /**
  34157. * Removes a specific vertex data
  34158. * @param kind defines the data kind (Position, normal, etc...)
  34159. */
  34160. Geometry.prototype.removeVerticesData = function (kind) {
  34161. if (this._vertexBuffers[kind]) {
  34162. this._vertexBuffers[kind].dispose();
  34163. delete this._vertexBuffers[kind];
  34164. }
  34165. };
  34166. /**
  34167. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34168. * @param buffer defines the vertex buffer to use
  34169. */
  34170. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34171. var kind = buffer.getKind();
  34172. if (this._vertexBuffers[kind]) {
  34173. this._vertexBuffers[kind].dispose();
  34174. }
  34175. this._vertexBuffers[kind] = buffer;
  34176. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34177. var data = buffer.getData();
  34178. var stride = buffer.getStrideSize();
  34179. this._totalVertices = data.length / stride;
  34180. this.updateExtend(data, stride);
  34181. this._resetPointsArrayCache();
  34182. var meshes = this._meshes;
  34183. var numOfMeshes = meshes.length;
  34184. for (var index = 0; index < numOfMeshes; index++) {
  34185. var mesh = meshes[index];
  34186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34187. mesh._createGlobalSubMesh(false);
  34188. mesh.computeWorldMatrix(true);
  34189. }
  34190. }
  34191. this.notifyUpdate(kind);
  34192. if (this._vertexArrayObjects) {
  34193. this._disposeVertexArrayObjects();
  34194. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34195. }
  34196. };
  34197. /**
  34198. * Update a specific vertex buffer
  34199. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34200. * It will do nothing if the buffer is not updatable
  34201. * @param kind defines the data kind (Position, normal, etc...)
  34202. * @param data defines the data to use
  34203. * @param offset defines the offset in the target buffer where to store the data
  34204. */
  34205. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34206. var vertexBuffer = this.getVertexBuffer(kind);
  34207. if (!vertexBuffer) {
  34208. return;
  34209. }
  34210. vertexBuffer.updateDirectly(data, offset);
  34211. this.notifyUpdate(kind);
  34212. };
  34213. /**
  34214. * Update a specific vertex buffer
  34215. * This function will create a new buffer if the current one is not updatable
  34216. * @param kind defines the data kind (Position, normal, etc...)
  34217. * @param data defines the data to use
  34218. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34219. */
  34220. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34221. if (updateExtends === void 0) { updateExtends = false; }
  34222. var vertexBuffer = this.getVertexBuffer(kind);
  34223. if (!vertexBuffer) {
  34224. return;
  34225. }
  34226. vertexBuffer.update(data);
  34227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34228. var stride = vertexBuffer.getStrideSize();
  34229. this._totalVertices = data.length / stride;
  34230. this.updateBoundingInfo(updateExtends, data);
  34231. }
  34232. this.notifyUpdate(kind);
  34233. };
  34234. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34235. if (updateExtends) {
  34236. this.updateExtend(data);
  34237. }
  34238. var meshes = this._meshes;
  34239. var numOfMeshes = meshes.length;
  34240. this._resetPointsArrayCache();
  34241. for (var index = 0; index < numOfMeshes; index++) {
  34242. var mesh = meshes[index];
  34243. if (updateExtends) {
  34244. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34245. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34246. var subMesh = mesh.subMeshes[subIndex];
  34247. subMesh.refreshBoundingInfo();
  34248. }
  34249. }
  34250. }
  34251. };
  34252. /** @ignore */
  34253. Geometry.prototype._bind = function (effect, indexToBind) {
  34254. if (!effect) {
  34255. return;
  34256. }
  34257. if (indexToBind === undefined) {
  34258. indexToBind = this._indexBuffer;
  34259. }
  34260. var vbs = this.getVertexBuffers();
  34261. if (!vbs) {
  34262. return;
  34263. }
  34264. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34265. this._engine.bindBuffers(vbs, indexToBind, effect);
  34266. return;
  34267. }
  34268. // Using VAO
  34269. if (!this._vertexArrayObjects[effect.key]) {
  34270. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34271. }
  34272. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34273. };
  34274. /**
  34275. * Gets total number of vertices
  34276. * @returns the total number of vertices
  34277. */
  34278. Geometry.prototype.getTotalVertices = function () {
  34279. if (!this.isReady()) {
  34280. return 0;
  34281. }
  34282. return this._totalVertices;
  34283. };
  34284. /**
  34285. * Gets a specific vertex data attached to this geometry
  34286. * @param kind defines the data kind (Position, normal, etc...)
  34287. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34288. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34289. * @returns a float array containing vertex data
  34290. */
  34291. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34292. var vertexBuffer = this.getVertexBuffer(kind);
  34293. if (!vertexBuffer) {
  34294. return null;
  34295. }
  34296. var orig = vertexBuffer.getData();
  34297. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34298. return orig;
  34299. }
  34300. else {
  34301. var len = orig.length;
  34302. var copy = [];
  34303. for (var i = 0; i < len; i++) {
  34304. copy.push(orig[i]);
  34305. }
  34306. return copy;
  34307. }
  34308. };
  34309. /**
  34310. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34311. * @param kind defines the data kind (Position, normal, etc...)
  34312. * @returns true if the vertex buffer with the specified kind is updatable
  34313. */
  34314. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34315. var vb = this._vertexBuffers[kind];
  34316. if (!vb) {
  34317. return false;
  34318. }
  34319. return vb.isUpdatable();
  34320. };
  34321. /**
  34322. * Gets a specific vertex buffer
  34323. * @param kind defines the data kind (Position, normal, etc...)
  34324. * @returns a {BABYLON.VertexBuffer}
  34325. */
  34326. Geometry.prototype.getVertexBuffer = function (kind) {
  34327. if (!this.isReady()) {
  34328. return null;
  34329. }
  34330. return this._vertexBuffers[kind];
  34331. };
  34332. /**
  34333. * Returns all vertex buffers
  34334. * @return an object holding all vertex buffers indexed by kind
  34335. */
  34336. Geometry.prototype.getVertexBuffers = function () {
  34337. if (!this.isReady()) {
  34338. return null;
  34339. }
  34340. return this._vertexBuffers;
  34341. };
  34342. /**
  34343. * Gets a boolean indicating if specific vertex buffer is present
  34344. * @param kind defines the data kind (Position, normal, etc...)
  34345. * @returns true if data is present
  34346. */
  34347. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34348. if (!this._vertexBuffers) {
  34349. if (this._delayInfo) {
  34350. return this._delayInfo.indexOf(kind) !== -1;
  34351. }
  34352. return false;
  34353. }
  34354. return this._vertexBuffers[kind] !== undefined;
  34355. };
  34356. /**
  34357. * Gets a list of all attached data kinds (Position, normal, etc...)
  34358. * @returns a list of string containing all kinds
  34359. */
  34360. Geometry.prototype.getVerticesDataKinds = function () {
  34361. var result = [];
  34362. var kind;
  34363. if (!this._vertexBuffers && this._delayInfo) {
  34364. for (kind in this._delayInfo) {
  34365. result.push(kind);
  34366. }
  34367. }
  34368. else {
  34369. for (kind in this._vertexBuffers) {
  34370. result.push(kind);
  34371. }
  34372. }
  34373. return result;
  34374. };
  34375. /**
  34376. * Update index buffer
  34377. * @param indices defines the indices to store in the index buffer
  34378. * @param offset defines the offset in the target buffer where to store the data
  34379. */
  34380. Geometry.prototype.updateIndices = function (indices, offset) {
  34381. if (!this._indexBuffer) {
  34382. return;
  34383. }
  34384. if (!this._indexBufferIsUpdatable) {
  34385. this.setIndices(indices, null, true);
  34386. }
  34387. else {
  34388. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34389. }
  34390. };
  34391. /**
  34392. * Creates a new index buffer
  34393. * @param indices defines the indices to store in the index buffer
  34394. * @param totalVertices defines the total number of vertices (could be null)
  34395. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34396. */
  34397. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34398. if (totalVertices === void 0) { totalVertices = null; }
  34399. if (updatable === void 0) { updatable = false; }
  34400. if (this._indexBuffer) {
  34401. this._engine._releaseBuffer(this._indexBuffer);
  34402. }
  34403. this._disposeVertexArrayObjects();
  34404. this._indices = indices;
  34405. this._indexBufferIsUpdatable = updatable;
  34406. if (this._meshes.length !== 0 && this._indices) {
  34407. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34408. }
  34409. if (totalVertices != undefined) {
  34410. this._totalVertices = totalVertices;
  34411. }
  34412. var meshes = this._meshes;
  34413. var numOfMeshes = meshes.length;
  34414. for (var index = 0; index < numOfMeshes; index++) {
  34415. meshes[index]._createGlobalSubMesh(true);
  34416. }
  34417. this.notifyUpdate();
  34418. };
  34419. /**
  34420. * Return the total number of indices
  34421. * @returns the total number of indices
  34422. */
  34423. Geometry.prototype.getTotalIndices = function () {
  34424. if (!this.isReady()) {
  34425. return 0;
  34426. }
  34427. return this._indices.length;
  34428. };
  34429. /**
  34430. * Gets the index buffer array
  34431. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34432. * @returns the index buffer array
  34433. */
  34434. Geometry.prototype.getIndices = function (copyWhenShared) {
  34435. if (!this.isReady()) {
  34436. return null;
  34437. }
  34438. var orig = this._indices;
  34439. if (!copyWhenShared || this._meshes.length === 1) {
  34440. return orig;
  34441. }
  34442. else {
  34443. var len = orig.length;
  34444. var copy = [];
  34445. for (var i = 0; i < len; i++) {
  34446. copy.push(orig[i]);
  34447. }
  34448. return copy;
  34449. }
  34450. };
  34451. /**
  34452. * Gets the index buffer
  34453. * @return the index buffer
  34454. */
  34455. Geometry.prototype.getIndexBuffer = function () {
  34456. if (!this.isReady()) {
  34457. return null;
  34458. }
  34459. return this._indexBuffer;
  34460. };
  34461. /** @ignore */
  34462. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34463. if (effect === void 0) { effect = null; }
  34464. if (!effect || !this._vertexArrayObjects) {
  34465. return;
  34466. }
  34467. if (this._vertexArrayObjects[effect.key]) {
  34468. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34469. delete this._vertexArrayObjects[effect.key];
  34470. }
  34471. };
  34472. /**
  34473. * Release the associated resources for a specific mesh
  34474. * @param mesh defines the source mesh
  34475. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34476. */
  34477. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34478. var meshes = this._meshes;
  34479. var index = meshes.indexOf(mesh);
  34480. if (index === -1) {
  34481. return;
  34482. }
  34483. meshes.splice(index, 1);
  34484. mesh._geometry = null;
  34485. if (meshes.length === 0 && shouldDispose) {
  34486. this.dispose();
  34487. }
  34488. };
  34489. /**
  34490. * Apply current geometry to a given mesh
  34491. * @param mesh defines the mesh to apply geometry to
  34492. */
  34493. Geometry.prototype.applyToMesh = function (mesh) {
  34494. if (mesh._geometry === this) {
  34495. return;
  34496. }
  34497. var previousGeometry = mesh._geometry;
  34498. if (previousGeometry) {
  34499. previousGeometry.releaseForMesh(mesh);
  34500. }
  34501. var meshes = this._meshes;
  34502. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34503. mesh._geometry = this;
  34504. this._scene.pushGeometry(this);
  34505. meshes.push(mesh);
  34506. if (this.isReady()) {
  34507. this._applyToMesh(mesh);
  34508. }
  34509. else {
  34510. mesh._boundingInfo = this._boundingInfo;
  34511. }
  34512. };
  34513. Geometry.prototype.updateExtend = function (data, stride) {
  34514. if (data === void 0) { data = null; }
  34515. if (!data) {
  34516. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34517. }
  34518. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34519. };
  34520. Geometry.prototype._applyToMesh = function (mesh) {
  34521. var numOfMeshes = this._meshes.length;
  34522. // vertexBuffers
  34523. for (var kind in this._vertexBuffers) {
  34524. if (numOfMeshes === 1) {
  34525. this._vertexBuffers[kind].create();
  34526. }
  34527. var buffer = this._vertexBuffers[kind].getBuffer();
  34528. if (buffer)
  34529. buffer.references = numOfMeshes;
  34530. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34531. if (!this._extend) {
  34532. this.updateExtend(this._vertexBuffers[kind].getData());
  34533. }
  34534. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34535. mesh._createGlobalSubMesh(false);
  34536. //bounding info was just created again, world matrix should be applied again.
  34537. mesh._updateBoundingInfo();
  34538. }
  34539. }
  34540. // indexBuffer
  34541. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34542. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34543. }
  34544. if (this._indexBuffer) {
  34545. this._indexBuffer.references = numOfMeshes;
  34546. }
  34547. };
  34548. Geometry.prototype.notifyUpdate = function (kind) {
  34549. if (this.onGeometryUpdated) {
  34550. this.onGeometryUpdated(this, kind);
  34551. }
  34552. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34553. var mesh = _a[_i];
  34554. mesh._markSubMeshesAsAttributesDirty();
  34555. }
  34556. };
  34557. /**
  34558. * Load the geometry if it was flagged as delay loaded
  34559. * @param scene defines the hosting scene
  34560. * @param onLoaded defines a callback called when the geometry is loaded
  34561. */
  34562. Geometry.prototype.load = function (scene, onLoaded) {
  34563. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34564. return;
  34565. }
  34566. if (this.isReady()) {
  34567. if (onLoaded) {
  34568. onLoaded();
  34569. }
  34570. return;
  34571. }
  34572. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34573. this._queueLoad(scene, onLoaded);
  34574. };
  34575. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34576. var _this = this;
  34577. if (!this.delayLoadingFile) {
  34578. return;
  34579. }
  34580. scene._addPendingData(this);
  34581. scene._loadFile(this.delayLoadingFile, function (data) {
  34582. if (!_this._delayLoadingFunction) {
  34583. return;
  34584. }
  34585. _this._delayLoadingFunction(JSON.parse(data), _this);
  34586. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34587. _this._delayInfo = [];
  34588. scene._removePendingData(_this);
  34589. var meshes = _this._meshes;
  34590. var numOfMeshes = meshes.length;
  34591. for (var index = 0; index < numOfMeshes; index++) {
  34592. _this._applyToMesh(meshes[index]);
  34593. }
  34594. if (onLoaded) {
  34595. onLoaded();
  34596. }
  34597. }, undefined, true);
  34598. };
  34599. /**
  34600. * Invert the geometry to move from a right handed system to a left handed one.
  34601. */
  34602. Geometry.prototype.toLeftHanded = function () {
  34603. // Flip faces
  34604. var tIndices = this.getIndices(false);
  34605. if (tIndices != null && tIndices.length > 0) {
  34606. for (var i = 0; i < tIndices.length; i += 3) {
  34607. var tTemp = tIndices[i + 0];
  34608. tIndices[i + 0] = tIndices[i + 2];
  34609. tIndices[i + 2] = tTemp;
  34610. }
  34611. this.setIndices(tIndices);
  34612. }
  34613. // Negate position.z
  34614. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34615. if (tPositions != null && tPositions.length > 0) {
  34616. for (var i = 0; i < tPositions.length; i += 3) {
  34617. tPositions[i + 2] = -tPositions[i + 2];
  34618. }
  34619. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34620. }
  34621. // Negate normal.z
  34622. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34623. if (tNormals != null && tNormals.length > 0) {
  34624. for (var i = 0; i < tNormals.length; i += 3) {
  34625. tNormals[i + 2] = -tNormals[i + 2];
  34626. }
  34627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34628. }
  34629. };
  34630. // Cache
  34631. /** @ignore */
  34632. Geometry.prototype._resetPointsArrayCache = function () {
  34633. this._positions = null;
  34634. };
  34635. /** @ignore */
  34636. Geometry.prototype._generatePointsArray = function () {
  34637. if (this._positions)
  34638. return true;
  34639. this._positions = [];
  34640. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34641. if (!data) {
  34642. return false;
  34643. }
  34644. for (var index = 0; index < data.length; index += 3) {
  34645. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34646. }
  34647. return true;
  34648. };
  34649. /**
  34650. * Gets a value indicating if the geometry is disposed
  34651. * @returns true if the geometry was disposed
  34652. */
  34653. Geometry.prototype.isDisposed = function () {
  34654. return this._isDisposed;
  34655. };
  34656. Geometry.prototype._disposeVertexArrayObjects = function () {
  34657. if (this._vertexArrayObjects) {
  34658. for (var kind in this._vertexArrayObjects) {
  34659. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34660. }
  34661. this._vertexArrayObjects = {};
  34662. }
  34663. };
  34664. /**
  34665. * Free all associated resources
  34666. */
  34667. Geometry.prototype.dispose = function () {
  34668. var meshes = this._meshes;
  34669. var numOfMeshes = meshes.length;
  34670. var index;
  34671. for (index = 0; index < numOfMeshes; index++) {
  34672. this.releaseForMesh(meshes[index]);
  34673. }
  34674. this._meshes = [];
  34675. this._disposeVertexArrayObjects();
  34676. for (var kind in this._vertexBuffers) {
  34677. this._vertexBuffers[kind].dispose();
  34678. }
  34679. this._vertexBuffers = {};
  34680. this._totalVertices = 0;
  34681. if (this._indexBuffer) {
  34682. this._engine._releaseBuffer(this._indexBuffer);
  34683. }
  34684. this._indexBuffer = null;
  34685. this._indices = [];
  34686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34687. this.delayLoadingFile = null;
  34688. this._delayLoadingFunction = null;
  34689. this._delayInfo = [];
  34690. this._boundingInfo = null;
  34691. this._scene.removeGeometry(this);
  34692. this._isDisposed = true;
  34693. };
  34694. /**
  34695. * Clone the current geometry into a new geometry
  34696. * @param id defines the unique ID of the new geometry
  34697. * @returns a new geometry object
  34698. */
  34699. Geometry.prototype.copy = function (id) {
  34700. var vertexData = new BABYLON.VertexData();
  34701. vertexData.indices = [];
  34702. var indices = this.getIndices();
  34703. if (indices) {
  34704. for (var index = 0; index < indices.length; index++) {
  34705. vertexData.indices.push(indices[index]);
  34706. }
  34707. }
  34708. var updatable = false;
  34709. var stopChecking = false;
  34710. var kind;
  34711. for (kind in this._vertexBuffers) {
  34712. // using slice() to make a copy of the array and not just reference it
  34713. var data = this.getVerticesData(kind);
  34714. if (data instanceof Float32Array) {
  34715. vertexData.set(new Float32Array(data), kind);
  34716. }
  34717. else {
  34718. vertexData.set(data.slice(0), kind);
  34719. }
  34720. if (!stopChecking) {
  34721. var vb = this.getVertexBuffer(kind);
  34722. if (vb) {
  34723. updatable = vb.isUpdatable();
  34724. stopChecking = !updatable;
  34725. }
  34726. }
  34727. }
  34728. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34729. geometry.delayLoadState = this.delayLoadState;
  34730. geometry.delayLoadingFile = this.delayLoadingFile;
  34731. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34732. for (kind in this._delayInfo) {
  34733. geometry._delayInfo = geometry._delayInfo || [];
  34734. geometry._delayInfo.push(kind);
  34735. }
  34736. // Bounding info
  34737. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34738. return geometry;
  34739. };
  34740. /**
  34741. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34742. * @return a JSON representation of the current geometry data (without the vertices data)
  34743. */
  34744. Geometry.prototype.serialize = function () {
  34745. var serializationObject = {};
  34746. serializationObject.id = this.id;
  34747. serializationObject.updatable = this._updatable;
  34748. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34749. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34750. }
  34751. return serializationObject;
  34752. };
  34753. Geometry.prototype.toNumberArray = function (origin) {
  34754. if (Array.isArray(origin)) {
  34755. return origin;
  34756. }
  34757. else {
  34758. return Array.prototype.slice.call(origin);
  34759. }
  34760. };
  34761. /**
  34762. * Serialize all vertices data into a JSON oject
  34763. * @returns a JSON representation of the current geometry data
  34764. */
  34765. Geometry.prototype.serializeVerticeData = function () {
  34766. var serializationObject = this.serialize();
  34767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34768. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34770. serializationObject.positions._updatable = true;
  34771. }
  34772. }
  34773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34774. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34775. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34776. serializationObject.normals._updatable = true;
  34777. }
  34778. }
  34779. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34780. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34781. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34782. serializationObject.tangets._updatable = true;
  34783. }
  34784. }
  34785. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34786. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34787. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34788. serializationObject.uvs._updatable = true;
  34789. }
  34790. }
  34791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34792. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34793. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34794. serializationObject.uv2s._updatable = true;
  34795. }
  34796. }
  34797. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34798. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34799. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34800. serializationObject.uv3s._updatable = true;
  34801. }
  34802. }
  34803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34804. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34805. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34806. serializationObject.uv4s._updatable = true;
  34807. }
  34808. }
  34809. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34810. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34811. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34812. serializationObject.uv5s._updatable = true;
  34813. }
  34814. }
  34815. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34816. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34817. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34818. serializationObject.uv6s._updatable = true;
  34819. }
  34820. }
  34821. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34822. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34823. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34824. serializationObject.colors._updatable = true;
  34825. }
  34826. }
  34827. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34828. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34829. serializationObject.matricesIndices._isExpanded = true;
  34830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34831. serializationObject.matricesIndices._updatable = true;
  34832. }
  34833. }
  34834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34835. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34836. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34837. serializationObject.matricesWeights._updatable = true;
  34838. }
  34839. }
  34840. serializationObject.indices = this.toNumberArray(this.getIndices());
  34841. return serializationObject;
  34842. };
  34843. // Statics
  34844. /**
  34845. * Extracts a clone of a mesh geometry
  34846. * @param mesh defines the source mesh
  34847. * @param id defines the unique ID of the new geometry object
  34848. * @returns the new geometry object
  34849. */
  34850. Geometry.ExtractFromMesh = function (mesh, id) {
  34851. var geometry = mesh._geometry;
  34852. if (!geometry) {
  34853. return null;
  34854. }
  34855. return geometry.copy(id);
  34856. };
  34857. /**
  34858. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34859. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34860. * Be aware Math.random() could cause collisions, but:
  34861. * "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"
  34862. * @returns a string containing a new GUID
  34863. */
  34864. Geometry.RandomId = function () {
  34865. return BABYLON.Tools.RandomId();
  34866. };
  34867. /** @ignore */
  34868. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34869. var scene = mesh.getScene();
  34870. // Geometry
  34871. var geometryId = parsedGeometry.geometryId;
  34872. if (geometryId) {
  34873. var geometry = scene.getGeometryByID(geometryId);
  34874. if (geometry) {
  34875. geometry.applyToMesh(mesh);
  34876. }
  34877. }
  34878. else if (parsedGeometry instanceof ArrayBuffer) {
  34879. var binaryInfo = mesh._binaryInfo;
  34880. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34881. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34882. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34883. }
  34884. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34885. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34886. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34887. }
  34888. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34889. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34890. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34891. }
  34892. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34893. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34894. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34895. }
  34896. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34897. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34898. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34899. }
  34900. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34901. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34902. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34903. }
  34904. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34905. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34906. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34907. }
  34908. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34909. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34910. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34911. }
  34912. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34913. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34914. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34915. }
  34916. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34917. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34918. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34919. }
  34920. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34921. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34922. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34923. }
  34924. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34925. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34927. }
  34928. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34929. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34930. mesh.setIndices(indicesData, null);
  34931. }
  34932. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34933. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34934. mesh.subMeshes = [];
  34935. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34936. var materialIndex = subMeshesData[(i * 5) + 0];
  34937. var verticesStart = subMeshesData[(i * 5) + 1];
  34938. var verticesCount = subMeshesData[(i * 5) + 2];
  34939. var indexStart = subMeshesData[(i * 5) + 3];
  34940. var indexCount = subMeshesData[(i * 5) + 4];
  34941. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34942. }
  34943. }
  34944. }
  34945. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34946. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34947. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34948. if (parsedGeometry.tangents) {
  34949. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34950. }
  34951. if (parsedGeometry.uvs) {
  34952. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34953. }
  34954. if (parsedGeometry.uvs2) {
  34955. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34956. }
  34957. if (parsedGeometry.uvs3) {
  34958. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34959. }
  34960. if (parsedGeometry.uvs4) {
  34961. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34962. }
  34963. if (parsedGeometry.uvs5) {
  34964. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34965. }
  34966. if (parsedGeometry.uvs6) {
  34967. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34968. }
  34969. if (parsedGeometry.colors) {
  34970. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34971. }
  34972. if (parsedGeometry.matricesIndices) {
  34973. if (!parsedGeometry.matricesIndices._isExpanded) {
  34974. var floatIndices = [];
  34975. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34976. var matricesIndex = parsedGeometry.matricesIndices[i];
  34977. floatIndices.push(matricesIndex & 0x000000FF);
  34978. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34979. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34980. floatIndices.push(matricesIndex >> 24);
  34981. }
  34982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34983. }
  34984. else {
  34985. delete parsedGeometry.matricesIndices._isExpanded;
  34986. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34987. }
  34988. }
  34989. if (parsedGeometry.matricesIndicesExtra) {
  34990. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34991. var floatIndices = [];
  34992. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34993. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34994. floatIndices.push(matricesIndex & 0x000000FF);
  34995. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34996. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34997. floatIndices.push(matricesIndex >> 24);
  34998. }
  34999. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35000. }
  35001. else {
  35002. delete parsedGeometry.matricesIndices._isExpanded;
  35003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35004. }
  35005. }
  35006. if (parsedGeometry.matricesWeights) {
  35007. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35008. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35009. }
  35010. if (parsedGeometry.matricesWeightsExtra) {
  35011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35012. }
  35013. mesh.setIndices(parsedGeometry.indices, null);
  35014. }
  35015. // SubMeshes
  35016. if (parsedGeometry.subMeshes) {
  35017. mesh.subMeshes = [];
  35018. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35019. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35020. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35021. }
  35022. }
  35023. // Flat shading
  35024. if (mesh._shouldGenerateFlatShading) {
  35025. mesh.convertToFlatShadedMesh();
  35026. delete mesh._shouldGenerateFlatShading;
  35027. }
  35028. // Update
  35029. mesh.computeWorldMatrix(true);
  35030. // Octree
  35031. var sceneOctree = scene.selectionOctree;
  35032. if (sceneOctree !== undefined && sceneOctree !== null) {
  35033. sceneOctree.addMesh(mesh);
  35034. }
  35035. };
  35036. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35037. var epsilon = 1e-3;
  35038. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35039. return;
  35040. }
  35041. var noInfluenceBoneIndex = 0.0;
  35042. if (parsedGeometry.skeletonId > -1) {
  35043. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35044. if (!skeleton) {
  35045. return;
  35046. }
  35047. noInfluenceBoneIndex = skeleton.bones.length;
  35048. }
  35049. else {
  35050. return;
  35051. }
  35052. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35053. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35054. var matricesWeights = parsedGeometry.matricesWeights;
  35055. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35056. var influencers = parsedGeometry.numBoneInfluencer;
  35057. var size = matricesWeights.length;
  35058. for (var i = 0; i < size; i += 4) {
  35059. var weight = 0.0;
  35060. var firstZeroWeight = -1;
  35061. for (var j = 0; j < 4; j++) {
  35062. var w = matricesWeights[i + j];
  35063. weight += w;
  35064. if (w < epsilon && firstZeroWeight < 0) {
  35065. firstZeroWeight = j;
  35066. }
  35067. }
  35068. if (matricesWeightsExtra) {
  35069. for (var j = 0; j < 4; j++) {
  35070. var w = matricesWeightsExtra[i + j];
  35071. weight += w;
  35072. if (w < epsilon && firstZeroWeight < 0) {
  35073. firstZeroWeight = j + 4;
  35074. }
  35075. }
  35076. }
  35077. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35078. firstZeroWeight = influencers - 1;
  35079. }
  35080. if (weight > epsilon) {
  35081. var mweight = 1.0 / weight;
  35082. for (var j = 0; j < 4; j++) {
  35083. matricesWeights[i + j] *= mweight;
  35084. }
  35085. if (matricesWeightsExtra) {
  35086. for (var j = 0; j < 4; j++) {
  35087. matricesWeightsExtra[i + j] *= mweight;
  35088. }
  35089. }
  35090. }
  35091. else {
  35092. if (firstZeroWeight >= 4) {
  35093. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35094. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35095. }
  35096. else {
  35097. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35098. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35099. }
  35100. }
  35101. }
  35102. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35103. if (parsedGeometry.matricesWeightsExtra) {
  35104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35105. }
  35106. };
  35107. /**
  35108. * Create a new geometry from persisted data (Using .babylon file format)
  35109. * @param parsedVertexData defines the persisted data
  35110. * @param scene defines the hosting scene
  35111. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35112. * @returns the new geometry object
  35113. */
  35114. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35115. if (scene.getGeometryByID(parsedVertexData.id)) {
  35116. return null; // null since geometry could be something else than a box...
  35117. }
  35118. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35119. if (BABYLON.Tags) {
  35120. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35121. }
  35122. if (parsedVertexData.delayLoadingFile) {
  35123. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35124. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35125. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35126. geometry._delayInfo = [];
  35127. if (parsedVertexData.hasUVs) {
  35128. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35129. }
  35130. if (parsedVertexData.hasUVs2) {
  35131. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35132. }
  35133. if (parsedVertexData.hasUVs3) {
  35134. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35135. }
  35136. if (parsedVertexData.hasUVs4) {
  35137. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35138. }
  35139. if (parsedVertexData.hasUVs5) {
  35140. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35141. }
  35142. if (parsedVertexData.hasUVs6) {
  35143. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35144. }
  35145. if (parsedVertexData.hasColors) {
  35146. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35147. }
  35148. if (parsedVertexData.hasMatricesIndices) {
  35149. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35150. }
  35151. if (parsedVertexData.hasMatricesWeights) {
  35152. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35153. }
  35154. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35155. }
  35156. else {
  35157. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35158. }
  35159. scene.pushGeometry(geometry, true);
  35160. return geometry;
  35161. };
  35162. return Geometry;
  35163. }());
  35164. BABYLON.Geometry = Geometry;
  35165. // Primitives
  35166. /// Abstract class
  35167. /**
  35168. * Abstract class used to provide common services for all typed geometries
  35169. */
  35170. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35171. __extends(_PrimitiveGeometry, _super);
  35172. /**
  35173. * Creates a new typed geometry
  35174. * @param id defines the unique ID of the geometry
  35175. * @param scene defines the hosting scene
  35176. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35177. * @param mesh defines the hosting mesh (can be null)
  35178. */
  35179. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35180. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35181. if (mesh === void 0) { mesh = null; }
  35182. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35183. _this._canBeRegenerated = _canBeRegenerated;
  35184. _this._beingRegenerated = true;
  35185. _this.regenerate();
  35186. _this._beingRegenerated = false;
  35187. return _this;
  35188. }
  35189. /**
  35190. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35191. * @returns true if the geometry can be regenerated
  35192. */
  35193. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35194. return this._canBeRegenerated;
  35195. };
  35196. /**
  35197. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35198. */
  35199. _PrimitiveGeometry.prototype.regenerate = function () {
  35200. if (!this._canBeRegenerated) {
  35201. return;
  35202. }
  35203. this._beingRegenerated = true;
  35204. this.setAllVerticesData(this._regenerateVertexData(), false);
  35205. this._beingRegenerated = false;
  35206. };
  35207. /**
  35208. * Clone the geometry
  35209. * @param id defines the unique ID of the new geometry
  35210. * @returns the new geometry
  35211. */
  35212. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35213. return _super.prototype.copy.call(this, id);
  35214. };
  35215. // overrides
  35216. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35217. if (!this._beingRegenerated) {
  35218. return;
  35219. }
  35220. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35221. };
  35222. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35223. if (!this._beingRegenerated) {
  35224. return;
  35225. }
  35226. _super.prototype.setVerticesData.call(this, kind, data, false);
  35227. };
  35228. // to override
  35229. /** @ignore */
  35230. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35231. throw new Error("Abstract method");
  35232. };
  35233. _PrimitiveGeometry.prototype.copy = function (id) {
  35234. throw new Error("Must be overriden in sub-classes.");
  35235. };
  35236. _PrimitiveGeometry.prototype.serialize = function () {
  35237. var serializationObject = _super.prototype.serialize.call(this);
  35238. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35239. return serializationObject;
  35240. };
  35241. return _PrimitiveGeometry;
  35242. }(Geometry));
  35243. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35244. /**
  35245. * Creates a ribbon geometry
  35246. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35247. */
  35248. var RibbonGeometry = /** @class */ (function (_super) {
  35249. __extends(RibbonGeometry, _super);
  35250. /**
  35251. * Creates a ribbon geometry
  35252. * @param id defines the unique ID of the geometry
  35253. * @param scene defines the hosting scene
  35254. * @param pathArray defines the array of paths to use
  35255. * @param closeArray defines if the last path and the first path must be joined
  35256. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35257. * @param offset defines the offset between points
  35258. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35259. * @param mesh defines the hosting mesh (can be null)
  35260. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35261. */
  35262. function RibbonGeometry(id, scene,
  35263. /**
  35264. * Defines the array of paths to use
  35265. */
  35266. pathArray,
  35267. /**
  35268. * Defines if the last and first points of each path in your pathArray must be joined
  35269. */
  35270. closeArray,
  35271. /**
  35272. * Defines if the last and first points of each path in your pathArray must be joined
  35273. */
  35274. closePath,
  35275. /**
  35276. * Defines the offset between points
  35277. */
  35278. offset, canBeRegenerated, mesh,
  35279. /**
  35280. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35281. */
  35282. side) {
  35283. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35284. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35285. _this.pathArray = pathArray;
  35286. _this.closeArray = closeArray;
  35287. _this.closePath = closePath;
  35288. _this.offset = offset;
  35289. _this.side = side;
  35290. return _this;
  35291. }
  35292. /** @ignore */
  35293. RibbonGeometry.prototype._regenerateVertexData = function () {
  35294. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35295. };
  35296. RibbonGeometry.prototype.copy = function (id) {
  35297. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35298. };
  35299. return RibbonGeometry;
  35300. }(_PrimitiveGeometry));
  35301. BABYLON.RibbonGeometry = RibbonGeometry;
  35302. /**
  35303. * Creates a box geometry
  35304. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35305. */
  35306. var BoxGeometry = /** @class */ (function (_super) {
  35307. __extends(BoxGeometry, _super);
  35308. /**
  35309. * Creates a box geometry
  35310. * @param id defines the unique ID of the geometry
  35311. * @param scene defines the hosting scene
  35312. * @param size defines the zise of the box (width, height and depth are the same)
  35313. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35314. * @param mesh defines the hosting mesh (can be null)
  35315. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35316. */
  35317. function BoxGeometry(id, scene,
  35318. /**
  35319. * Defines the zise of the box (width, height and depth are the same)
  35320. */
  35321. size, canBeRegenerated, mesh,
  35322. /**
  35323. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35324. */
  35325. side) {
  35326. if (mesh === void 0) { mesh = null; }
  35327. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35328. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35329. _this.size = size;
  35330. _this.side = side;
  35331. return _this;
  35332. }
  35333. BoxGeometry.prototype._regenerateVertexData = function () {
  35334. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35335. };
  35336. BoxGeometry.prototype.copy = function (id) {
  35337. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35338. };
  35339. BoxGeometry.prototype.serialize = function () {
  35340. var serializationObject = _super.prototype.serialize.call(this);
  35341. serializationObject.size = this.size;
  35342. return serializationObject;
  35343. };
  35344. BoxGeometry.Parse = function (parsedBox, scene) {
  35345. if (scene.getGeometryByID(parsedBox.id)) {
  35346. return null; // null since geometry could be something else than a box...
  35347. }
  35348. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35349. if (BABYLON.Tags) {
  35350. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35351. }
  35352. scene.pushGeometry(box, true);
  35353. return box;
  35354. };
  35355. return BoxGeometry;
  35356. }(_PrimitiveGeometry));
  35357. BABYLON.BoxGeometry = BoxGeometry;
  35358. /**
  35359. * Creates a sphere geometry
  35360. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35361. */
  35362. var SphereGeometry = /** @class */ (function (_super) {
  35363. __extends(SphereGeometry, _super);
  35364. /**
  35365. * Create a new sphere geometry
  35366. * @param id defines the unique ID of the geometry
  35367. * @param scene defines the hosting scene
  35368. * @param segments defines the number of segments to use to create the sphere
  35369. * @param diameter defines the diameter of the sphere
  35370. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35371. * @param mesh defines the hosting mesh (can be null)
  35372. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35373. */
  35374. function SphereGeometry(id, scene,
  35375. /**
  35376. * Defines the number of segments to use to create the sphere
  35377. */
  35378. segments,
  35379. /**
  35380. * Defines the diameter of the sphere
  35381. */
  35382. diameter, canBeRegenerated, mesh,
  35383. /**
  35384. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35385. */
  35386. side) {
  35387. if (mesh === void 0) { mesh = null; }
  35388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35390. _this.segments = segments;
  35391. _this.diameter = diameter;
  35392. _this.side = side;
  35393. return _this;
  35394. }
  35395. SphereGeometry.prototype._regenerateVertexData = function () {
  35396. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35397. };
  35398. SphereGeometry.prototype.copy = function (id) {
  35399. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35400. };
  35401. SphereGeometry.prototype.serialize = function () {
  35402. var serializationObject = _super.prototype.serialize.call(this);
  35403. serializationObject.segments = this.segments;
  35404. serializationObject.diameter = this.diameter;
  35405. return serializationObject;
  35406. };
  35407. SphereGeometry.Parse = function (parsedSphere, scene) {
  35408. if (scene.getGeometryByID(parsedSphere.id)) {
  35409. return null; // null since geometry could be something else than a sphere...
  35410. }
  35411. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35412. if (BABYLON.Tags) {
  35413. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35414. }
  35415. scene.pushGeometry(sphere, true);
  35416. return sphere;
  35417. };
  35418. return SphereGeometry;
  35419. }(_PrimitiveGeometry));
  35420. BABYLON.SphereGeometry = SphereGeometry;
  35421. /**
  35422. * Creates a disc geometry
  35423. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35424. */
  35425. var DiscGeometry = /** @class */ (function (_super) {
  35426. __extends(DiscGeometry, _super);
  35427. /**
  35428. * Creates a new disc geometry
  35429. * @param id defines the unique ID of the geometry
  35430. * @param scene defines the hosting scene
  35431. * @param radius defines the radius of the disc
  35432. * @param tessellation defines the tesselation factor to apply to the disc
  35433. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35434. * @param mesh defines the hosting mesh (can be null)
  35435. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35436. */
  35437. function DiscGeometry(id, scene,
  35438. /**
  35439. * Defines the radius of the disc
  35440. */
  35441. radius,
  35442. /**
  35443. * Defines the tesselation factor to apply to the disc
  35444. */
  35445. tessellation, canBeRegenerated, mesh,
  35446. /**
  35447. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35448. */
  35449. side) {
  35450. if (mesh === void 0) { mesh = null; }
  35451. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35453. _this.radius = radius;
  35454. _this.tessellation = tessellation;
  35455. _this.side = side;
  35456. return _this;
  35457. }
  35458. DiscGeometry.prototype._regenerateVertexData = function () {
  35459. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35460. };
  35461. DiscGeometry.prototype.copy = function (id) {
  35462. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35463. };
  35464. return DiscGeometry;
  35465. }(_PrimitiveGeometry));
  35466. BABYLON.DiscGeometry = DiscGeometry;
  35467. /**
  35468. * Creates a new cylinder geometry
  35469. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35470. */
  35471. var CylinderGeometry = /** @class */ (function (_super) {
  35472. __extends(CylinderGeometry, _super);
  35473. /**
  35474. * Creates a new cylinder geometry
  35475. * @param id defines the unique ID of the geometry
  35476. * @param scene defines the hosting scene
  35477. * @param height defines the height of the cylinder
  35478. * @param diameterTop defines the diameter of the cylinder's top cap
  35479. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35480. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35481. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35482. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35483. * @param mesh defines the hosting mesh (can be null)
  35484. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35485. */
  35486. function CylinderGeometry(id, scene,
  35487. /**
  35488. * Defines the height of the cylinder
  35489. */
  35490. height,
  35491. /**
  35492. * Defines the diameter of the cylinder's top cap
  35493. */
  35494. diameterTop,
  35495. /**
  35496. * Defines the diameter of the cylinder's bottom cap
  35497. */
  35498. diameterBottom,
  35499. /**
  35500. * Defines the tessellation factor to apply to the cylinder
  35501. */
  35502. tessellation,
  35503. /**
  35504. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35505. */
  35506. subdivisions, canBeRegenerated, mesh,
  35507. /**
  35508. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35509. */
  35510. side) {
  35511. if (subdivisions === void 0) { subdivisions = 1; }
  35512. if (mesh === void 0) { mesh = null; }
  35513. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35514. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35515. _this.height = height;
  35516. _this.diameterTop = diameterTop;
  35517. _this.diameterBottom = diameterBottom;
  35518. _this.tessellation = tessellation;
  35519. _this.subdivisions = subdivisions;
  35520. _this.side = side;
  35521. return _this;
  35522. }
  35523. CylinderGeometry.prototype._regenerateVertexData = function () {
  35524. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35525. };
  35526. CylinderGeometry.prototype.copy = function (id) {
  35527. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35528. };
  35529. CylinderGeometry.prototype.serialize = function () {
  35530. var serializationObject = _super.prototype.serialize.call(this);
  35531. serializationObject.height = this.height;
  35532. serializationObject.diameterTop = this.diameterTop;
  35533. serializationObject.diameterBottom = this.diameterBottom;
  35534. serializationObject.tessellation = this.tessellation;
  35535. return serializationObject;
  35536. };
  35537. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35538. if (scene.getGeometryByID(parsedCylinder.id)) {
  35539. return null; // null since geometry could be something else than a cylinder...
  35540. }
  35541. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35542. if (BABYLON.Tags) {
  35543. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35544. }
  35545. scene.pushGeometry(cylinder, true);
  35546. return cylinder;
  35547. };
  35548. return CylinderGeometry;
  35549. }(_PrimitiveGeometry));
  35550. BABYLON.CylinderGeometry = CylinderGeometry;
  35551. /**
  35552. * Creates a new torus geometry
  35553. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35554. */
  35555. var TorusGeometry = /** @class */ (function (_super) {
  35556. __extends(TorusGeometry, _super);
  35557. /**
  35558. * Creates a new torus geometry
  35559. * @param id defines the unique ID of the geometry
  35560. * @param scene defines the hosting scene
  35561. * @param diameter defines the diameter of the torus
  35562. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35563. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35564. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35565. * @param mesh defines the hosting mesh (can be null)
  35566. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35567. */
  35568. function TorusGeometry(id, scene,
  35569. /**
  35570. * Defines the diameter of the torus
  35571. */
  35572. diameter,
  35573. /**
  35574. * Defines the thickness of the torus (ie. internal diameter)
  35575. */
  35576. thickness,
  35577. /**
  35578. * Defines the tesselation factor to apply to the torus
  35579. */
  35580. tessellation, canBeRegenerated, mesh,
  35581. /**
  35582. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35583. */
  35584. side) {
  35585. if (mesh === void 0) { mesh = null; }
  35586. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35587. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35588. _this.diameter = diameter;
  35589. _this.thickness = thickness;
  35590. _this.tessellation = tessellation;
  35591. _this.side = side;
  35592. return _this;
  35593. }
  35594. TorusGeometry.prototype._regenerateVertexData = function () {
  35595. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35596. };
  35597. TorusGeometry.prototype.copy = function (id) {
  35598. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35599. };
  35600. TorusGeometry.prototype.serialize = function () {
  35601. var serializationObject = _super.prototype.serialize.call(this);
  35602. serializationObject.diameter = this.diameter;
  35603. serializationObject.thickness = this.thickness;
  35604. serializationObject.tessellation = this.tessellation;
  35605. return serializationObject;
  35606. };
  35607. TorusGeometry.Parse = function (parsedTorus, scene) {
  35608. if (scene.getGeometryByID(parsedTorus.id)) {
  35609. return null; // null since geometry could be something else than a torus...
  35610. }
  35611. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35612. if (BABYLON.Tags) {
  35613. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35614. }
  35615. scene.pushGeometry(torus, true);
  35616. return torus;
  35617. };
  35618. return TorusGeometry;
  35619. }(_PrimitiveGeometry));
  35620. BABYLON.TorusGeometry = TorusGeometry;
  35621. /**
  35622. * Creates a new ground geometry
  35623. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35624. */
  35625. var GroundGeometry = /** @class */ (function (_super) {
  35626. __extends(GroundGeometry, _super);
  35627. /**
  35628. * Creates a new ground geometry
  35629. * @param id defines the unique ID of the geometry
  35630. * @param scene defines the hosting scene
  35631. * @param width defines the width of the ground
  35632. * @param height defines the height of the ground
  35633. * @param subdivisions defines the subdivisions to apply to the ground
  35634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35635. * @param mesh defines the hosting mesh (can be null)
  35636. */
  35637. function GroundGeometry(id, scene,
  35638. /**
  35639. * Defines the width of the ground
  35640. */
  35641. width,
  35642. /**
  35643. * Defines the height of the ground
  35644. */
  35645. height,
  35646. /**
  35647. * Defines the subdivisions to apply to the ground
  35648. */
  35649. subdivisions, canBeRegenerated, mesh) {
  35650. if (mesh === void 0) { mesh = null; }
  35651. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35652. _this.width = width;
  35653. _this.height = height;
  35654. _this.subdivisions = subdivisions;
  35655. return _this;
  35656. }
  35657. GroundGeometry.prototype._regenerateVertexData = function () {
  35658. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35659. };
  35660. GroundGeometry.prototype.copy = function (id) {
  35661. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35662. };
  35663. GroundGeometry.prototype.serialize = function () {
  35664. var serializationObject = _super.prototype.serialize.call(this);
  35665. serializationObject.width = this.width;
  35666. serializationObject.height = this.height;
  35667. serializationObject.subdivisions = this.subdivisions;
  35668. return serializationObject;
  35669. };
  35670. GroundGeometry.Parse = function (parsedGround, scene) {
  35671. if (scene.getGeometryByID(parsedGround.id)) {
  35672. return null; // null since geometry could be something else than a ground...
  35673. }
  35674. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35675. if (BABYLON.Tags) {
  35676. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35677. }
  35678. scene.pushGeometry(ground, true);
  35679. return ground;
  35680. };
  35681. return GroundGeometry;
  35682. }(_PrimitiveGeometry));
  35683. BABYLON.GroundGeometry = GroundGeometry;
  35684. /**
  35685. * Creates a tiled ground geometry
  35686. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35687. */
  35688. var TiledGroundGeometry = /** @class */ (function (_super) {
  35689. __extends(TiledGroundGeometry, _super);
  35690. /**
  35691. * Creates a tiled ground geometry
  35692. * @param id defines the unique ID of the geometry
  35693. * @param scene defines the hosting scene
  35694. * @param xmin defines the minimum value on X axis
  35695. * @param zmin defines the minimum value on Z axis
  35696. * @param xmax defines the maximum value on X axis
  35697. * @param zmax defines the maximum value on Z axis
  35698. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35699. * @param precision defines the precision to use when computing the tiles
  35700. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35701. * @param mesh defines the hosting mesh (can be null)
  35702. */
  35703. function TiledGroundGeometry(id, scene,
  35704. /**
  35705. * Defines the minimum value on X axis
  35706. */
  35707. xmin,
  35708. /**
  35709. * Defines the minimum value on Z axis
  35710. */
  35711. zmin,
  35712. /**
  35713. * Defines the maximum value on X axis
  35714. */
  35715. xmax,
  35716. /**
  35717. * Defines the maximum value on Z axis
  35718. */
  35719. zmax,
  35720. /**
  35721. * Defines the subdivisions to apply to the ground
  35722. */
  35723. subdivisions,
  35724. /**
  35725. * Defines the precision to use when computing the tiles
  35726. */
  35727. precision, canBeRegenerated, mesh) {
  35728. if (mesh === void 0) { mesh = null; }
  35729. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35730. _this.xmin = xmin;
  35731. _this.zmin = zmin;
  35732. _this.xmax = xmax;
  35733. _this.zmax = zmax;
  35734. _this.subdivisions = subdivisions;
  35735. _this.precision = precision;
  35736. return _this;
  35737. }
  35738. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35739. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35740. };
  35741. TiledGroundGeometry.prototype.copy = function (id) {
  35742. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35743. };
  35744. return TiledGroundGeometry;
  35745. }(_PrimitiveGeometry));
  35746. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35747. /**
  35748. * Creates a plane geometry
  35749. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35750. */
  35751. var PlaneGeometry = /** @class */ (function (_super) {
  35752. __extends(PlaneGeometry, _super);
  35753. /**
  35754. * Creates a plane geometry
  35755. * @param id defines the unique ID of the geometry
  35756. * @param scene defines the hosting scene
  35757. * @param size defines the size of the plane (width === height)
  35758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35759. * @param mesh defines the hosting mesh (can be null)
  35760. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35761. */
  35762. function PlaneGeometry(id, scene,
  35763. /**
  35764. * Defines the size of the plane (width === height)
  35765. */
  35766. size, canBeRegenerated, mesh,
  35767. /**
  35768. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35769. */
  35770. side) {
  35771. if (mesh === void 0) { mesh = null; }
  35772. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35773. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35774. _this.size = size;
  35775. _this.side = side;
  35776. return _this;
  35777. }
  35778. PlaneGeometry.prototype._regenerateVertexData = function () {
  35779. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35780. };
  35781. PlaneGeometry.prototype.copy = function (id) {
  35782. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35783. };
  35784. PlaneGeometry.prototype.serialize = function () {
  35785. var serializationObject = _super.prototype.serialize.call(this);
  35786. serializationObject.size = this.size;
  35787. return serializationObject;
  35788. };
  35789. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35790. if (scene.getGeometryByID(parsedPlane.id)) {
  35791. return null; // null since geometry could be something else than a ground...
  35792. }
  35793. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35794. if (BABYLON.Tags) {
  35795. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35796. }
  35797. scene.pushGeometry(plane, true);
  35798. return plane;
  35799. };
  35800. return PlaneGeometry;
  35801. }(_PrimitiveGeometry));
  35802. BABYLON.PlaneGeometry = PlaneGeometry;
  35803. /**
  35804. * Creates a torus knot geometry
  35805. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35806. */
  35807. var TorusKnotGeometry = /** @class */ (function (_super) {
  35808. __extends(TorusKnotGeometry, _super);
  35809. /**
  35810. * Creates a torus knot geometry
  35811. * @param id defines the unique ID of the geometry
  35812. * @param scene defines the hosting scene
  35813. * @param radius defines the radius of the torus knot
  35814. * @param tube defines the thickness of the torus knot tube
  35815. * @param radialSegments defines the number of radial segments
  35816. * @param tubularSegments defines the number of tubular segments
  35817. * @param p defines the first number of windings
  35818. * @param q defines the second number of windings
  35819. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35820. * @param mesh defines the hosting mesh (can be null)
  35821. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35822. */
  35823. function TorusKnotGeometry(id, scene,
  35824. /**
  35825. * Defines the radius of the torus knot
  35826. */
  35827. radius,
  35828. /**
  35829. * Defines the thickness of the torus knot tube
  35830. */
  35831. tube,
  35832. /**
  35833. * Defines the number of radial segments
  35834. */
  35835. radialSegments,
  35836. /**
  35837. * Defines the number of tubular segments
  35838. */
  35839. tubularSegments,
  35840. /**
  35841. * Defines the first number of windings
  35842. */
  35843. p,
  35844. /**
  35845. * Defines the second number of windings
  35846. */
  35847. q, canBeRegenerated, mesh,
  35848. /**
  35849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. side) {
  35852. if (mesh === void 0) { mesh = null; }
  35853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35854. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35855. _this.radius = radius;
  35856. _this.tube = tube;
  35857. _this.radialSegments = radialSegments;
  35858. _this.tubularSegments = tubularSegments;
  35859. _this.p = p;
  35860. _this.q = q;
  35861. _this.side = side;
  35862. return _this;
  35863. }
  35864. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35865. 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 });
  35866. };
  35867. TorusKnotGeometry.prototype.copy = function (id) {
  35868. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35869. };
  35870. TorusKnotGeometry.prototype.serialize = function () {
  35871. var serializationObject = _super.prototype.serialize.call(this);
  35872. serializationObject.radius = this.radius;
  35873. serializationObject.tube = this.tube;
  35874. serializationObject.radialSegments = this.radialSegments;
  35875. serializationObject.tubularSegments = this.tubularSegments;
  35876. serializationObject.p = this.p;
  35877. serializationObject.q = this.q;
  35878. return serializationObject;
  35879. };
  35880. ;
  35881. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35882. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35883. return null; // null since geometry could be something else than a ground...
  35884. }
  35885. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35886. if (BABYLON.Tags) {
  35887. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35888. }
  35889. scene.pushGeometry(torusKnot, true);
  35890. return torusKnot;
  35891. };
  35892. return TorusKnotGeometry;
  35893. }(_PrimitiveGeometry));
  35894. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35895. //}
  35896. })(BABYLON || (BABYLON = {}));
  35897. //# sourceMappingURL=babylon.geometry.js.map
  35898. var BABYLON;
  35899. (function (BABYLON) {
  35900. /**
  35901. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35902. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35903. */
  35904. var PostProcessManager = /** @class */ (function () {
  35905. /**
  35906. * Creates a new instance of @see PostProcess
  35907. * @param scene The scene that the post process is associated with.
  35908. */
  35909. function PostProcessManager(scene) {
  35910. this._vertexBuffers = {};
  35911. this._scene = scene;
  35912. }
  35913. PostProcessManager.prototype._prepareBuffers = function () {
  35914. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35915. return;
  35916. }
  35917. // VBO
  35918. var vertices = [];
  35919. vertices.push(1, 1);
  35920. vertices.push(-1, 1);
  35921. vertices.push(-1, -1);
  35922. vertices.push(1, -1);
  35923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35924. this._buildIndexBuffer();
  35925. };
  35926. PostProcessManager.prototype._buildIndexBuffer = function () {
  35927. // Indices
  35928. var indices = [];
  35929. indices.push(0);
  35930. indices.push(1);
  35931. indices.push(2);
  35932. indices.push(0);
  35933. indices.push(2);
  35934. indices.push(3);
  35935. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35936. };
  35937. /**
  35938. * Rebuilds the vertex buffers of the manager.
  35939. */
  35940. PostProcessManager.prototype._rebuild = function () {
  35941. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35942. if (!vb) {
  35943. return;
  35944. }
  35945. vb._rebuild();
  35946. this._buildIndexBuffer();
  35947. };
  35948. // Methods
  35949. /**
  35950. * Prepares a frame to be run through a post process.
  35951. * @param sourceTexture The input texture to the post procesess. (default: null)
  35952. * @param postProcesses An array of post processes to be run. (default: null)
  35953. * @returns True if the post processes were able to be run.
  35954. */
  35955. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35956. if (sourceTexture === void 0) { sourceTexture = null; }
  35957. if (postProcesses === void 0) { postProcesses = null; }
  35958. var camera = this._scene.activeCamera;
  35959. if (!camera) {
  35960. return false;
  35961. }
  35962. var postProcesses = postProcesses || camera._postProcesses;
  35963. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35964. return false;
  35965. }
  35966. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35967. return true;
  35968. };
  35969. /**
  35970. * Manually render a set of post processes to a texture.
  35971. * @param postProcesses An array of post processes to be run.
  35972. * @param targetTexture The target texture to render to.
  35973. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35974. */
  35975. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35976. if (targetTexture === void 0) { targetTexture = null; }
  35977. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35978. var engine = this._scene.getEngine();
  35979. for (var index = 0; index < postProcesses.length; index++) {
  35980. if (index < postProcesses.length - 1) {
  35981. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35982. }
  35983. else {
  35984. if (targetTexture) {
  35985. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35986. }
  35987. else {
  35988. engine.restoreDefaultFramebuffer();
  35989. }
  35990. }
  35991. var pp = postProcesses[index];
  35992. var effect = pp.apply();
  35993. if (effect) {
  35994. pp.onBeforeRenderObservable.notifyObservers(effect);
  35995. // VBOs
  35996. this._prepareBuffers();
  35997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35998. // Draw order
  35999. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36000. pp.onAfterRenderObservable.notifyObservers(effect);
  36001. }
  36002. }
  36003. // Restore depth buffer
  36004. engine.setDepthBuffer(true);
  36005. engine.setDepthWrite(true);
  36006. };
  36007. /**
  36008. * Finalize the result of the output of the postprocesses.
  36009. * @param doNotPresent If true the result will not be displayed to the screen.
  36010. * @param targetTexture The target texture to render to.
  36011. * @param faceIndex The index of the face to bind the target texture to.
  36012. * @param postProcesses The array of post processes to render.
  36013. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36014. */
  36015. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36016. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36017. var camera = this._scene.activeCamera;
  36018. if (!camera) {
  36019. return;
  36020. }
  36021. postProcesses = postProcesses || camera._postProcesses;
  36022. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36023. return;
  36024. }
  36025. var engine = this._scene.getEngine();
  36026. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36027. if (index < len - 1) {
  36028. postProcesses[index + 1].activate(camera, targetTexture);
  36029. }
  36030. else {
  36031. if (targetTexture) {
  36032. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36033. }
  36034. else {
  36035. engine.restoreDefaultFramebuffer();
  36036. }
  36037. }
  36038. if (doNotPresent) {
  36039. break;
  36040. }
  36041. var pp = postProcesses[index];
  36042. var effect = pp.apply();
  36043. if (effect) {
  36044. pp.onBeforeRenderObservable.notifyObservers(effect);
  36045. // VBOs
  36046. this._prepareBuffers();
  36047. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36048. // Draw order
  36049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36050. pp.onAfterRenderObservable.notifyObservers(effect);
  36051. }
  36052. }
  36053. // Restore states
  36054. engine.setDepthBuffer(true);
  36055. engine.setDepthWrite(true);
  36056. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36057. };
  36058. /**
  36059. * Disposes of the post process manager.
  36060. */
  36061. PostProcessManager.prototype.dispose = function () {
  36062. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36063. if (buffer) {
  36064. buffer.dispose();
  36065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36066. }
  36067. if (this._indexBuffer) {
  36068. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36069. this._indexBuffer = null;
  36070. }
  36071. };
  36072. return PostProcessManager;
  36073. }());
  36074. BABYLON.PostProcessManager = PostProcessManager;
  36075. })(BABYLON || (BABYLON = {}));
  36076. //# sourceMappingURL=babylon.postProcessManager.js.map
  36077. var BABYLON;
  36078. (function (BABYLON) {
  36079. /**
  36080. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36081. */
  36082. var PerformanceMonitor = /** @class */ (function () {
  36083. /**
  36084. * constructor
  36085. * @param frameSampleSize The number of samples required to saturate the sliding window
  36086. */
  36087. function PerformanceMonitor(frameSampleSize) {
  36088. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36089. this._enabled = true;
  36090. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36091. }
  36092. /**
  36093. * Samples current frame
  36094. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36095. */
  36096. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36097. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36098. if (!this._enabled)
  36099. return;
  36100. if (this._lastFrameTimeMs != null) {
  36101. var dt = timeMs - this._lastFrameTimeMs;
  36102. this._rollingFrameTime.add(dt);
  36103. }
  36104. this._lastFrameTimeMs = timeMs;
  36105. };
  36106. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36107. /**
  36108. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36109. * @return Average frame time in milliseconds
  36110. */
  36111. get: function () {
  36112. return this._rollingFrameTime.average;
  36113. },
  36114. enumerable: true,
  36115. configurable: true
  36116. });
  36117. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36118. /**
  36119. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36120. * @return Frame time variance in milliseconds squared
  36121. */
  36122. get: function () {
  36123. return this._rollingFrameTime.variance;
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36129. /**
  36130. * Returns the frame time of the most recent frame
  36131. * @return Frame time in milliseconds
  36132. */
  36133. get: function () {
  36134. return this._rollingFrameTime.history(0);
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36140. /**
  36141. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36142. * @return Framerate in frames per second
  36143. */
  36144. get: function () {
  36145. return 1000.0 / this._rollingFrameTime.average;
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36151. /**
  36152. * Returns the average framerate in frames per second using the most recent frame time
  36153. * @return Framerate in frames per second
  36154. */
  36155. get: function () {
  36156. var history = this._rollingFrameTime.history(0);
  36157. if (history === 0) {
  36158. return 0;
  36159. }
  36160. return 1000.0 / history;
  36161. },
  36162. enumerable: true,
  36163. configurable: true
  36164. });
  36165. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36166. /**
  36167. * Returns true if enough samples have been taken to completely fill the sliding window
  36168. * @return true if saturated
  36169. */
  36170. get: function () {
  36171. return this._rollingFrameTime.isSaturated();
  36172. },
  36173. enumerable: true,
  36174. configurable: true
  36175. });
  36176. /**
  36177. * Enables contributions to the sliding window sample set
  36178. */
  36179. PerformanceMonitor.prototype.enable = function () {
  36180. this._enabled = true;
  36181. };
  36182. /**
  36183. * Disables contributions to the sliding window sample set
  36184. * Samples will not be interpolated over the disabled period
  36185. */
  36186. PerformanceMonitor.prototype.disable = function () {
  36187. this._enabled = false;
  36188. //clear last sample to avoid interpolating over the disabled period when next enabled
  36189. this._lastFrameTimeMs = null;
  36190. };
  36191. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36192. /**
  36193. * Returns true if sampling is enabled
  36194. * @return true if enabled
  36195. */
  36196. get: function () {
  36197. return this._enabled;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. /**
  36203. * Resets performance monitor
  36204. */
  36205. PerformanceMonitor.prototype.reset = function () {
  36206. //clear last sample to avoid interpolating over the disabled period when next enabled
  36207. this._lastFrameTimeMs = null;
  36208. //wipe record
  36209. this._rollingFrameTime.reset();
  36210. };
  36211. return PerformanceMonitor;
  36212. }());
  36213. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36214. /**
  36215. * RollingAverage
  36216. *
  36217. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36218. */
  36219. var RollingAverage = /** @class */ (function () {
  36220. /**
  36221. * constructor
  36222. * @param length The number of samples required to saturate the sliding window
  36223. */
  36224. function RollingAverage(length) {
  36225. this._samples = new Array(length);
  36226. this.reset();
  36227. }
  36228. /**
  36229. * Adds a sample to the sample set
  36230. * @param v The sample value
  36231. */
  36232. RollingAverage.prototype.add = function (v) {
  36233. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36234. var delta;
  36235. //we need to check if we've already wrapped round
  36236. if (this.isSaturated()) {
  36237. //remove bottom of stack from mean
  36238. var bottomValue = this._samples[this._pos];
  36239. delta = bottomValue - this.average;
  36240. this.average -= delta / (this._sampleCount - 1);
  36241. this._m2 -= delta * (bottomValue - this.average);
  36242. }
  36243. else {
  36244. this._sampleCount++;
  36245. }
  36246. //add new value to mean
  36247. delta = v - this.average;
  36248. this.average += delta / (this._sampleCount);
  36249. this._m2 += delta * (v - this.average);
  36250. //set the new variance
  36251. this.variance = this._m2 / (this._sampleCount - 1);
  36252. this._samples[this._pos] = v;
  36253. this._pos++;
  36254. this._pos %= this._samples.length; //positive wrap around
  36255. };
  36256. /**
  36257. * Returns previously added values or null if outside of history or outside the sliding window domain
  36258. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36259. * @return Value previously recorded with add() or null if outside of range
  36260. */
  36261. RollingAverage.prototype.history = function (i) {
  36262. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36263. return 0;
  36264. }
  36265. var i0 = this._wrapPosition(this._pos - 1.0);
  36266. return this._samples[this._wrapPosition(i0 - i)];
  36267. };
  36268. /**
  36269. * Returns true if enough samples have been taken to completely fill the sliding window
  36270. * @return true if sample-set saturated
  36271. */
  36272. RollingAverage.prototype.isSaturated = function () {
  36273. return this._sampleCount >= this._samples.length;
  36274. };
  36275. /**
  36276. * Resets the rolling average (equivalent to 0 samples taken so far)
  36277. */
  36278. RollingAverage.prototype.reset = function () {
  36279. this.average = 0;
  36280. this.variance = 0;
  36281. this._sampleCount = 0;
  36282. this._pos = 0;
  36283. this._m2 = 0;
  36284. };
  36285. /**
  36286. * Wraps a value around the sample range boundaries
  36287. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36288. * @return Wrapped position in sample range
  36289. */
  36290. RollingAverage.prototype._wrapPosition = function (i) {
  36291. var max = this._samples.length;
  36292. return ((i % max) + max) % max;
  36293. };
  36294. return RollingAverage;
  36295. }());
  36296. BABYLON.RollingAverage = RollingAverage;
  36297. })(BABYLON || (BABYLON = {}));
  36298. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36299. var BABYLON;
  36300. (function (BABYLON) {
  36301. /**
  36302. * This groups together the common properties used for image processing either in direct forward pass
  36303. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36304. * or not.
  36305. */
  36306. var ImageProcessingConfiguration = /** @class */ (function () {
  36307. function ImageProcessingConfiguration() {
  36308. /**
  36309. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36310. */
  36311. this.colorCurves = new BABYLON.ColorCurves();
  36312. this._colorCurvesEnabled = false;
  36313. this._colorGradingEnabled = false;
  36314. this._colorGradingWithGreenDepth = true;
  36315. this._colorGradingBGR = true;
  36316. this._exposure = 1.0;
  36317. this._toneMappingEnabled = false;
  36318. this._contrast = 1.0;
  36319. /**
  36320. * Vignette stretch size.
  36321. */
  36322. this.vignetteStretch = 0;
  36323. /**
  36324. * Vignette centre X Offset.
  36325. */
  36326. this.vignetteCentreX = 0;
  36327. /**
  36328. * Vignette centre Y Offset.
  36329. */
  36330. this.vignetteCentreY = 0;
  36331. /**
  36332. * Vignette weight or intensity of the vignette effect.
  36333. */
  36334. this.vignetteWeight = 1.5;
  36335. /**
  36336. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36337. * if vignetteEnabled is set to true.
  36338. */
  36339. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36340. /**
  36341. * Camera field of view used by the Vignette effect.
  36342. */
  36343. this.vignetteCameraFov = 0.5;
  36344. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36345. this._vignetteEnabled = false;
  36346. this._applyByPostProcess = false;
  36347. this._isEnabled = true;
  36348. /**
  36349. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36350. * @type {BABYLON.Observable}
  36351. */
  36352. this.onUpdateParameters = new BABYLON.Observable();
  36353. }
  36354. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36355. /**
  36356. * Gets wether the color curves effect is enabled.
  36357. */
  36358. get: function () {
  36359. return this._colorCurvesEnabled;
  36360. },
  36361. /**
  36362. * Sets wether the color curves effect is enabled.
  36363. */
  36364. set: function (value) {
  36365. if (this._colorCurvesEnabled === value) {
  36366. return;
  36367. }
  36368. this._colorCurvesEnabled = value;
  36369. this._updateParameters();
  36370. },
  36371. enumerable: true,
  36372. configurable: true
  36373. });
  36374. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36375. /**
  36376. * Gets wether the color grading effect is enabled.
  36377. */
  36378. get: function () {
  36379. return this._colorGradingEnabled;
  36380. },
  36381. /**
  36382. * Sets wether the color grading effect is enabled.
  36383. */
  36384. set: function (value) {
  36385. if (this._colorGradingEnabled === value) {
  36386. return;
  36387. }
  36388. this._colorGradingEnabled = value;
  36389. this._updateParameters();
  36390. },
  36391. enumerable: true,
  36392. configurable: true
  36393. });
  36394. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36395. /**
  36396. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36397. */
  36398. get: function () {
  36399. return this._colorGradingWithGreenDepth;
  36400. },
  36401. /**
  36402. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36403. */
  36404. set: function (value) {
  36405. if (this._colorGradingWithGreenDepth === value) {
  36406. return;
  36407. }
  36408. this._colorGradingWithGreenDepth = value;
  36409. this._updateParameters();
  36410. },
  36411. enumerable: true,
  36412. configurable: true
  36413. });
  36414. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36415. /**
  36416. * Gets wether the color grading texture contains BGR values.
  36417. */
  36418. get: function () {
  36419. return this._colorGradingBGR;
  36420. },
  36421. /**
  36422. * Sets wether the color grading texture contains BGR values.
  36423. */
  36424. set: function (value) {
  36425. if (this._colorGradingBGR === value) {
  36426. return;
  36427. }
  36428. this._colorGradingBGR = value;
  36429. this._updateParameters();
  36430. },
  36431. enumerable: true,
  36432. configurable: true
  36433. });
  36434. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36435. /**
  36436. * Gets the Exposure used in the effect.
  36437. */
  36438. get: function () {
  36439. return this._exposure;
  36440. },
  36441. /**
  36442. * Sets the Exposure used in the effect.
  36443. */
  36444. set: function (value) {
  36445. if (this._exposure === value) {
  36446. return;
  36447. }
  36448. this._exposure = value;
  36449. this._updateParameters();
  36450. },
  36451. enumerable: true,
  36452. configurable: true
  36453. });
  36454. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36455. /**
  36456. * Gets wether the tone mapping effect is enabled.
  36457. */
  36458. get: function () {
  36459. return this._toneMappingEnabled;
  36460. },
  36461. /**
  36462. * Sets wether the tone mapping effect is enabled.
  36463. */
  36464. set: function (value) {
  36465. if (this._toneMappingEnabled === value) {
  36466. return;
  36467. }
  36468. this._toneMappingEnabled = value;
  36469. this._updateParameters();
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36475. /**
  36476. * Gets the contrast used in the effect.
  36477. */
  36478. get: function () {
  36479. return this._contrast;
  36480. },
  36481. /**
  36482. * Sets the contrast used in the effect.
  36483. */
  36484. set: function (value) {
  36485. if (this._contrast === value) {
  36486. return;
  36487. }
  36488. this._contrast = value;
  36489. this._updateParameters();
  36490. },
  36491. enumerable: true,
  36492. configurable: true
  36493. });
  36494. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36495. /**
  36496. * Gets the vignette blend mode allowing different kind of effect.
  36497. */
  36498. get: function () {
  36499. return this._vignetteBlendMode;
  36500. },
  36501. /**
  36502. * Sets the vignette blend mode allowing different kind of effect.
  36503. */
  36504. set: function (value) {
  36505. if (this._vignetteBlendMode === value) {
  36506. return;
  36507. }
  36508. this._vignetteBlendMode = value;
  36509. this._updateParameters();
  36510. },
  36511. enumerable: true,
  36512. configurable: true
  36513. });
  36514. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36515. /**
  36516. * Gets wether the vignette effect is enabled.
  36517. */
  36518. get: function () {
  36519. return this._vignetteEnabled;
  36520. },
  36521. /**
  36522. * Sets wether the vignette effect is enabled.
  36523. */
  36524. set: function (value) {
  36525. if (this._vignetteEnabled === value) {
  36526. return;
  36527. }
  36528. this._vignetteEnabled = value;
  36529. this._updateParameters();
  36530. },
  36531. enumerable: true,
  36532. configurable: true
  36533. });
  36534. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36535. /**
  36536. * Gets wether the image processing is applied through a post process or not.
  36537. */
  36538. get: function () {
  36539. return this._applyByPostProcess;
  36540. },
  36541. /**
  36542. * Sets wether the image processing is applied through a post process or not.
  36543. */
  36544. set: function (value) {
  36545. if (this._applyByPostProcess === value) {
  36546. return;
  36547. }
  36548. this._applyByPostProcess = value;
  36549. this._updateParameters();
  36550. },
  36551. enumerable: true,
  36552. configurable: true
  36553. });
  36554. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36555. /**
  36556. * Gets wether the image processing is enabled or not.
  36557. */
  36558. get: function () {
  36559. return this._isEnabled;
  36560. },
  36561. /**
  36562. * Sets wether the image processing is enabled or not.
  36563. */
  36564. set: function (value) {
  36565. if (this._isEnabled === value) {
  36566. return;
  36567. }
  36568. this._isEnabled = value;
  36569. this._updateParameters();
  36570. },
  36571. enumerable: true,
  36572. configurable: true
  36573. });
  36574. /**
  36575. * Method called each time the image processing information changes requires to recompile the effect.
  36576. */
  36577. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36578. this.onUpdateParameters.notifyObservers(this);
  36579. };
  36580. ImageProcessingConfiguration.prototype.getClassName = function () {
  36581. return "ImageProcessingConfiguration";
  36582. };
  36583. /**
  36584. * Prepare the list of uniforms associated with the Image Processing effects.
  36585. * @param uniformsList The list of uniforms used in the effect
  36586. * @param defines the list of defines currently in use
  36587. */
  36588. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36589. if (defines.EXPOSURE) {
  36590. uniforms.push("exposureLinear");
  36591. }
  36592. if (defines.CONTRAST) {
  36593. uniforms.push("contrast");
  36594. }
  36595. if (defines.COLORGRADING) {
  36596. uniforms.push("colorTransformSettings");
  36597. }
  36598. if (defines.VIGNETTE) {
  36599. uniforms.push("vInverseScreenSize");
  36600. uniforms.push("vignetteSettings1");
  36601. uniforms.push("vignetteSettings2");
  36602. }
  36603. if (defines.COLORCURVES) {
  36604. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36605. }
  36606. };
  36607. /**
  36608. * Prepare the list of samplers associated with the Image Processing effects.
  36609. * @param uniformsList The list of uniforms used in the effect
  36610. * @param defines the list of defines currently in use
  36611. */
  36612. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36613. if (defines.COLORGRADING) {
  36614. samplersList.push("txColorTransform");
  36615. }
  36616. };
  36617. /**
  36618. * Prepare the list of defines associated to the shader.
  36619. * @param defines the list of defines to complete
  36620. */
  36621. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36622. if (forPostProcess === void 0) { forPostProcess = false; }
  36623. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36624. defines.VIGNETTE = false;
  36625. defines.TONEMAPPING = false;
  36626. defines.CONTRAST = false;
  36627. defines.EXPOSURE = false;
  36628. defines.COLORCURVES = false;
  36629. defines.COLORGRADING = false;
  36630. defines.COLORGRADING3D = false;
  36631. defines.IMAGEPROCESSING = false;
  36632. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36633. return;
  36634. }
  36635. defines.VIGNETTE = this.vignetteEnabled;
  36636. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36637. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36638. defines.TONEMAPPING = this.toneMappingEnabled;
  36639. defines.CONTRAST = (this.contrast !== 1.0);
  36640. defines.EXPOSURE = (this.exposure !== 1.0);
  36641. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36642. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36643. if (defines.COLORGRADING) {
  36644. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36645. }
  36646. else {
  36647. defines.COLORGRADING3D = false;
  36648. }
  36649. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36650. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36651. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36652. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36653. };
  36654. /**
  36655. * Returns true if all the image processing information are ready.
  36656. */
  36657. ImageProcessingConfiguration.prototype.isReady = function () {
  36658. // Color Grading texure can not be none blocking.
  36659. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36660. };
  36661. /**
  36662. * Binds the image processing to the shader.
  36663. * @param effect The effect to bind to
  36664. */
  36665. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36666. if (aspectRatio === void 0) { aspectRatio = 1; }
  36667. // Color Curves
  36668. if (this._colorCurvesEnabled && this.colorCurves) {
  36669. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36670. }
  36671. // Vignette
  36672. if (this._vignetteEnabled) {
  36673. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36674. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36675. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36676. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36677. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36678. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36679. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36680. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36681. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36682. var vignettePower = -2.0 * this.vignetteWeight;
  36683. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36684. }
  36685. // Exposure
  36686. effect.setFloat("exposureLinear", this.exposure);
  36687. // Contrast
  36688. effect.setFloat("contrast", this.contrast);
  36689. // Color transform settings
  36690. if (this.colorGradingTexture) {
  36691. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36692. var textureSize = this.colorGradingTexture.getSize().height;
  36693. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36694. 0.5 / textureSize, // textureOffset
  36695. textureSize, // textureSize
  36696. this.colorGradingTexture.level // weight
  36697. );
  36698. }
  36699. };
  36700. /**
  36701. * Clones the current image processing instance.
  36702. * @return The cloned image processing
  36703. */
  36704. ImageProcessingConfiguration.prototype.clone = function () {
  36705. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36706. };
  36707. /**
  36708. * Serializes the current image processing instance to a json representation.
  36709. * @return a JSON representation
  36710. */
  36711. ImageProcessingConfiguration.prototype.serialize = function () {
  36712. return BABYLON.SerializationHelper.Serialize(this);
  36713. };
  36714. /**
  36715. * Parses the image processing from a json representation.
  36716. * @param source the JSON source to parse
  36717. * @return The parsed image processing
  36718. */
  36719. ImageProcessingConfiguration.Parse = function (source) {
  36720. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36721. };
  36722. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36723. /**
  36724. * Used to apply the vignette as a mix with the pixel color.
  36725. */
  36726. get: function () {
  36727. return this._VIGNETTEMODE_MULTIPLY;
  36728. },
  36729. enumerable: true,
  36730. configurable: true
  36731. });
  36732. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36733. /**
  36734. * Used to apply the vignette as a replacement of the pixel color.
  36735. */
  36736. get: function () {
  36737. return this._VIGNETTEMODE_OPAQUE;
  36738. },
  36739. enumerable: true,
  36740. configurable: true
  36741. });
  36742. // Static constants associated to the image processing.
  36743. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36744. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36745. __decorate([
  36746. BABYLON.serializeAsColorCurves()
  36747. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36748. __decorate([
  36749. BABYLON.serialize()
  36750. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36751. __decorate([
  36752. BABYLON.serializeAsTexture()
  36753. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36754. __decorate([
  36755. BABYLON.serialize()
  36756. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36757. __decorate([
  36758. BABYLON.serialize()
  36759. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36760. __decorate([
  36761. BABYLON.serialize()
  36762. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36763. __decorate([
  36764. BABYLON.serialize()
  36765. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36766. __decorate([
  36767. BABYLON.serialize()
  36768. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36769. __decorate([
  36770. BABYLON.serialize()
  36771. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36772. __decorate([
  36773. BABYLON.serialize()
  36774. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36775. __decorate([
  36776. BABYLON.serialize()
  36777. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36778. __decorate([
  36779. BABYLON.serialize()
  36780. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36781. __decorate([
  36782. BABYLON.serialize()
  36783. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36784. __decorate([
  36785. BABYLON.serializeAsColor4()
  36786. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36787. __decorate([
  36788. BABYLON.serialize()
  36789. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36790. __decorate([
  36791. BABYLON.serialize()
  36792. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36793. __decorate([
  36794. BABYLON.serialize()
  36795. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36796. __decorate([
  36797. BABYLON.serialize()
  36798. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36799. __decorate([
  36800. BABYLON.serialize()
  36801. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36802. return ImageProcessingConfiguration;
  36803. }());
  36804. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36805. })(BABYLON || (BABYLON = {}));
  36806. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36807. var BABYLON;
  36808. (function (BABYLON) {
  36809. /**
  36810. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36811. * It can help converting any input color in a desired output one. This can then be used to create effects
  36812. * from sepia, black and white to sixties or futuristic rendering...
  36813. *
  36814. * The only supported format is currently 3dl.
  36815. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36816. */
  36817. var ColorGradingTexture = /** @class */ (function (_super) {
  36818. __extends(ColorGradingTexture, _super);
  36819. /**
  36820. * Instantiates a ColorGradingTexture from the following parameters.
  36821. *
  36822. * @param url The location of the color gradind data (currently only supporting 3dl)
  36823. * @param scene The scene the texture will be used in
  36824. */
  36825. function ColorGradingTexture(url, scene) {
  36826. var _this = _super.call(this, scene) || this;
  36827. if (!url) {
  36828. return _this;
  36829. }
  36830. _this._engine = scene.getEngine();
  36831. _this._textureMatrix = BABYLON.Matrix.Identity();
  36832. _this.name = url;
  36833. _this.url = url;
  36834. _this.hasAlpha = false;
  36835. _this.isCube = false;
  36836. _this.is3D = _this._engine.webGLVersion > 1;
  36837. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36838. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36839. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36840. _this.anisotropicFilteringLevel = 1;
  36841. _this._texture = _this._getFromCache(url, true);
  36842. if (!_this._texture) {
  36843. if (!scene.useDelayedTextureLoading) {
  36844. _this.loadTexture();
  36845. }
  36846. else {
  36847. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36848. }
  36849. }
  36850. return _this;
  36851. }
  36852. /**
  36853. * Returns the texture matrix used in most of the material.
  36854. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36855. */
  36856. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36857. return this._textureMatrix;
  36858. };
  36859. /**
  36860. * Occurs when the file being loaded is a .3dl LUT file.
  36861. */
  36862. ColorGradingTexture.prototype.load3dlTexture = function () {
  36863. var engine = this._engine;
  36864. var texture;
  36865. if (engine.webGLVersion === 1) {
  36866. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36867. }
  36868. else {
  36869. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36870. }
  36871. this._texture = texture;
  36872. var callback = function (text) {
  36873. if (typeof text !== "string") {
  36874. return;
  36875. }
  36876. var data = null;
  36877. var tempData = null;
  36878. var line;
  36879. var lines = text.split('\n');
  36880. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36881. var maxColor = 0;
  36882. for (var i = 0; i < lines.length; i++) {
  36883. line = lines[i];
  36884. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36885. continue;
  36886. if (line.indexOf('#') === 0)
  36887. continue;
  36888. var words = line.split(" ");
  36889. if (size === 0) {
  36890. // Number of space + one
  36891. size = words.length;
  36892. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36893. tempData = new Float32Array(size * size * size * 4);
  36894. continue;
  36895. }
  36896. if (size != 0) {
  36897. var r = Math.max(parseInt(words[0]), 0);
  36898. var g = Math.max(parseInt(words[1]), 0);
  36899. var b = Math.max(parseInt(words[2]), 0);
  36900. maxColor = Math.max(r, maxColor);
  36901. maxColor = Math.max(g, maxColor);
  36902. maxColor = Math.max(b, maxColor);
  36903. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36904. if (tempData) {
  36905. tempData[pixelStorageIndex + 0] = r;
  36906. tempData[pixelStorageIndex + 1] = g;
  36907. tempData[pixelStorageIndex + 2] = b;
  36908. }
  36909. pixelIndexSlice++;
  36910. if (pixelIndexSlice % size == 0) {
  36911. pixelIndexH++;
  36912. pixelIndexSlice = 0;
  36913. if (pixelIndexH % size == 0) {
  36914. pixelIndexW++;
  36915. pixelIndexH = 0;
  36916. }
  36917. }
  36918. }
  36919. }
  36920. if (tempData && data) {
  36921. for (var i = 0; i < tempData.length; i++) {
  36922. if (i > 0 && (i + 1) % 4 === 0) {
  36923. data[i] = 255;
  36924. }
  36925. else {
  36926. var value = tempData[i];
  36927. data[i] = (value / maxColor * 255);
  36928. }
  36929. }
  36930. }
  36931. if (texture.is3D) {
  36932. texture.updateSize(size, size, size);
  36933. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36934. }
  36935. else {
  36936. texture.updateSize(size * size, size);
  36937. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36938. }
  36939. };
  36940. var scene = this.getScene();
  36941. if (scene) {
  36942. scene._loadFile(this.url, callback);
  36943. }
  36944. else {
  36945. this._engine._loadFile(this.url, callback);
  36946. }
  36947. return this._texture;
  36948. };
  36949. /**
  36950. * Starts the loading process of the texture.
  36951. */
  36952. ColorGradingTexture.prototype.loadTexture = function () {
  36953. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36954. this.load3dlTexture();
  36955. }
  36956. };
  36957. /**
  36958. * Clones the color gradind texture.
  36959. */
  36960. ColorGradingTexture.prototype.clone = function () {
  36961. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36962. // Base texture
  36963. newTexture.level = this.level;
  36964. return newTexture;
  36965. };
  36966. /**
  36967. * Called during delayed load for textures.
  36968. */
  36969. ColorGradingTexture.prototype.delayLoad = function () {
  36970. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36971. return;
  36972. }
  36973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36974. this._texture = this._getFromCache(this.url, true);
  36975. if (!this._texture) {
  36976. this.loadTexture();
  36977. }
  36978. };
  36979. /**
  36980. * Parses a color grading texture serialized by Babylon.
  36981. * @param parsedTexture The texture information being parsedTexture
  36982. * @param scene The scene to load the texture in
  36983. * @param rootUrl The root url of the data assets to load
  36984. * @return A color gradind texture
  36985. */
  36986. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36987. var texture = null;
  36988. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36989. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36990. texture.name = parsedTexture.name;
  36991. texture.level = parsedTexture.level;
  36992. }
  36993. return texture;
  36994. };
  36995. /**
  36996. * Serializes the LUT texture to json format.
  36997. */
  36998. ColorGradingTexture.prototype.serialize = function () {
  36999. if (!this.name) {
  37000. return null;
  37001. }
  37002. var serializationObject = {};
  37003. serializationObject.name = this.name;
  37004. serializationObject.level = this.level;
  37005. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37006. return serializationObject;
  37007. };
  37008. /**
  37009. * Empty line regex stored for GC.
  37010. */
  37011. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37012. return ColorGradingTexture;
  37013. }(BABYLON.BaseTexture));
  37014. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37015. })(BABYLON || (BABYLON = {}));
  37016. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37017. var BABYLON;
  37018. (function (BABYLON) {
  37019. /**
  37020. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37021. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37022. * 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;
  37023. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37024. */
  37025. var ColorCurves = /** @class */ (function () {
  37026. function ColorCurves() {
  37027. this._dirty = true;
  37028. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37029. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37030. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37031. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37032. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37033. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37034. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37035. this._globalHue = 30;
  37036. this._globalDensity = 0;
  37037. this._globalSaturation = 0;
  37038. this._globalExposure = 0;
  37039. this._highlightsHue = 30;
  37040. this._highlightsDensity = 0;
  37041. this._highlightsSaturation = 0;
  37042. this._highlightsExposure = 0;
  37043. this._midtonesHue = 30;
  37044. this._midtonesDensity = 0;
  37045. this._midtonesSaturation = 0;
  37046. this._midtonesExposure = 0;
  37047. this._shadowsHue = 30;
  37048. this._shadowsDensity = 0;
  37049. this._shadowsSaturation = 0;
  37050. this._shadowsExposure = 0;
  37051. }
  37052. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37053. /**
  37054. * Gets the global Hue value.
  37055. * 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).
  37056. */
  37057. get: function () {
  37058. return this._globalHue;
  37059. },
  37060. /**
  37061. * Sets the global Hue value.
  37062. * 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).
  37063. */
  37064. set: function (value) {
  37065. this._globalHue = value;
  37066. this._dirty = true;
  37067. },
  37068. enumerable: true,
  37069. configurable: true
  37070. });
  37071. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37072. /**
  37073. * Gets the global Density value.
  37074. * 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.
  37075. * Values less than zero provide a filter of opposite hue.
  37076. */
  37077. get: function () {
  37078. return this._globalDensity;
  37079. },
  37080. /**
  37081. * Sets the global Density value.
  37082. * 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.
  37083. * Values less than zero provide a filter of opposite hue.
  37084. */
  37085. set: function (value) {
  37086. this._globalDensity = value;
  37087. this._dirty = true;
  37088. },
  37089. enumerable: true,
  37090. configurable: true
  37091. });
  37092. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37093. /**
  37094. * Gets the global Saturation value.
  37095. * 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.
  37096. */
  37097. get: function () {
  37098. return this._globalSaturation;
  37099. },
  37100. /**
  37101. * Sets the global Saturation value.
  37102. * 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.
  37103. */
  37104. set: function (value) {
  37105. this._globalSaturation = value;
  37106. this._dirty = true;
  37107. },
  37108. enumerable: true,
  37109. configurable: true
  37110. });
  37111. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37112. /**
  37113. * Gets the highlights Hue value.
  37114. * 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).
  37115. */
  37116. get: function () {
  37117. return this._highlightsHue;
  37118. },
  37119. /**
  37120. * Sets the highlights Hue value.
  37121. * 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).
  37122. */
  37123. set: function (value) {
  37124. this._highlightsHue = value;
  37125. this._dirty = true;
  37126. },
  37127. enumerable: true,
  37128. configurable: true
  37129. });
  37130. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37131. /**
  37132. * Gets the highlights Density value.
  37133. * 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.
  37134. * Values less than zero provide a filter of opposite hue.
  37135. */
  37136. get: function () {
  37137. return this._highlightsDensity;
  37138. },
  37139. /**
  37140. * Sets the highlights Density value.
  37141. * 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.
  37142. * Values less than zero provide a filter of opposite hue.
  37143. */
  37144. set: function (value) {
  37145. this._highlightsDensity = value;
  37146. this._dirty = true;
  37147. },
  37148. enumerable: true,
  37149. configurable: true
  37150. });
  37151. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37152. /**
  37153. * Gets the highlights Saturation value.
  37154. * 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.
  37155. */
  37156. get: function () {
  37157. return this._highlightsSaturation;
  37158. },
  37159. /**
  37160. * Sets the highlights Saturation value.
  37161. * 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.
  37162. */
  37163. set: function (value) {
  37164. this._highlightsSaturation = value;
  37165. this._dirty = true;
  37166. },
  37167. enumerable: true,
  37168. configurable: true
  37169. });
  37170. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37171. /**
  37172. * Gets the highlights Exposure value.
  37173. * 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.
  37174. */
  37175. get: function () {
  37176. return this._highlightsExposure;
  37177. },
  37178. /**
  37179. * Sets the highlights Exposure value.
  37180. * 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.
  37181. */
  37182. set: function (value) {
  37183. this._highlightsExposure = value;
  37184. this._dirty = true;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37190. /**
  37191. * Gets the midtones Hue value.
  37192. * 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).
  37193. */
  37194. get: function () {
  37195. return this._midtonesHue;
  37196. },
  37197. /**
  37198. * Sets the midtones Hue value.
  37199. * 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).
  37200. */
  37201. set: function (value) {
  37202. this._midtonesHue = value;
  37203. this._dirty = true;
  37204. },
  37205. enumerable: true,
  37206. configurable: true
  37207. });
  37208. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37209. /**
  37210. * Gets the midtones Density value.
  37211. * 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.
  37212. * Values less than zero provide a filter of opposite hue.
  37213. */
  37214. get: function () {
  37215. return this._midtonesDensity;
  37216. },
  37217. /**
  37218. * Sets the midtones Density value.
  37219. * 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.
  37220. * Values less than zero provide a filter of opposite hue.
  37221. */
  37222. set: function (value) {
  37223. this._midtonesDensity = value;
  37224. this._dirty = true;
  37225. },
  37226. enumerable: true,
  37227. configurable: true
  37228. });
  37229. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37230. /**
  37231. * Gets the midtones Saturation value.
  37232. * 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.
  37233. */
  37234. get: function () {
  37235. return this._midtonesSaturation;
  37236. },
  37237. /**
  37238. * Sets the midtones Saturation value.
  37239. * 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.
  37240. */
  37241. set: function (value) {
  37242. this._midtonesSaturation = value;
  37243. this._dirty = true;
  37244. },
  37245. enumerable: true,
  37246. configurable: true
  37247. });
  37248. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37249. /**
  37250. * Gets the midtones Exposure value.
  37251. * 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.
  37252. */
  37253. get: function () {
  37254. return this._midtonesExposure;
  37255. },
  37256. /**
  37257. * Sets the midtones Exposure value.
  37258. * 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.
  37259. */
  37260. set: function (value) {
  37261. this._midtonesExposure = value;
  37262. this._dirty = true;
  37263. },
  37264. enumerable: true,
  37265. configurable: true
  37266. });
  37267. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37268. /**
  37269. * Gets the shadows Hue value.
  37270. * 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).
  37271. */
  37272. get: function () {
  37273. return this._shadowsHue;
  37274. },
  37275. /**
  37276. * Sets the shadows Hue value.
  37277. * 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).
  37278. */
  37279. set: function (value) {
  37280. this._shadowsHue = value;
  37281. this._dirty = true;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37287. /**
  37288. * Gets the shadows Density value.
  37289. * 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.
  37290. * Values less than zero provide a filter of opposite hue.
  37291. */
  37292. get: function () {
  37293. return this._shadowsDensity;
  37294. },
  37295. /**
  37296. * Sets the shadows Density value.
  37297. * 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.
  37298. * Values less than zero provide a filter of opposite hue.
  37299. */
  37300. set: function (value) {
  37301. this._shadowsDensity = value;
  37302. this._dirty = true;
  37303. },
  37304. enumerable: true,
  37305. configurable: true
  37306. });
  37307. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37308. /**
  37309. * Gets the shadows Saturation value.
  37310. * 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.
  37311. */
  37312. get: function () {
  37313. return this._shadowsSaturation;
  37314. },
  37315. /**
  37316. * Sets the shadows Saturation value.
  37317. * 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.
  37318. */
  37319. set: function (value) {
  37320. this._shadowsSaturation = value;
  37321. this._dirty = true;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37327. /**
  37328. * Gets the shadows Exposure value.
  37329. * 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.
  37330. */
  37331. get: function () {
  37332. return this._shadowsExposure;
  37333. },
  37334. /**
  37335. * Sets the shadows Exposure value.
  37336. * 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.
  37337. */
  37338. set: function (value) {
  37339. this._shadowsExposure = value;
  37340. this._dirty = true;
  37341. },
  37342. enumerable: true,
  37343. configurable: true
  37344. });
  37345. ColorCurves.prototype.getClassName = function () {
  37346. return "ColorCurves";
  37347. };
  37348. /**
  37349. * Binds the color curves to the shader.
  37350. * @param colorCurves The color curve to bind
  37351. * @param effect The effect to bind to
  37352. */
  37353. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37354. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37355. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37356. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37357. if (colorCurves._dirty) {
  37358. colorCurves._dirty = false;
  37359. // Fill in global info.
  37360. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37361. // Compute highlights info.
  37362. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37363. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37364. // Compute midtones info.
  37365. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37366. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37367. // Compute shadows info.
  37368. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37369. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37370. // Compute deltas (neutral is midtones).
  37371. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37372. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37373. }
  37374. if (effect) {
  37375. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37376. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37377. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37378. }
  37379. };
  37380. /**
  37381. * Prepare the list of uniforms associated with the ColorCurves effects.
  37382. * @param uniformsList The list of uniforms used in the effect
  37383. */
  37384. ColorCurves.PrepareUniforms = function (uniformsList) {
  37385. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37386. };
  37387. /**
  37388. * Returns color grading data based on a hue, density, saturation and exposure value.
  37389. * @param filterHue The hue of the color filter.
  37390. * @param filterDensity The density of the color filter.
  37391. * @param saturation The saturation.
  37392. * @param exposure The exposure.
  37393. * @param result The result data container.
  37394. */
  37395. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37396. if (hue == null) {
  37397. return;
  37398. }
  37399. hue = ColorCurves.clamp(hue, 0, 360);
  37400. density = ColorCurves.clamp(density, -100, 100);
  37401. saturation = ColorCurves.clamp(saturation, -100, 100);
  37402. exposure = ColorCurves.clamp(exposure, -100, 100);
  37403. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37404. // so that the maximum filter density is only 50% control. This provides fine control
  37405. // for small values and reasonable range.
  37406. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37407. density *= 0.5;
  37408. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37409. if (density < 0) {
  37410. density *= -1;
  37411. hue = (hue + 180) % 360;
  37412. }
  37413. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37414. result.scaleToRef(2, result);
  37415. result.a = 1 + 0.01 * saturation;
  37416. };
  37417. /**
  37418. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37419. * @param value The input slider value in range [-100,100].
  37420. * @returns Adjusted value.
  37421. */
  37422. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37423. value /= 100;
  37424. var x = Math.abs(value);
  37425. x = Math.pow(x, 2);
  37426. if (value < 0) {
  37427. x *= -1;
  37428. }
  37429. x *= 100;
  37430. return x;
  37431. };
  37432. /**
  37433. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37434. * @param hue The hue (H) input.
  37435. * @param saturation The saturation (S) input.
  37436. * @param brightness The brightness (B) input.
  37437. * @result An RGBA color represented as Vector4.
  37438. */
  37439. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37440. var h = ColorCurves.clamp(hue, 0, 360);
  37441. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37442. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37443. if (s === 0) {
  37444. result.r = v;
  37445. result.g = v;
  37446. result.b = v;
  37447. }
  37448. else {
  37449. // sector 0 to 5
  37450. h /= 60;
  37451. var i = Math.floor(h);
  37452. // fractional part of h
  37453. var f = h - i;
  37454. var p = v * (1 - s);
  37455. var q = v * (1 - s * f);
  37456. var t = v * (1 - s * (1 - f));
  37457. switch (i) {
  37458. case 0:
  37459. result.r = v;
  37460. result.g = t;
  37461. result.b = p;
  37462. break;
  37463. case 1:
  37464. result.r = q;
  37465. result.g = v;
  37466. result.b = p;
  37467. break;
  37468. case 2:
  37469. result.r = p;
  37470. result.g = v;
  37471. result.b = t;
  37472. break;
  37473. case 3:
  37474. result.r = p;
  37475. result.g = q;
  37476. result.b = v;
  37477. break;
  37478. case 4:
  37479. result.r = t;
  37480. result.g = p;
  37481. result.b = v;
  37482. break;
  37483. default:// case 5:
  37484. result.r = v;
  37485. result.g = p;
  37486. result.b = q;
  37487. break;
  37488. }
  37489. }
  37490. result.a = 1;
  37491. };
  37492. /**
  37493. * Returns a value clamped between min and max
  37494. * @param value The value to clamp
  37495. * @param min The minimum of value
  37496. * @param max The maximum of value
  37497. * @returns The clamped value.
  37498. */
  37499. ColorCurves.clamp = function (value, min, max) {
  37500. return Math.min(Math.max(value, min), max);
  37501. };
  37502. /**
  37503. * Clones the current color curve instance.
  37504. * @return The cloned curves
  37505. */
  37506. ColorCurves.prototype.clone = function () {
  37507. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37508. };
  37509. /**
  37510. * Serializes the current color curve instance to a json representation.
  37511. * @return a JSON representation
  37512. */
  37513. ColorCurves.prototype.serialize = function () {
  37514. return BABYLON.SerializationHelper.Serialize(this);
  37515. };
  37516. /**
  37517. * Parses the color curve from a json representation.
  37518. * @param source the JSON source to parse
  37519. * @return The parsed curves
  37520. */
  37521. ColorCurves.Parse = function (source) {
  37522. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37523. };
  37524. __decorate([
  37525. BABYLON.serialize()
  37526. ], ColorCurves.prototype, "_globalHue", void 0);
  37527. __decorate([
  37528. BABYLON.serialize()
  37529. ], ColorCurves.prototype, "_globalDensity", void 0);
  37530. __decorate([
  37531. BABYLON.serialize()
  37532. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37533. __decorate([
  37534. BABYLON.serialize()
  37535. ], ColorCurves.prototype, "_globalExposure", void 0);
  37536. __decorate([
  37537. BABYLON.serialize()
  37538. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37539. __decorate([
  37540. BABYLON.serialize()
  37541. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37542. __decorate([
  37543. BABYLON.serialize()
  37544. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37545. __decorate([
  37546. BABYLON.serialize()
  37547. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37548. __decorate([
  37549. BABYLON.serialize()
  37550. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37551. __decorate([
  37552. BABYLON.serialize()
  37553. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37554. __decorate([
  37555. BABYLON.serialize()
  37556. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37557. __decorate([
  37558. BABYLON.serialize()
  37559. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37560. return ColorCurves;
  37561. }());
  37562. BABYLON.ColorCurves = ColorCurves;
  37563. })(BABYLON || (BABYLON = {}));
  37564. //# sourceMappingURL=babylon.colorCurves.js.map
  37565. //# sourceMappingURL=babylon.behavior.js.map
  37566. var BABYLON;
  37567. (function (BABYLON) {
  37568. /**
  37569. * "Static Class" containing the most commonly used helper while dealing with material for
  37570. * rendering purpose.
  37571. *
  37572. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37573. *
  37574. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37575. */
  37576. var MaterialHelper = /** @class */ (function () {
  37577. function MaterialHelper() {
  37578. }
  37579. /**
  37580. * Bind the current view position to an effect.
  37581. * @param effect The effect to be bound
  37582. * @param scene The scene the eyes position is used from
  37583. */
  37584. MaterialHelper.BindEyePosition = function (effect, scene) {
  37585. if (scene._forcedViewPosition) {
  37586. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37587. return;
  37588. }
  37589. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37590. };
  37591. /**
  37592. * Helps preparing the defines values about the UVs in used in the effect.
  37593. * UVs are shared as much as we can accross chanels in the shaders.
  37594. * @param texture The texture we are preparing the UVs for
  37595. * @param defines The defines to update
  37596. * @param key The chanel key "diffuse", "specular"... used in the shader
  37597. */
  37598. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37599. defines._needUVs = true;
  37600. defines[key] = true;
  37601. if (texture.getTextureMatrix().isIdentity(true)) {
  37602. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37603. if (texture.coordinatesIndex === 0) {
  37604. defines["MAINUV1"] = true;
  37605. }
  37606. else {
  37607. defines["MAINUV2"] = true;
  37608. }
  37609. }
  37610. else {
  37611. defines[key + "DIRECTUV"] = 0;
  37612. }
  37613. };
  37614. /**
  37615. * Binds a texture matrix value to its corrsponding uniform
  37616. * @param texture The texture to bind the matrix for
  37617. * @param uniformBuffer The uniform buffer receivin the data
  37618. * @param key The chanel key "diffuse", "specular"... used in the shader
  37619. */
  37620. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37621. var matrix = texture.getTextureMatrix();
  37622. if (!matrix.isIdentity(true)) {
  37623. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37624. }
  37625. };
  37626. /**
  37627. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37628. * @param mesh defines the current mesh
  37629. * @param scene defines the current scene
  37630. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37631. * @param pointsCloud defines if point cloud rendering has to be turned on
  37632. * @param fogEnabled defines if fog has to be turned on
  37633. * @param alphaTest defines if alpha testing has to be turned on
  37634. * @param defines defines the current list of defines
  37635. */
  37636. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37637. if (defines._areMiscDirty) {
  37638. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37639. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37640. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37641. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37642. defines["ALPHATEST"] = alphaTest;
  37643. }
  37644. };
  37645. /**
  37646. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37647. * @param scene defines the current scene
  37648. * @param engine defines the current engine
  37649. * @param defines specifies the list of active defines
  37650. * @param useInstances defines if instances have to be turned on
  37651. * @param useClipPlane defines if clip plane have to be turned on
  37652. */
  37653. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37654. if (useClipPlane === void 0) { useClipPlane = null; }
  37655. var changed = false;
  37656. if (useClipPlane == null) {
  37657. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37658. }
  37659. if (defines["CLIPPLANE"] !== useClipPlane) {
  37660. defines["CLIPPLANE"] = useClipPlane;
  37661. changed = true;
  37662. }
  37663. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37664. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37665. changed = true;
  37666. }
  37667. if (defines["INSTANCES"] !== useInstances) {
  37668. defines["INSTANCES"] = useInstances;
  37669. changed = true;
  37670. }
  37671. if (changed) {
  37672. defines.markAsUnprocessed();
  37673. }
  37674. };
  37675. /**
  37676. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37677. * @param mesh The mesh containing the geometry data we will draw
  37678. * @param defines The defines to update
  37679. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37680. * @param useBones Precise whether bones should be used or not (override mesh info)
  37681. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37682. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37683. * @returns false if defines are considered not dirty and have not been checked
  37684. */
  37685. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37686. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37687. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37688. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37689. return false;
  37690. }
  37691. defines._normals = defines._needNormals;
  37692. defines._uvs = defines._needUVs;
  37693. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37694. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37695. defines["TANGENT"] = true;
  37696. }
  37697. if (defines._needUVs) {
  37698. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37699. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37700. }
  37701. else {
  37702. defines["UV1"] = false;
  37703. defines["UV2"] = false;
  37704. }
  37705. if (useVertexColor) {
  37706. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37707. defines["VERTEXCOLOR"] = hasVertexColors;
  37708. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37709. }
  37710. if (useBones) {
  37711. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37712. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37713. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37714. }
  37715. else {
  37716. defines["NUM_BONE_INFLUENCERS"] = 0;
  37717. defines["BonesPerMesh"] = 0;
  37718. }
  37719. }
  37720. if (useMorphTargets) {
  37721. var manager = mesh.morphTargetManager;
  37722. if (manager) {
  37723. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37724. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37725. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37726. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37727. }
  37728. else {
  37729. defines["MORPHTARGETS_TANGENT"] = false;
  37730. defines["MORPHTARGETS_NORMAL"] = false;
  37731. defines["MORPHTARGETS"] = false;
  37732. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37733. }
  37734. }
  37735. return true;
  37736. };
  37737. /**
  37738. * Prepares the defines related to the light information passed in parameter
  37739. * @param scene The scene we are intending to draw
  37740. * @param mesh The mesh the effect is compiling for
  37741. * @param defines The defines to update
  37742. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37743. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37744. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37745. * @returns true if normals will be required for the rest of the effect
  37746. */
  37747. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37748. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37749. if (disableLighting === void 0) { disableLighting = false; }
  37750. if (!defines._areLightsDirty) {
  37751. return defines._needNormals;
  37752. }
  37753. var lightIndex = 0;
  37754. var needNormals = false;
  37755. var needRebuild = false;
  37756. var lightmapMode = false;
  37757. var shadowEnabled = false;
  37758. var specularEnabled = false;
  37759. if (scene.lightsEnabled && !disableLighting) {
  37760. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37761. var light = _a[_i];
  37762. needNormals = true;
  37763. if (defines["LIGHT" + lightIndex] === undefined) {
  37764. needRebuild = true;
  37765. }
  37766. defines["LIGHT" + lightIndex] = true;
  37767. defines["SPOTLIGHT" + lightIndex] = false;
  37768. defines["HEMILIGHT" + lightIndex] = false;
  37769. defines["POINTLIGHT" + lightIndex] = false;
  37770. defines["DIRLIGHT" + lightIndex] = false;
  37771. var type;
  37772. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37773. type = "SPOTLIGHT" + lightIndex;
  37774. var spotLight = light;
  37775. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37776. }
  37777. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37778. type = "HEMILIGHT" + lightIndex;
  37779. }
  37780. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37781. type = "POINTLIGHT" + lightIndex;
  37782. }
  37783. else {
  37784. type = "DIRLIGHT" + lightIndex;
  37785. }
  37786. defines[type] = true;
  37787. // Specular
  37788. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37789. specularEnabled = true;
  37790. }
  37791. // Shadows
  37792. defines["SHADOW" + lightIndex] = false;
  37793. defines["SHADOWPCF" + lightIndex] = false;
  37794. defines["SHADOWESM" + lightIndex] = false;
  37795. defines["SHADOWCUBE" + lightIndex] = false;
  37796. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37797. var shadowGenerator = light.getShadowGenerator();
  37798. if (shadowGenerator) {
  37799. shadowEnabled = true;
  37800. shadowGenerator.prepareDefines(defines, lightIndex);
  37801. }
  37802. }
  37803. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37804. lightmapMode = true;
  37805. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37806. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37807. }
  37808. else {
  37809. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37810. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37811. }
  37812. lightIndex++;
  37813. if (lightIndex === maxSimultaneousLights)
  37814. break;
  37815. }
  37816. }
  37817. defines["SPECULARTERM"] = specularEnabled;
  37818. defines["SHADOWS"] = shadowEnabled;
  37819. // Resetting all other lights if any
  37820. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37821. if (defines["LIGHT" + index] !== undefined) {
  37822. defines["LIGHT" + index] = false;
  37823. defines["HEMILIGHT" + lightIndex] = false;
  37824. defines["POINTLIGHT" + lightIndex] = false;
  37825. defines["DIRLIGHT" + lightIndex] = false;
  37826. defines["SPOTLIGHT" + lightIndex] = false;
  37827. defines["SHADOW" + lightIndex] = false;
  37828. }
  37829. }
  37830. var caps = scene.getEngine().getCaps();
  37831. if (defines["SHADOWFLOAT"] === undefined) {
  37832. needRebuild = true;
  37833. }
  37834. defines["SHADOWFLOAT"] = shadowEnabled &&
  37835. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37836. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37837. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37838. if (needRebuild) {
  37839. defines.rebuild();
  37840. }
  37841. return needNormals;
  37842. };
  37843. /**
  37844. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37845. * that won t be acctive due to defines being turned off.
  37846. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37847. * @param samplersList The samplers list
  37848. * @param defines The defines helping in the list generation
  37849. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37850. */
  37851. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37852. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37853. var uniformsList;
  37854. var uniformBuffersList = null;
  37855. if (uniformsListOrOptions.uniformsNames) {
  37856. var options = uniformsListOrOptions;
  37857. uniformsList = options.uniformsNames;
  37858. uniformBuffersList = options.uniformBuffersNames;
  37859. samplersList = options.samplers;
  37860. defines = options.defines;
  37861. maxSimultaneousLights = options.maxSimultaneousLights;
  37862. }
  37863. else {
  37864. uniformsList = uniformsListOrOptions;
  37865. if (!samplersList) {
  37866. samplersList = [];
  37867. }
  37868. }
  37869. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37870. if (!defines["LIGHT" + lightIndex]) {
  37871. break;
  37872. }
  37873. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37874. if (uniformBuffersList) {
  37875. uniformBuffersList.push("Light" + lightIndex);
  37876. }
  37877. samplersList.push("shadowSampler" + lightIndex);
  37878. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37879. samplersList.push("projectionLightSampler" + lightIndex);
  37880. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37881. }
  37882. }
  37883. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37884. uniformsList.push("morphTargetInfluences");
  37885. }
  37886. };
  37887. /**
  37888. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37889. * @param defines The defines to update while falling back
  37890. * @param fallbacks The authorized effect fallbacks
  37891. * @param maxSimultaneousLights The maximum number of lights allowed
  37892. * @param rank the current rank of the Effect
  37893. * @returns The newly affected rank
  37894. */
  37895. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37896. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37897. if (rank === void 0) { rank = 0; }
  37898. var lightFallbackRank = 0;
  37899. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37900. if (!defines["LIGHT" + lightIndex]) {
  37901. break;
  37902. }
  37903. if (lightIndex > 0) {
  37904. lightFallbackRank = rank + lightIndex;
  37905. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37906. }
  37907. if (!defines["SHADOWS"]) {
  37908. if (defines["SHADOW" + lightIndex]) {
  37909. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37910. }
  37911. if (defines["SHADOWPCF" + lightIndex]) {
  37912. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37913. }
  37914. if (defines["SHADOWESM" + lightIndex]) {
  37915. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37916. }
  37917. }
  37918. }
  37919. return lightFallbackRank++;
  37920. };
  37921. /**
  37922. * Prepares the list of attributes required for morph targets according to the effect defines.
  37923. * @param attribs The current list of supported attribs
  37924. * @param mesh The mesh to prepare the morph targets attributes for
  37925. * @param defines The current Defines of the effect
  37926. */
  37927. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37928. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37929. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37930. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37931. var manager = mesh.morphTargetManager;
  37932. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37933. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37934. for (var index = 0; index < influencers; index++) {
  37935. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37936. if (normal) {
  37937. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37938. }
  37939. if (tangent) {
  37940. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37941. }
  37942. if (attribs.length > maxAttributesCount) {
  37943. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37944. }
  37945. }
  37946. }
  37947. };
  37948. /**
  37949. * Prepares the list of attributes required for bones according to the effect defines.
  37950. * @param attribs The current list of supported attribs
  37951. * @param mesh The mesh to prepare the bones attributes for
  37952. * @param defines The current Defines of the effect
  37953. * @param fallbacks The current efffect fallback strategy
  37954. */
  37955. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37956. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37957. fallbacks.addCPUSkinningFallback(0, mesh);
  37958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37960. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37963. }
  37964. }
  37965. };
  37966. /**
  37967. * Prepares the list of attributes required for instances according to the effect defines.
  37968. * @param attribs The current list of supported attribs
  37969. * @param defines The current Defines of the effect
  37970. */
  37971. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37972. if (defines["INSTANCES"]) {
  37973. attribs.push("world0");
  37974. attribs.push("world1");
  37975. attribs.push("world2");
  37976. attribs.push("world3");
  37977. }
  37978. };
  37979. /**
  37980. * Binds the light shadow information to the effect for the given mesh.
  37981. * @param light The light containing the generator
  37982. * @param scene The scene the lights belongs to
  37983. * @param mesh The mesh we are binding the information to render
  37984. * @param lightIndex The light index in the effect used to render the mesh
  37985. * @param effect The effect we are binding the data to
  37986. */
  37987. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37988. if (light.shadowEnabled && mesh.receiveShadows) {
  37989. var shadowGenerator = light.getShadowGenerator();
  37990. if (shadowGenerator) {
  37991. shadowGenerator.bindShadowLight(lightIndex, effect);
  37992. }
  37993. }
  37994. };
  37995. /**
  37996. * Binds the light information to the effect.
  37997. * @param light The light containing the generator
  37998. * @param effect The effect we are binding the data to
  37999. * @param lightIndex The light index in the effect used to render
  38000. */
  38001. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38002. light.transferToEffect(effect, lightIndex + "");
  38003. };
  38004. /**
  38005. * Binds the lights information from the scene to the effect for the given mesh.
  38006. * @param scene The scene the lights belongs to
  38007. * @param mesh The mesh we are binding the information to render
  38008. * @param effect The effect we are binding the data to
  38009. * @param defines The generated defines for the effect
  38010. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38011. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38012. */
  38013. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38014. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38015. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38016. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38017. for (var i = 0; i < len; i++) {
  38018. var light = mesh._lightSources[i];
  38019. var iAsString = i.toString();
  38020. var scaledIntensity = light.getScaledIntensity();
  38021. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38022. MaterialHelper.BindLightProperties(light, effect, i);
  38023. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38024. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38025. if (defines["SPECULARTERM"]) {
  38026. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38027. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38028. }
  38029. // Shadows
  38030. if (scene.shadowsEnabled) {
  38031. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38032. }
  38033. light._uniformBuffer.update();
  38034. }
  38035. };
  38036. /**
  38037. * Binds the fog information from the scene to the effect for the given mesh.
  38038. * @param scene The scene the lights belongs to
  38039. * @param mesh The mesh we are binding the information to render
  38040. * @param effect The effect we are binding the data to
  38041. */
  38042. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38043. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38044. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38045. effect.setColor3("vFogColor", scene.fogColor);
  38046. }
  38047. };
  38048. /**
  38049. * Binds the bones information from the mesh to the effect.
  38050. * @param mesh The mesh we are binding the information to render
  38051. * @param effect The effect we are binding the data to
  38052. */
  38053. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38054. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38055. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38056. if (matrices && effect) {
  38057. effect.setMatrices("mBones", matrices);
  38058. }
  38059. }
  38060. };
  38061. /**
  38062. * Binds the morph targets information from the mesh to the effect.
  38063. * @param abstractMesh The mesh we are binding the information to render
  38064. * @param effect The effect we are binding the data to
  38065. */
  38066. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38067. var manager = abstractMesh.morphTargetManager;
  38068. if (!abstractMesh || !manager) {
  38069. return;
  38070. }
  38071. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38072. };
  38073. /**
  38074. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38075. * @param defines The generated defines used in the effect
  38076. * @param effect The effect we are binding the data to
  38077. * @param scene The scene we are willing to render with logarithmic scale for
  38078. */
  38079. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38080. if (defines["LOGARITHMICDEPTH"]) {
  38081. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38082. }
  38083. };
  38084. /**
  38085. * Binds the clip plane information from the scene to the effect.
  38086. * @param scene The scene the clip plane information are extracted from
  38087. * @param effect The effect we are binding the data to
  38088. */
  38089. MaterialHelper.BindClipPlane = function (effect, scene) {
  38090. if (scene.clipPlane) {
  38091. var clipPlane = scene.clipPlane;
  38092. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38093. }
  38094. };
  38095. return MaterialHelper;
  38096. }());
  38097. BABYLON.MaterialHelper = MaterialHelper;
  38098. })(BABYLON || (BABYLON = {}));
  38099. //# sourceMappingURL=babylon.materialHelper.js.map
  38100. var BABYLON;
  38101. (function (BABYLON) {
  38102. var PushMaterial = /** @class */ (function (_super) {
  38103. __extends(PushMaterial, _super);
  38104. function PushMaterial(name, scene) {
  38105. var _this = _super.call(this, name, scene) || this;
  38106. _this.storeEffectOnSubMeshes = true;
  38107. return _this;
  38108. }
  38109. PushMaterial.prototype.getEffect = function () {
  38110. return this._activeEffect;
  38111. };
  38112. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38113. if (!mesh) {
  38114. return false;
  38115. }
  38116. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38117. return true;
  38118. }
  38119. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38120. };
  38121. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38122. this._activeEffect.setMatrix("world", world);
  38123. };
  38124. PushMaterial.prototype.bind = function (world, mesh) {
  38125. if (!mesh) {
  38126. return;
  38127. }
  38128. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38129. };
  38130. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38131. if (effect === void 0) { effect = null; }
  38132. _super.prototype._afterBind.call(this, mesh);
  38133. this.getScene()._cachedEffect = effect;
  38134. };
  38135. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38136. if (visibility === void 0) { visibility = 1; }
  38137. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38138. };
  38139. return PushMaterial;
  38140. }(BABYLON.Material));
  38141. BABYLON.PushMaterial = PushMaterial;
  38142. })(BABYLON || (BABYLON = {}));
  38143. //# sourceMappingURL=babylon.pushMaterial.js.map
  38144. var BABYLON;
  38145. (function (BABYLON) {
  38146. /** @ignore */
  38147. var StandardMaterialDefines = /** @class */ (function (_super) {
  38148. __extends(StandardMaterialDefines, _super);
  38149. function StandardMaterialDefines() {
  38150. var _this = _super.call(this) || this;
  38151. _this.MAINUV1 = false;
  38152. _this.MAINUV2 = false;
  38153. _this.DIFFUSE = false;
  38154. _this.DIFFUSEDIRECTUV = 0;
  38155. _this.AMBIENT = false;
  38156. _this.AMBIENTDIRECTUV = 0;
  38157. _this.OPACITY = false;
  38158. _this.OPACITYDIRECTUV = 0;
  38159. _this.OPACITYRGB = false;
  38160. _this.REFLECTION = false;
  38161. _this.EMISSIVE = false;
  38162. _this.EMISSIVEDIRECTUV = 0;
  38163. _this.SPECULAR = false;
  38164. _this.SPECULARDIRECTUV = 0;
  38165. _this.BUMP = false;
  38166. _this.BUMPDIRECTUV = 0;
  38167. _this.PARALLAX = false;
  38168. _this.PARALLAXOCCLUSION = false;
  38169. _this.SPECULAROVERALPHA = false;
  38170. _this.CLIPPLANE = false;
  38171. _this.ALPHATEST = false;
  38172. _this.DEPTHPREPASS = false;
  38173. _this.ALPHAFROMDIFFUSE = false;
  38174. _this.POINTSIZE = false;
  38175. _this.FOG = false;
  38176. _this.SPECULARTERM = false;
  38177. _this.DIFFUSEFRESNEL = false;
  38178. _this.OPACITYFRESNEL = false;
  38179. _this.REFLECTIONFRESNEL = false;
  38180. _this.REFRACTIONFRESNEL = false;
  38181. _this.EMISSIVEFRESNEL = false;
  38182. _this.FRESNEL = false;
  38183. _this.NORMAL = false;
  38184. _this.UV1 = false;
  38185. _this.UV2 = false;
  38186. _this.VERTEXCOLOR = false;
  38187. _this.VERTEXALPHA = false;
  38188. _this.NUM_BONE_INFLUENCERS = 0;
  38189. _this.BonesPerMesh = 0;
  38190. _this.INSTANCES = false;
  38191. _this.GLOSSINESS = false;
  38192. _this.ROUGHNESS = false;
  38193. _this.EMISSIVEASILLUMINATION = false;
  38194. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38195. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38196. _this.LIGHTMAP = false;
  38197. _this.LIGHTMAPDIRECTUV = 0;
  38198. _this.USELIGHTMAPASSHADOWMAP = false;
  38199. _this.REFLECTIONMAP_3D = false;
  38200. _this.REFLECTIONMAP_SPHERICAL = false;
  38201. _this.REFLECTIONMAP_PLANAR = false;
  38202. _this.REFLECTIONMAP_CUBIC = false;
  38203. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38204. _this.REFLECTIONMAP_PROJECTION = false;
  38205. _this.REFLECTIONMAP_SKYBOX = false;
  38206. _this.REFLECTIONMAP_EXPLICIT = false;
  38207. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38208. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38209. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38210. _this.INVERTCUBICMAP = false;
  38211. _this.LOGARITHMICDEPTH = false;
  38212. _this.REFRACTION = false;
  38213. _this.REFRACTIONMAP_3D = false;
  38214. _this.REFLECTIONOVERALPHA = false;
  38215. _this.TWOSIDEDLIGHTING = false;
  38216. _this.SHADOWFLOAT = false;
  38217. _this.MORPHTARGETS = false;
  38218. _this.MORPHTARGETS_NORMAL = false;
  38219. _this.MORPHTARGETS_TANGENT = false;
  38220. _this.NUM_MORPH_INFLUENCERS = 0;
  38221. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38222. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38223. _this.IMAGEPROCESSING = false;
  38224. _this.VIGNETTE = false;
  38225. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38226. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38227. _this.TONEMAPPING = false;
  38228. _this.CONTRAST = false;
  38229. _this.COLORCURVES = false;
  38230. _this.COLORGRADING = false;
  38231. _this.COLORGRADING3D = false;
  38232. _this.SAMPLER3DGREENDEPTH = false;
  38233. _this.SAMPLER3DBGRMAP = false;
  38234. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38235. _this.EXPOSURE = false;
  38236. _this.rebuild();
  38237. return _this;
  38238. }
  38239. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38240. var modes = [
  38241. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38242. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38243. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38244. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38245. ];
  38246. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38247. var mode = modes_1[_i];
  38248. this[mode] = (mode === modeToEnable);
  38249. }
  38250. };
  38251. return StandardMaterialDefines;
  38252. }(BABYLON.MaterialDefines));
  38253. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38254. var StandardMaterial = /** @class */ (function (_super) {
  38255. __extends(StandardMaterial, _super);
  38256. function StandardMaterial(name, scene) {
  38257. var _this = _super.call(this, name, scene) || this;
  38258. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38259. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38260. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38261. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38262. _this.specularPower = 64;
  38263. _this._useAlphaFromDiffuseTexture = false;
  38264. _this._useEmissiveAsIllumination = false;
  38265. _this._linkEmissiveWithDiffuse = false;
  38266. _this._useSpecularOverAlpha = false;
  38267. _this._useReflectionOverAlpha = false;
  38268. _this._disableLighting = false;
  38269. _this._useParallax = false;
  38270. _this._useParallaxOcclusion = false;
  38271. _this.parallaxScaleBias = 0.05;
  38272. _this._roughness = 0;
  38273. _this.indexOfRefraction = 0.98;
  38274. _this.invertRefractionY = true;
  38275. _this._useLightmapAsShadowmap = false;
  38276. _this._useReflectionFresnelFromSpecular = false;
  38277. _this._useGlossinessFromSpecularMapAlpha = false;
  38278. _this._maxSimultaneousLights = 4;
  38279. /**
  38280. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38281. */
  38282. _this._invertNormalMapX = false;
  38283. /**
  38284. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38285. */
  38286. _this._invertNormalMapY = false;
  38287. /**
  38288. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38289. */
  38290. _this._twoSidedLighting = false;
  38291. _this._renderTargets = new BABYLON.SmartArray(16);
  38292. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38293. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38294. // Setup the default processing configuration to the scene.
  38295. _this._attachImageProcessingConfiguration(null);
  38296. _this.getRenderTargetTextures = function () {
  38297. _this._renderTargets.reset();
  38298. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38299. _this._renderTargets.push(_this._reflectionTexture);
  38300. }
  38301. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38302. _this._renderTargets.push(_this._refractionTexture);
  38303. }
  38304. return _this._renderTargets;
  38305. };
  38306. return _this;
  38307. }
  38308. ;
  38309. ;
  38310. ;
  38311. ;
  38312. ;
  38313. ;
  38314. ;
  38315. ;
  38316. ;
  38317. ;
  38318. ;
  38319. ;
  38320. ;
  38321. ;
  38322. ;
  38323. ;
  38324. ;
  38325. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38326. /**
  38327. * Gets the image processing configuration used either in this material.
  38328. */
  38329. get: function () {
  38330. return this._imageProcessingConfiguration;
  38331. },
  38332. /**
  38333. * Sets the Default image processing configuration used either in the this material.
  38334. *
  38335. * If sets to null, the scene one is in use.
  38336. */
  38337. set: function (value) {
  38338. this._attachImageProcessingConfiguration(value);
  38339. // Ensure the effect will be rebuilt.
  38340. this._markAllSubMeshesAsTexturesDirty();
  38341. },
  38342. enumerable: true,
  38343. configurable: true
  38344. });
  38345. /**
  38346. * Attaches a new image processing configuration to the Standard Material.
  38347. * @param configuration
  38348. */
  38349. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38350. var _this = this;
  38351. if (configuration === this._imageProcessingConfiguration) {
  38352. return;
  38353. }
  38354. // Detaches observer.
  38355. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38356. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38357. }
  38358. // Pick the scene configuration if needed.
  38359. if (!configuration) {
  38360. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38361. }
  38362. else {
  38363. this._imageProcessingConfiguration = configuration;
  38364. }
  38365. // Attaches observer.
  38366. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38367. _this._markAllSubMeshesAsImageProcessingDirty();
  38368. });
  38369. };
  38370. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38371. /**
  38372. * Gets wether the color curves effect is enabled.
  38373. */
  38374. get: function () {
  38375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38376. },
  38377. /**
  38378. * Sets wether the color curves effect is enabled.
  38379. */
  38380. set: function (value) {
  38381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38382. },
  38383. enumerable: true,
  38384. configurable: true
  38385. });
  38386. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38387. /**
  38388. * Gets wether the color grading effect is enabled.
  38389. */
  38390. get: function () {
  38391. return this.imageProcessingConfiguration.colorGradingEnabled;
  38392. },
  38393. /**
  38394. * Gets wether the color grading effect is enabled.
  38395. */
  38396. set: function (value) {
  38397. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38403. /**
  38404. * Gets wether tonemapping is enabled or not.
  38405. */
  38406. get: function () {
  38407. return this._imageProcessingConfiguration.toneMappingEnabled;
  38408. },
  38409. /**
  38410. * Sets wether tonemapping is enabled or not
  38411. */
  38412. set: function (value) {
  38413. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. ;
  38419. ;
  38420. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38421. /**
  38422. * The camera exposure used on this material.
  38423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38424. * This corresponds to a photographic exposure.
  38425. */
  38426. get: function () {
  38427. return this._imageProcessingConfiguration.exposure;
  38428. },
  38429. /**
  38430. * The camera exposure used on this material.
  38431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38432. * This corresponds to a photographic exposure.
  38433. */
  38434. set: function (value) {
  38435. this._imageProcessingConfiguration.exposure = value;
  38436. },
  38437. enumerable: true,
  38438. configurable: true
  38439. });
  38440. ;
  38441. ;
  38442. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38443. /**
  38444. * Gets The camera contrast used on this material.
  38445. */
  38446. get: function () {
  38447. return this._imageProcessingConfiguration.contrast;
  38448. },
  38449. /**
  38450. * Sets The camera contrast used on this material.
  38451. */
  38452. set: function (value) {
  38453. this._imageProcessingConfiguration.contrast = value;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38459. /**
  38460. * Gets the Color Grading 2D Lookup Texture.
  38461. */
  38462. get: function () {
  38463. return this._imageProcessingConfiguration.colorGradingTexture;
  38464. },
  38465. /**
  38466. * Sets the Color Grading 2D Lookup Texture.
  38467. */
  38468. set: function (value) {
  38469. this._imageProcessingConfiguration.colorGradingTexture = value;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38475. /**
  38476. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38477. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38478. * 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;
  38479. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38480. */
  38481. get: function () {
  38482. return this._imageProcessingConfiguration.colorCurves;
  38483. },
  38484. /**
  38485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38487. * 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;
  38488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38489. */
  38490. set: function (value) {
  38491. this._imageProcessingConfiguration.colorCurves = value;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. StandardMaterial.prototype.getClassName = function () {
  38497. return "StandardMaterial";
  38498. };
  38499. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38500. get: function () {
  38501. return this._useLogarithmicDepth;
  38502. },
  38503. set: function (value) {
  38504. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38505. this._markAllSubMeshesAsMiscDirty();
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. StandardMaterial.prototype.needAlphaBlending = function () {
  38511. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38512. };
  38513. StandardMaterial.prototype.needAlphaTesting = function () {
  38514. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38515. };
  38516. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38517. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38518. };
  38519. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38520. return this._diffuseTexture;
  38521. };
  38522. /**
  38523. * Child classes can use it to update shaders
  38524. */
  38525. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38526. if (useInstances === void 0) { useInstances = false; }
  38527. if (subMesh.effect && this.isFrozen) {
  38528. if (this._wasPreviouslyReady && subMesh.effect) {
  38529. return true;
  38530. }
  38531. }
  38532. if (!subMesh._materialDefines) {
  38533. subMesh._materialDefines = new StandardMaterialDefines();
  38534. }
  38535. var scene = this.getScene();
  38536. var defines = subMesh._materialDefines;
  38537. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38538. if (defines._renderId === scene.getRenderId()) {
  38539. return true;
  38540. }
  38541. }
  38542. var engine = scene.getEngine();
  38543. // Lights
  38544. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38545. // Textures
  38546. if (defines._areTexturesDirty) {
  38547. defines._needUVs = false;
  38548. defines.MAINUV1 = false;
  38549. defines.MAINUV2 = false;
  38550. if (scene.texturesEnabled) {
  38551. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38552. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38553. return false;
  38554. }
  38555. else {
  38556. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38557. }
  38558. }
  38559. else {
  38560. defines.DIFFUSE = false;
  38561. }
  38562. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38563. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38564. return false;
  38565. }
  38566. else {
  38567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38568. }
  38569. }
  38570. else {
  38571. defines.AMBIENT = false;
  38572. }
  38573. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38574. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38575. return false;
  38576. }
  38577. else {
  38578. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38579. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38580. }
  38581. }
  38582. else {
  38583. defines.OPACITY = false;
  38584. }
  38585. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38586. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38587. return false;
  38588. }
  38589. else {
  38590. defines._needNormals = true;
  38591. defines.REFLECTION = true;
  38592. defines.ROUGHNESS = (this._roughness > 0);
  38593. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38594. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38595. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38596. switch (this._reflectionTexture.coordinatesMode) {
  38597. case BABYLON.Texture.CUBIC_MODE:
  38598. case BABYLON.Texture.INVCUBIC_MODE:
  38599. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38600. break;
  38601. case BABYLON.Texture.EXPLICIT_MODE:
  38602. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38603. break;
  38604. case BABYLON.Texture.PLANAR_MODE:
  38605. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38606. break;
  38607. case BABYLON.Texture.PROJECTION_MODE:
  38608. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38609. break;
  38610. case BABYLON.Texture.SKYBOX_MODE:
  38611. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38612. break;
  38613. case BABYLON.Texture.SPHERICAL_MODE:
  38614. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38615. break;
  38616. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38617. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38618. break;
  38619. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38620. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38621. break;
  38622. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38623. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38624. break;
  38625. }
  38626. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38627. }
  38628. }
  38629. else {
  38630. defines.REFLECTION = false;
  38631. }
  38632. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38633. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38634. return false;
  38635. }
  38636. else {
  38637. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38638. }
  38639. }
  38640. else {
  38641. defines.EMISSIVE = false;
  38642. }
  38643. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38644. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38645. return false;
  38646. }
  38647. else {
  38648. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38649. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38650. }
  38651. }
  38652. else {
  38653. defines.LIGHTMAP = false;
  38654. }
  38655. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38656. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38657. return false;
  38658. }
  38659. else {
  38660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38661. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38662. }
  38663. }
  38664. else {
  38665. defines.SPECULAR = false;
  38666. }
  38667. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38668. // Bump texure can not be not blocking.
  38669. if (!this._bumpTexture.isReady()) {
  38670. return false;
  38671. }
  38672. else {
  38673. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38674. defines.PARALLAX = this._useParallax;
  38675. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38676. }
  38677. }
  38678. else {
  38679. defines.BUMP = false;
  38680. }
  38681. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38682. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38683. return false;
  38684. }
  38685. else {
  38686. defines._needUVs = true;
  38687. defines.REFRACTION = true;
  38688. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38689. }
  38690. }
  38691. else {
  38692. defines.REFRACTION = false;
  38693. }
  38694. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38695. }
  38696. else {
  38697. defines.DIFFUSE = false;
  38698. defines.AMBIENT = false;
  38699. defines.OPACITY = false;
  38700. defines.REFLECTION = false;
  38701. defines.EMISSIVE = false;
  38702. defines.LIGHTMAP = false;
  38703. defines.BUMP = false;
  38704. defines.REFRACTION = false;
  38705. }
  38706. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38707. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38708. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38709. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38710. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38711. }
  38712. if (defines._areImageProcessingDirty) {
  38713. if (!this._imageProcessingConfiguration.isReady()) {
  38714. return false;
  38715. }
  38716. this._imageProcessingConfiguration.prepareDefines(defines);
  38717. }
  38718. if (defines._areFresnelDirty) {
  38719. if (StandardMaterial.FresnelEnabled) {
  38720. // Fresnel
  38721. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38722. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38723. this._reflectionFresnelParameters) {
  38724. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38725. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38726. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38727. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38728. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38729. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38730. defines._needNormals = true;
  38731. defines.FRESNEL = true;
  38732. }
  38733. }
  38734. else {
  38735. defines.FRESNEL = false;
  38736. }
  38737. }
  38738. // Misc.
  38739. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38740. // Attribs
  38741. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38742. // Values that need to be evaluated on every frame
  38743. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38744. // Get correct effect
  38745. if (defines.isDirty) {
  38746. defines.markAsProcessed();
  38747. scene.resetCachedMaterial();
  38748. // Fallbacks
  38749. var fallbacks = new BABYLON.EffectFallbacks();
  38750. if (defines.REFLECTION) {
  38751. fallbacks.addFallback(0, "REFLECTION");
  38752. }
  38753. if (defines.SPECULAR) {
  38754. fallbacks.addFallback(0, "SPECULAR");
  38755. }
  38756. if (defines.BUMP) {
  38757. fallbacks.addFallback(0, "BUMP");
  38758. }
  38759. if (defines.PARALLAX) {
  38760. fallbacks.addFallback(1, "PARALLAX");
  38761. }
  38762. if (defines.PARALLAXOCCLUSION) {
  38763. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38764. }
  38765. if (defines.SPECULAROVERALPHA) {
  38766. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38767. }
  38768. if (defines.FOG) {
  38769. fallbacks.addFallback(1, "FOG");
  38770. }
  38771. if (defines.POINTSIZE) {
  38772. fallbacks.addFallback(0, "POINTSIZE");
  38773. }
  38774. if (defines.LOGARITHMICDEPTH) {
  38775. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38776. }
  38777. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38778. if (defines.SPECULARTERM) {
  38779. fallbacks.addFallback(0, "SPECULARTERM");
  38780. }
  38781. if (defines.DIFFUSEFRESNEL) {
  38782. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38783. }
  38784. if (defines.OPACITYFRESNEL) {
  38785. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38786. }
  38787. if (defines.REFLECTIONFRESNEL) {
  38788. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38789. }
  38790. if (defines.EMISSIVEFRESNEL) {
  38791. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38792. }
  38793. if (defines.FRESNEL) {
  38794. fallbacks.addFallback(4, "FRESNEL");
  38795. }
  38796. //Attributes
  38797. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38798. if (defines.NORMAL) {
  38799. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38800. }
  38801. if (defines.UV1) {
  38802. attribs.push(BABYLON.VertexBuffer.UVKind);
  38803. }
  38804. if (defines.UV2) {
  38805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38806. }
  38807. if (defines.VERTEXCOLOR) {
  38808. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38809. }
  38810. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38811. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38812. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38813. var shaderName = "default";
  38814. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38815. "vFogInfos", "vFogColor", "pointSize",
  38816. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38817. "mBones",
  38818. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38819. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38820. "vReflectionPosition", "vReflectionSize",
  38821. "logarithmicDepthConstant", "vTangentSpaceParams"
  38822. ];
  38823. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38824. var uniformBuffers = ["Material", "Scene"];
  38825. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38826. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38827. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38828. uniformsNames: uniforms,
  38829. uniformBuffersNames: uniformBuffers,
  38830. samplers: samplers,
  38831. defines: defines,
  38832. maxSimultaneousLights: this._maxSimultaneousLights
  38833. });
  38834. if (this.customShaderNameResolve) {
  38835. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38836. }
  38837. var join = defines.toString();
  38838. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38839. attributes: attribs,
  38840. uniformsNames: uniforms,
  38841. uniformBuffersNames: uniformBuffers,
  38842. samplers: samplers,
  38843. defines: join,
  38844. fallbacks: fallbacks,
  38845. onCompiled: this.onCompiled,
  38846. onError: this.onError,
  38847. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38848. }, engine), defines);
  38849. this.buildUniformLayout();
  38850. }
  38851. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38852. return false;
  38853. }
  38854. defines._renderId = scene.getRenderId();
  38855. this._wasPreviouslyReady = true;
  38856. return true;
  38857. };
  38858. StandardMaterial.prototype.buildUniformLayout = function () {
  38859. // Order is important !
  38860. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38861. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38862. this._uniformBuffer.addUniform("opacityParts", 4);
  38863. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38864. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38865. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38866. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38867. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38868. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38869. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38870. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38871. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38872. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38873. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38874. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38875. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38876. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38877. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38878. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38879. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38880. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38881. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38882. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38883. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38884. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38885. this._uniformBuffer.addUniform("specularMatrix", 16);
  38886. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38887. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38888. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38889. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38890. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38891. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38892. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38893. this._uniformBuffer.addUniform("pointSize", 1);
  38894. this._uniformBuffer.create();
  38895. };
  38896. StandardMaterial.prototype.unbind = function () {
  38897. if (this._activeEffect) {
  38898. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38899. this._activeEffect.setTexture("reflection2DSampler", null);
  38900. }
  38901. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38902. this._activeEffect.setTexture("refraction2DSampler", null);
  38903. }
  38904. }
  38905. _super.prototype.unbind.call(this);
  38906. };
  38907. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38908. var scene = this.getScene();
  38909. var defines = subMesh._materialDefines;
  38910. if (!defines) {
  38911. return;
  38912. }
  38913. var effect = subMesh.effect;
  38914. if (!effect) {
  38915. return;
  38916. }
  38917. this._activeEffect = effect;
  38918. // Matrices
  38919. this.bindOnlyWorldMatrix(world);
  38920. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38921. // Bones
  38922. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38923. if (mustRebind) {
  38924. this._uniformBuffer.bindToEffect(effect, "Material");
  38925. this.bindViewProjection(effect);
  38926. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38927. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38928. // Fresnel
  38929. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38930. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38931. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38932. }
  38933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38934. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38935. }
  38936. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38937. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38938. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38939. }
  38940. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38941. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38942. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38943. }
  38944. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38945. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38946. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38947. }
  38948. }
  38949. // Textures
  38950. if (scene.texturesEnabled) {
  38951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38952. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38953. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38954. }
  38955. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38956. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38957. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38958. }
  38959. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38960. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38961. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38962. }
  38963. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38964. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38965. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38966. if (this._reflectionTexture.boundingBoxSize) {
  38967. var cubeTexture = this._reflectionTexture;
  38968. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38969. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38970. }
  38971. }
  38972. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38973. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38974. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38975. }
  38976. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38977. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38978. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38979. }
  38980. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38981. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38982. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38983. }
  38984. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38985. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38986. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38987. if (scene._mirroredCameraPosition) {
  38988. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38989. }
  38990. else {
  38991. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38992. }
  38993. }
  38994. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38995. var depth = 1.0;
  38996. if (!this._refractionTexture.isCube) {
  38997. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38998. if (this._refractionTexture.depth) {
  38999. depth = this._refractionTexture.depth;
  39000. }
  39001. }
  39002. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39003. }
  39004. }
  39005. // Point size
  39006. if (this.pointsCloud) {
  39007. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39008. }
  39009. if (defines.SPECULARTERM) {
  39010. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39011. }
  39012. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39013. // Diffuse
  39014. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39015. }
  39016. // Textures
  39017. if (scene.texturesEnabled) {
  39018. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39019. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39020. }
  39021. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39022. effect.setTexture("ambientSampler", this._ambientTexture);
  39023. }
  39024. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39025. effect.setTexture("opacitySampler", this._opacityTexture);
  39026. }
  39027. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39028. if (this._reflectionTexture.isCube) {
  39029. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39030. }
  39031. else {
  39032. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39033. }
  39034. }
  39035. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39036. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39037. }
  39038. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39039. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39040. }
  39041. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39042. effect.setTexture("specularSampler", this._specularTexture);
  39043. }
  39044. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39045. effect.setTexture("bumpSampler", this._bumpTexture);
  39046. }
  39047. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39048. var depth = 1.0;
  39049. if (this._refractionTexture.isCube) {
  39050. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39051. }
  39052. else {
  39053. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39054. }
  39055. }
  39056. }
  39057. // Clip plane
  39058. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39059. // Colors
  39060. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39061. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39062. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39063. }
  39064. if (mustRebind || !this.isFrozen) {
  39065. // Lights
  39066. if (scene.lightsEnabled && !this._disableLighting) {
  39067. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39068. }
  39069. // View
  39070. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39071. this.bindView(effect);
  39072. }
  39073. // Fog
  39074. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39075. // Morph targets
  39076. if (defines.NUM_MORPH_INFLUENCERS) {
  39077. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39078. }
  39079. // Log. depth
  39080. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39081. // image processing
  39082. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39083. this._imageProcessingConfiguration.bind(this._activeEffect);
  39084. }
  39085. }
  39086. this._uniformBuffer.update();
  39087. this._afterBind(mesh, this._activeEffect);
  39088. };
  39089. StandardMaterial.prototype.getAnimatables = function () {
  39090. var results = [];
  39091. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39092. results.push(this._diffuseTexture);
  39093. }
  39094. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39095. results.push(this._ambientTexture);
  39096. }
  39097. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39098. results.push(this._opacityTexture);
  39099. }
  39100. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39101. results.push(this._reflectionTexture);
  39102. }
  39103. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39104. results.push(this._emissiveTexture);
  39105. }
  39106. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39107. results.push(this._specularTexture);
  39108. }
  39109. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39110. results.push(this._bumpTexture);
  39111. }
  39112. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39113. results.push(this._lightmapTexture);
  39114. }
  39115. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39116. results.push(this._refractionTexture);
  39117. }
  39118. return results;
  39119. };
  39120. StandardMaterial.prototype.getActiveTextures = function () {
  39121. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39122. if (this._diffuseTexture) {
  39123. activeTextures.push(this._diffuseTexture);
  39124. }
  39125. if (this._ambientTexture) {
  39126. activeTextures.push(this._ambientTexture);
  39127. }
  39128. if (this._opacityTexture) {
  39129. activeTextures.push(this._opacityTexture);
  39130. }
  39131. if (this._reflectionTexture) {
  39132. activeTextures.push(this._reflectionTexture);
  39133. }
  39134. if (this._emissiveTexture) {
  39135. activeTextures.push(this._emissiveTexture);
  39136. }
  39137. if (this._specularTexture) {
  39138. activeTextures.push(this._specularTexture);
  39139. }
  39140. if (this._bumpTexture) {
  39141. activeTextures.push(this._bumpTexture);
  39142. }
  39143. if (this._lightmapTexture) {
  39144. activeTextures.push(this._lightmapTexture);
  39145. }
  39146. if (this._refractionTexture) {
  39147. activeTextures.push(this._refractionTexture);
  39148. }
  39149. return activeTextures;
  39150. };
  39151. StandardMaterial.prototype.hasTexture = function (texture) {
  39152. if (_super.prototype.hasTexture.call(this, texture)) {
  39153. return true;
  39154. }
  39155. if (this._diffuseTexture === texture) {
  39156. return true;
  39157. }
  39158. if (this._ambientTexture === texture) {
  39159. return true;
  39160. }
  39161. if (this._opacityTexture === texture) {
  39162. return true;
  39163. }
  39164. if (this._reflectionTexture === texture) {
  39165. return true;
  39166. }
  39167. if (this._emissiveTexture === texture) {
  39168. return true;
  39169. }
  39170. if (this._specularTexture === texture) {
  39171. return true;
  39172. }
  39173. if (this._bumpTexture === texture) {
  39174. return true;
  39175. }
  39176. if (this._lightmapTexture === texture) {
  39177. return true;
  39178. }
  39179. if (this._refractionTexture === texture) {
  39180. return true;
  39181. }
  39182. return false;
  39183. };
  39184. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39185. if (forceDisposeTextures) {
  39186. if (this._diffuseTexture) {
  39187. this._diffuseTexture.dispose();
  39188. }
  39189. if (this._ambientTexture) {
  39190. this._ambientTexture.dispose();
  39191. }
  39192. if (this._opacityTexture) {
  39193. this._opacityTexture.dispose();
  39194. }
  39195. if (this._reflectionTexture) {
  39196. this._reflectionTexture.dispose();
  39197. }
  39198. if (this._emissiveTexture) {
  39199. this._emissiveTexture.dispose();
  39200. }
  39201. if (this._specularTexture) {
  39202. this._specularTexture.dispose();
  39203. }
  39204. if (this._bumpTexture) {
  39205. this._bumpTexture.dispose();
  39206. }
  39207. if (this._lightmapTexture) {
  39208. this._lightmapTexture.dispose();
  39209. }
  39210. if (this._refractionTexture) {
  39211. this._refractionTexture.dispose();
  39212. }
  39213. }
  39214. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39215. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39216. }
  39217. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39218. };
  39219. StandardMaterial.prototype.clone = function (name) {
  39220. var _this = this;
  39221. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39222. result.name = name;
  39223. result.id = name;
  39224. return result;
  39225. };
  39226. StandardMaterial.prototype.serialize = function () {
  39227. return BABYLON.SerializationHelper.Serialize(this);
  39228. };
  39229. // Statics
  39230. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39231. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39232. };
  39233. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39234. get: function () {
  39235. return StandardMaterial._DiffuseTextureEnabled;
  39236. },
  39237. set: function (value) {
  39238. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39239. return;
  39240. }
  39241. StandardMaterial._DiffuseTextureEnabled = value;
  39242. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39248. get: function () {
  39249. return StandardMaterial._AmbientTextureEnabled;
  39250. },
  39251. set: function (value) {
  39252. if (StandardMaterial._AmbientTextureEnabled === value) {
  39253. return;
  39254. }
  39255. StandardMaterial._AmbientTextureEnabled = value;
  39256. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39257. },
  39258. enumerable: true,
  39259. configurable: true
  39260. });
  39261. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39262. get: function () {
  39263. return StandardMaterial._OpacityTextureEnabled;
  39264. },
  39265. set: function (value) {
  39266. if (StandardMaterial._OpacityTextureEnabled === value) {
  39267. return;
  39268. }
  39269. StandardMaterial._OpacityTextureEnabled = value;
  39270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39276. get: function () {
  39277. return StandardMaterial._ReflectionTextureEnabled;
  39278. },
  39279. set: function (value) {
  39280. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39281. return;
  39282. }
  39283. StandardMaterial._ReflectionTextureEnabled = value;
  39284. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39290. get: function () {
  39291. return StandardMaterial._EmissiveTextureEnabled;
  39292. },
  39293. set: function (value) {
  39294. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39295. return;
  39296. }
  39297. StandardMaterial._EmissiveTextureEnabled = value;
  39298. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39304. get: function () {
  39305. return StandardMaterial._SpecularTextureEnabled;
  39306. },
  39307. set: function (value) {
  39308. if (StandardMaterial._SpecularTextureEnabled === value) {
  39309. return;
  39310. }
  39311. StandardMaterial._SpecularTextureEnabled = value;
  39312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39318. get: function () {
  39319. return StandardMaterial._BumpTextureEnabled;
  39320. },
  39321. set: function (value) {
  39322. if (StandardMaterial._BumpTextureEnabled === value) {
  39323. return;
  39324. }
  39325. StandardMaterial._BumpTextureEnabled = value;
  39326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39332. get: function () {
  39333. return StandardMaterial._LightmapTextureEnabled;
  39334. },
  39335. set: function (value) {
  39336. if (StandardMaterial._LightmapTextureEnabled === value) {
  39337. return;
  39338. }
  39339. StandardMaterial._LightmapTextureEnabled = value;
  39340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39346. get: function () {
  39347. return StandardMaterial._RefractionTextureEnabled;
  39348. },
  39349. set: function (value) {
  39350. if (StandardMaterial._RefractionTextureEnabled === value) {
  39351. return;
  39352. }
  39353. StandardMaterial._RefractionTextureEnabled = value;
  39354. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39355. },
  39356. enumerable: true,
  39357. configurable: true
  39358. });
  39359. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39360. get: function () {
  39361. return StandardMaterial._ColorGradingTextureEnabled;
  39362. },
  39363. set: function (value) {
  39364. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39365. return;
  39366. }
  39367. StandardMaterial._ColorGradingTextureEnabled = value;
  39368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39369. },
  39370. enumerable: true,
  39371. configurable: true
  39372. });
  39373. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39374. get: function () {
  39375. return StandardMaterial._FresnelEnabled;
  39376. },
  39377. set: function (value) {
  39378. if (StandardMaterial._FresnelEnabled === value) {
  39379. return;
  39380. }
  39381. StandardMaterial._FresnelEnabled = value;
  39382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39383. },
  39384. enumerable: true,
  39385. configurable: true
  39386. });
  39387. // Flags used to enable or disable a type of texture for all Standard Materials
  39388. StandardMaterial._DiffuseTextureEnabled = true;
  39389. StandardMaterial._AmbientTextureEnabled = true;
  39390. StandardMaterial._OpacityTextureEnabled = true;
  39391. StandardMaterial._ReflectionTextureEnabled = true;
  39392. StandardMaterial._EmissiveTextureEnabled = true;
  39393. StandardMaterial._SpecularTextureEnabled = true;
  39394. StandardMaterial._BumpTextureEnabled = true;
  39395. StandardMaterial._LightmapTextureEnabled = true;
  39396. StandardMaterial._RefractionTextureEnabled = true;
  39397. StandardMaterial._ColorGradingTextureEnabled = true;
  39398. StandardMaterial._FresnelEnabled = true;
  39399. __decorate([
  39400. BABYLON.serializeAsTexture("diffuseTexture")
  39401. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39402. __decorate([
  39403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39404. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39405. __decorate([
  39406. BABYLON.serializeAsTexture("ambientTexture")
  39407. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39408. __decorate([
  39409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39410. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39411. __decorate([
  39412. BABYLON.serializeAsTexture("opacityTexture")
  39413. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39414. __decorate([
  39415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39416. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39417. __decorate([
  39418. BABYLON.serializeAsTexture("reflectionTexture")
  39419. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39420. __decorate([
  39421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39422. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39423. __decorate([
  39424. BABYLON.serializeAsTexture("emissiveTexture")
  39425. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39426. __decorate([
  39427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39428. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39429. __decorate([
  39430. BABYLON.serializeAsTexture("specularTexture")
  39431. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39432. __decorate([
  39433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39434. ], StandardMaterial.prototype, "specularTexture", void 0);
  39435. __decorate([
  39436. BABYLON.serializeAsTexture("bumpTexture")
  39437. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39438. __decorate([
  39439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39440. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsTexture("lightmapTexture")
  39443. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39444. __decorate([
  39445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39446. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39447. __decorate([
  39448. BABYLON.serializeAsTexture("refractionTexture")
  39449. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39450. __decorate([
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39452. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39453. __decorate([
  39454. BABYLON.serializeAsColor3("ambient")
  39455. ], StandardMaterial.prototype, "ambientColor", void 0);
  39456. __decorate([
  39457. BABYLON.serializeAsColor3("diffuse")
  39458. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39459. __decorate([
  39460. BABYLON.serializeAsColor3("specular")
  39461. ], StandardMaterial.prototype, "specularColor", void 0);
  39462. __decorate([
  39463. BABYLON.serializeAsColor3("emissive")
  39464. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39465. __decorate([
  39466. BABYLON.serialize()
  39467. ], StandardMaterial.prototype, "specularPower", void 0);
  39468. __decorate([
  39469. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39470. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39471. __decorate([
  39472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39473. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39474. __decorate([
  39475. BABYLON.serialize("useEmissiveAsIllumination")
  39476. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39477. __decorate([
  39478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39479. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39480. __decorate([
  39481. BABYLON.serialize("linkEmissiveWithDiffuse")
  39482. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39483. __decorate([
  39484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39485. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39486. __decorate([
  39487. BABYLON.serialize("useSpecularOverAlpha")
  39488. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39489. __decorate([
  39490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39491. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39492. __decorate([
  39493. BABYLON.serialize("useReflectionOverAlpha")
  39494. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39495. __decorate([
  39496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39497. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39498. __decorate([
  39499. BABYLON.serialize("disableLighting")
  39500. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39501. __decorate([
  39502. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39503. ], StandardMaterial.prototype, "disableLighting", void 0);
  39504. __decorate([
  39505. BABYLON.serialize("useParallax")
  39506. ], StandardMaterial.prototype, "_useParallax", void 0);
  39507. __decorate([
  39508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39509. ], StandardMaterial.prototype, "useParallax", void 0);
  39510. __decorate([
  39511. BABYLON.serialize("useParallaxOcclusion")
  39512. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39513. __decorate([
  39514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39515. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39516. __decorate([
  39517. BABYLON.serialize()
  39518. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39519. __decorate([
  39520. BABYLON.serialize("roughness")
  39521. ], StandardMaterial.prototype, "_roughness", void 0);
  39522. __decorate([
  39523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39524. ], StandardMaterial.prototype, "roughness", void 0);
  39525. __decorate([
  39526. BABYLON.serialize()
  39527. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39528. __decorate([
  39529. BABYLON.serialize()
  39530. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39531. __decorate([
  39532. BABYLON.serialize("useLightmapAsShadowmap")
  39533. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39534. __decorate([
  39535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39536. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39537. __decorate([
  39538. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39539. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39540. __decorate([
  39541. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39542. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39543. __decorate([
  39544. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39545. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39546. __decorate([
  39547. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39548. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39549. __decorate([
  39550. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39551. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39552. __decorate([
  39553. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39554. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39555. __decorate([
  39556. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39557. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39558. __decorate([
  39559. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39560. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39561. __decorate([
  39562. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39563. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39564. __decorate([
  39565. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39566. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39567. __decorate([
  39568. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39569. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39570. __decorate([
  39571. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39572. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39573. __decorate([
  39574. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39575. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39576. __decorate([
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39578. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39579. __decorate([
  39580. BABYLON.serialize("maxSimultaneousLights")
  39581. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39582. __decorate([
  39583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39584. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39585. __decorate([
  39586. BABYLON.serialize("invertNormalMapX")
  39587. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39588. __decorate([
  39589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39590. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39591. __decorate([
  39592. BABYLON.serialize("invertNormalMapY")
  39593. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39594. __decorate([
  39595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39596. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39597. __decorate([
  39598. BABYLON.serialize("twoSidedLighting")
  39599. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39600. __decorate([
  39601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39602. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39603. __decorate([
  39604. BABYLON.serialize()
  39605. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39606. return StandardMaterial;
  39607. }(BABYLON.PushMaterial));
  39608. BABYLON.StandardMaterial = StandardMaterial;
  39609. })(BABYLON || (BABYLON = {}));
  39610. //# sourceMappingURL=babylon.standardMaterial.js.map
  39611. var BABYLON;
  39612. (function (BABYLON) {
  39613. /**
  39614. * Manages the defines for the PBR Material.
  39615. */
  39616. var PBRMaterialDefines = /** @class */ (function (_super) {
  39617. __extends(PBRMaterialDefines, _super);
  39618. /**
  39619. * Initializes the PBR Material defines.
  39620. */
  39621. function PBRMaterialDefines() {
  39622. var _this = _super.call(this) || this;
  39623. _this.PBR = true;
  39624. _this.MAINUV1 = false;
  39625. _this.MAINUV2 = false;
  39626. _this.UV1 = false;
  39627. _this.UV2 = false;
  39628. _this.ALBEDO = false;
  39629. _this.ALBEDODIRECTUV = 0;
  39630. _this.VERTEXCOLOR = false;
  39631. _this.AMBIENT = false;
  39632. _this.AMBIENTDIRECTUV = 0;
  39633. _this.AMBIENTINGRAYSCALE = false;
  39634. _this.OPACITY = false;
  39635. _this.VERTEXALPHA = false;
  39636. _this.OPACITYDIRECTUV = 0;
  39637. _this.OPACITYRGB = false;
  39638. _this.ALPHATEST = false;
  39639. _this.DEPTHPREPASS = false;
  39640. _this.ALPHABLEND = false;
  39641. _this.ALPHAFROMALBEDO = false;
  39642. _this.ALPHATESTVALUE = 0.5;
  39643. _this.SPECULAROVERALPHA = false;
  39644. _this.RADIANCEOVERALPHA = false;
  39645. _this.ALPHAFRESNEL = false;
  39646. _this.LINEARALPHAFRESNEL = false;
  39647. _this.PREMULTIPLYALPHA = false;
  39648. _this.EMISSIVE = false;
  39649. _this.EMISSIVEDIRECTUV = 0;
  39650. _this.REFLECTIVITY = false;
  39651. _this.REFLECTIVITYDIRECTUV = 0;
  39652. _this.SPECULARTERM = false;
  39653. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39654. _this.MICROSURFACEAUTOMATIC = false;
  39655. _this.LODBASEDMICROSFURACE = false;
  39656. _this.MICROSURFACEMAP = false;
  39657. _this.MICROSURFACEMAPDIRECTUV = 0;
  39658. _this.METALLICWORKFLOW = false;
  39659. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39660. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39661. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39662. _this.AOSTOREINMETALMAPRED = false;
  39663. _this.ENVIRONMENTBRDF = false;
  39664. _this.NORMAL = false;
  39665. _this.TANGENT = false;
  39666. _this.BUMP = false;
  39667. _this.BUMPDIRECTUV = 0;
  39668. _this.PARALLAX = false;
  39669. _this.PARALLAXOCCLUSION = false;
  39670. _this.NORMALXYSCALE = true;
  39671. _this.LIGHTMAP = false;
  39672. _this.LIGHTMAPDIRECTUV = 0;
  39673. _this.USELIGHTMAPASSHADOWMAP = false;
  39674. _this.REFLECTION = false;
  39675. _this.REFLECTIONMAP_3D = false;
  39676. _this.REFLECTIONMAP_SPHERICAL = false;
  39677. _this.REFLECTIONMAP_PLANAR = false;
  39678. _this.REFLECTIONMAP_CUBIC = false;
  39679. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39680. _this.REFLECTIONMAP_PROJECTION = false;
  39681. _this.REFLECTIONMAP_SKYBOX = false;
  39682. _this.REFLECTIONMAP_EXPLICIT = false;
  39683. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39684. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39685. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39686. _this.INVERTCUBICMAP = false;
  39687. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39688. _this.USESPHERICALINVERTEX = false;
  39689. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39690. _this.LODINREFLECTIONALPHA = false;
  39691. _this.GAMMAREFLECTION = false;
  39692. _this.RADIANCEOCCLUSION = false;
  39693. _this.HORIZONOCCLUSION = false;
  39694. _this.REFRACTION = false;
  39695. _this.REFRACTIONMAP_3D = false;
  39696. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39697. _this.LODINREFRACTIONALPHA = false;
  39698. _this.GAMMAREFRACTION = false;
  39699. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39700. _this.INSTANCES = false;
  39701. _this.NUM_BONE_INFLUENCERS = 0;
  39702. _this.BonesPerMesh = 0;
  39703. _this.NONUNIFORMSCALING = false;
  39704. _this.MORPHTARGETS = false;
  39705. _this.MORPHTARGETS_NORMAL = false;
  39706. _this.MORPHTARGETS_TANGENT = false;
  39707. _this.NUM_MORPH_INFLUENCERS = 0;
  39708. _this.IMAGEPROCESSING = false;
  39709. _this.VIGNETTE = false;
  39710. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39711. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39712. _this.TONEMAPPING = false;
  39713. _this.CONTRAST = false;
  39714. _this.COLORCURVES = false;
  39715. _this.COLORGRADING = false;
  39716. _this.COLORGRADING3D = false;
  39717. _this.SAMPLER3DGREENDEPTH = false;
  39718. _this.SAMPLER3DBGRMAP = false;
  39719. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39720. _this.EXPOSURE = false;
  39721. _this.USEPHYSICALLIGHTFALLOFF = false;
  39722. _this.TWOSIDEDLIGHTING = false;
  39723. _this.SHADOWFLOAT = false;
  39724. _this.CLIPPLANE = false;
  39725. _this.POINTSIZE = false;
  39726. _this.FOG = false;
  39727. _this.LOGARITHMICDEPTH = false;
  39728. _this.FORCENORMALFORWARD = false;
  39729. _this.rebuild();
  39730. return _this;
  39731. }
  39732. /**
  39733. * Resets the PBR Material defines.
  39734. */
  39735. PBRMaterialDefines.prototype.reset = function () {
  39736. _super.prototype.reset.call(this);
  39737. this.ALPHATESTVALUE = 0.5;
  39738. this.PBR = true;
  39739. };
  39740. return PBRMaterialDefines;
  39741. }(BABYLON.MaterialDefines));
  39742. /**
  39743. * The Physically based material base class of BJS.
  39744. *
  39745. * This offers the main features of a standard PBR material.
  39746. * For more information, please refer to the documentation :
  39747. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39748. */
  39749. var PBRBaseMaterial = /** @class */ (function (_super) {
  39750. __extends(PBRBaseMaterial, _super);
  39751. /**
  39752. * Instantiates a new PBRMaterial instance.
  39753. *
  39754. * @param name The material name
  39755. * @param scene The scene the material will be use in.
  39756. */
  39757. function PBRBaseMaterial(name, scene) {
  39758. var _this = _super.call(this, name, scene) || this;
  39759. /**
  39760. * Intensity of the direct lights e.g. the four lights available in your scene.
  39761. * This impacts both the direct diffuse and specular highlights.
  39762. */
  39763. _this._directIntensity = 1.0;
  39764. /**
  39765. * Intensity of the emissive part of the material.
  39766. * This helps controlling the emissive effect without modifying the emissive color.
  39767. */
  39768. _this._emissiveIntensity = 1.0;
  39769. /**
  39770. * Intensity of the environment e.g. how much the environment will light the object
  39771. * either through harmonics for rough material or through the refelction for shiny ones.
  39772. */
  39773. _this._environmentIntensity = 1.0;
  39774. /**
  39775. * This is a special control allowing the reduction of the specular highlights coming from the
  39776. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39777. */
  39778. _this._specularIntensity = 1.0;
  39779. /**
  39780. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39781. */
  39782. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39783. /**
  39784. * Debug Control allowing disabling the bump map on this material.
  39785. */
  39786. _this._disableBumpMap = false;
  39787. /**
  39788. * AKA Occlusion Texture Intensity in other nomenclature.
  39789. */
  39790. _this._ambientTextureStrength = 1.0;
  39791. /**
  39792. * The color of a material in ambient lighting.
  39793. */
  39794. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39795. /**
  39796. * AKA Diffuse Color in other nomenclature.
  39797. */
  39798. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39799. /**
  39800. * AKA Specular Color in other nomenclature.
  39801. */
  39802. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39803. /**
  39804. * The color applied when light is reflected from a material.
  39805. */
  39806. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39807. /**
  39808. * The color applied when light is emitted from a material.
  39809. */
  39810. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39811. /**
  39812. * AKA Glossiness in other nomenclature.
  39813. */
  39814. _this._microSurface = 0.9;
  39815. /**
  39816. * source material index of refraction (IOR)' / 'destination material IOR.
  39817. */
  39818. _this._indexOfRefraction = 0.66;
  39819. /**
  39820. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39821. */
  39822. _this._invertRefractionY = false;
  39823. /**
  39824. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39825. * Materials half opaque for instance using refraction could benefit from this control.
  39826. */
  39827. _this._linkRefractionWithTransparency = false;
  39828. /**
  39829. * Specifies that the material will use the light map as a show map.
  39830. */
  39831. _this._useLightmapAsShadowmap = false;
  39832. /**
  39833. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39834. * makes the reflect vector face the model (under horizon).
  39835. */
  39836. _this._useHorizonOcclusion = true;
  39837. /**
  39838. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39839. * too much the area relying on ambient texture to define their ambient occlusion.
  39840. */
  39841. _this._useRadianceOcclusion = true;
  39842. /**
  39843. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39844. */
  39845. _this._useAlphaFromAlbedoTexture = false;
  39846. /**
  39847. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39848. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39849. */
  39850. _this._useSpecularOverAlpha = true;
  39851. /**
  39852. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39853. */
  39854. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39855. /**
  39856. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39857. */
  39858. _this._useRoughnessFromMetallicTextureAlpha = true;
  39859. /**
  39860. * Specifies if the metallic texture contains the roughness information in its green channel.
  39861. */
  39862. _this._useRoughnessFromMetallicTextureGreen = false;
  39863. /**
  39864. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39865. */
  39866. _this._useMetallnessFromMetallicTextureBlue = false;
  39867. /**
  39868. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39869. */
  39870. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39871. /**
  39872. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39873. */
  39874. _this._useAmbientInGrayScale = false;
  39875. /**
  39876. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39877. * The material will try to infer what glossiness each pixel should be.
  39878. */
  39879. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39880. /**
  39881. * BJS is using an harcoded light falloff based on a manually sets up range.
  39882. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39883. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39884. */
  39885. _this._usePhysicalLightFalloff = true;
  39886. /**
  39887. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39888. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39889. */
  39890. _this._useRadianceOverAlpha = true;
  39891. /**
  39892. * Allows using the bump map in parallax mode.
  39893. */
  39894. _this._useParallax = false;
  39895. /**
  39896. * Allows using the bump map in parallax occlusion mode.
  39897. */
  39898. _this._useParallaxOcclusion = false;
  39899. /**
  39900. * Controls the scale bias of the parallax mode.
  39901. */
  39902. _this._parallaxScaleBias = 0.05;
  39903. /**
  39904. * If sets to true, disables all the lights affecting the material.
  39905. */
  39906. _this._disableLighting = false;
  39907. /**
  39908. * Number of Simultaneous lights allowed on the material.
  39909. */
  39910. _this._maxSimultaneousLights = 4;
  39911. /**
  39912. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39913. */
  39914. _this._invertNormalMapX = false;
  39915. /**
  39916. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39917. */
  39918. _this._invertNormalMapY = false;
  39919. /**
  39920. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39921. */
  39922. _this._twoSidedLighting = false;
  39923. /**
  39924. * Defines the alpha limits in alpha test mode.
  39925. */
  39926. _this._alphaCutOff = 0.4;
  39927. /**
  39928. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39929. */
  39930. _this._forceAlphaTest = false;
  39931. /**
  39932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39933. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39934. */
  39935. _this._useAlphaFresnel = false;
  39936. /**
  39937. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39938. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39939. */
  39940. _this._useLinearAlphaFresnel = false;
  39941. /**
  39942. * The transparency mode of the material.
  39943. */
  39944. _this._transparencyMode = null;
  39945. /**
  39946. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39947. * from cos thetav and roughness:
  39948. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39949. */
  39950. _this._environmentBRDFTexture = null;
  39951. /**
  39952. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39953. */
  39954. _this._forceIrradianceInFragment = false;
  39955. /**
  39956. * Force normal to face away from face.
  39957. */
  39958. _this._forceNormalForward = false;
  39959. /**
  39960. * Force metallic workflow.
  39961. */
  39962. _this._forceMetallicWorkflow = false;
  39963. /**
  39964. * Stores the available render targets.
  39965. */
  39966. _this._renderTargets = new BABYLON.SmartArray(16);
  39967. /**
  39968. * Sets the global ambient color for the material used in lighting calculations.
  39969. */
  39970. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39971. // Setup the default processing configuration to the scene.
  39972. _this._attachImageProcessingConfiguration(null);
  39973. _this.getRenderTargetTextures = function () {
  39974. _this._renderTargets.reset();
  39975. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39976. _this._renderTargets.push(_this._reflectionTexture);
  39977. }
  39978. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39979. _this._renderTargets.push(_this._refractionTexture);
  39980. }
  39981. return _this._renderTargets;
  39982. };
  39983. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39984. return _this;
  39985. }
  39986. /**
  39987. * Attaches a new image processing configuration to the PBR Material.
  39988. * @param configuration
  39989. */
  39990. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39991. var _this = this;
  39992. if (configuration === this._imageProcessingConfiguration) {
  39993. return;
  39994. }
  39995. // Detaches observer.
  39996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39998. }
  39999. // Pick the scene configuration if needed.
  40000. if (!configuration) {
  40001. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40002. }
  40003. else {
  40004. this._imageProcessingConfiguration = configuration;
  40005. }
  40006. // Attaches observer.
  40007. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40008. _this._markAllSubMeshesAsImageProcessingDirty();
  40009. });
  40010. };
  40011. /**
  40012. * Gets the name of the material class.
  40013. */
  40014. PBRBaseMaterial.prototype.getClassName = function () {
  40015. return "PBRBaseMaterial";
  40016. };
  40017. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40018. /**
  40019. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40020. */
  40021. get: function () {
  40022. return this._useLogarithmicDepth;
  40023. },
  40024. /**
  40025. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40026. */
  40027. set: function (value) {
  40028. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40029. },
  40030. enumerable: true,
  40031. configurable: true
  40032. });
  40033. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40034. /**
  40035. * Gets the current transparency mode.
  40036. */
  40037. get: function () {
  40038. return this._transparencyMode;
  40039. },
  40040. /**
  40041. * Sets the transparency mode of the material.
  40042. */
  40043. set: function (value) {
  40044. if (this._transparencyMode === value) {
  40045. return;
  40046. }
  40047. this._transparencyMode = value;
  40048. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40049. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40050. },
  40051. enumerable: true,
  40052. configurable: true
  40053. });
  40054. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40055. /**
  40056. * Returns true if alpha blending should be disabled.
  40057. */
  40058. get: function () {
  40059. return (this._linkRefractionWithTransparency ||
  40060. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40061. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40062. },
  40063. enumerable: true,
  40064. configurable: true
  40065. });
  40066. /**
  40067. * Specifies whether or not this material should be rendered in alpha blend mode.
  40068. */
  40069. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40070. if (this._disableAlphaBlending) {
  40071. return false;
  40072. }
  40073. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40074. };
  40075. /**
  40076. * Specifies if the mesh will require alpha blending.
  40077. * @param mesh - BJS mesh.
  40078. */
  40079. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40080. if (this._disableAlphaBlending) {
  40081. return false;
  40082. }
  40083. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40084. };
  40085. /**
  40086. * Specifies whether or not this material should be rendered in alpha test mode.
  40087. */
  40088. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40089. if (this._forceAlphaTest) {
  40090. return true;
  40091. }
  40092. if (this._linkRefractionWithTransparency) {
  40093. return false;
  40094. }
  40095. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40096. };
  40097. /**
  40098. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40099. */
  40100. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40101. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40102. };
  40103. /**
  40104. * Gets the texture used for the alpha test.
  40105. */
  40106. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40107. return this._albedoTexture;
  40108. };
  40109. /**
  40110. * Specifies that the submesh is ready to be used.
  40111. * @param mesh - BJS mesh.
  40112. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40113. * @param useInstances - Specifies that instances should be used.
  40114. * @returns - boolean indicating that the submesh is ready or not.
  40115. */
  40116. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40117. if (subMesh.effect && this.isFrozen) {
  40118. if (this._wasPreviouslyReady) {
  40119. return true;
  40120. }
  40121. }
  40122. if (!subMesh._materialDefines) {
  40123. subMesh._materialDefines = new PBRMaterialDefines();
  40124. }
  40125. var defines = subMesh._materialDefines;
  40126. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40127. if (defines._renderId === this.getScene().getRenderId()) {
  40128. return true;
  40129. }
  40130. }
  40131. var scene = this.getScene();
  40132. var engine = scene.getEngine();
  40133. if (defines._areTexturesDirty) {
  40134. if (scene.texturesEnabled) {
  40135. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40136. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40137. return false;
  40138. }
  40139. }
  40140. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40141. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40142. return false;
  40143. }
  40144. }
  40145. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40146. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40147. return false;
  40148. }
  40149. }
  40150. var reflectionTexture = this._getReflectionTexture();
  40151. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40152. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40153. return false;
  40154. }
  40155. }
  40156. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40157. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40158. return false;
  40159. }
  40160. }
  40161. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40162. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40163. return false;
  40164. }
  40165. }
  40166. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40167. if (this._metallicTexture) {
  40168. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40169. return false;
  40170. }
  40171. }
  40172. else if (this._reflectivityTexture) {
  40173. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40174. return false;
  40175. }
  40176. }
  40177. if (this._microSurfaceTexture) {
  40178. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40179. return false;
  40180. }
  40181. }
  40182. }
  40183. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40184. // Bump texture cannot be not blocking.
  40185. if (!this._bumpTexture.isReady()) {
  40186. return false;
  40187. }
  40188. }
  40189. var refractionTexture = this._getRefractionTexture();
  40190. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40191. if (!refractionTexture.isReadyOrNotBlocking()) {
  40192. return false;
  40193. }
  40194. }
  40195. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40196. // This is blocking.
  40197. if (!this._environmentBRDFTexture.isReady()) {
  40198. return false;
  40199. }
  40200. }
  40201. }
  40202. }
  40203. if (defines._areImageProcessingDirty) {
  40204. if (!this._imageProcessingConfiguration.isReady()) {
  40205. return false;
  40206. }
  40207. }
  40208. if (!engine.getCaps().standardDerivatives) {
  40209. var bufferMesh = null;
  40210. if (mesh.getClassName() === "InstancedMesh") {
  40211. bufferMesh = mesh.sourceMesh;
  40212. }
  40213. else if (mesh.getClassName() === "Mesh") {
  40214. bufferMesh = mesh;
  40215. }
  40216. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40217. bufferMesh.createNormals(true);
  40218. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40219. }
  40220. }
  40221. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40222. if (effect) {
  40223. scene.resetCachedMaterial();
  40224. subMesh.setEffect(effect, defines);
  40225. this.buildUniformLayout();
  40226. }
  40227. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40228. return false;
  40229. }
  40230. defines._renderId = scene.getRenderId();
  40231. this._wasPreviouslyReady = true;
  40232. return true;
  40233. };
  40234. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40235. if (onCompiled === void 0) { onCompiled = null; }
  40236. if (onError === void 0) { onError = null; }
  40237. if (useInstances === void 0) { useInstances = null; }
  40238. if (useClipPlane === void 0) { useClipPlane = null; }
  40239. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40240. if (!defines.isDirty) {
  40241. return null;
  40242. }
  40243. defines.markAsProcessed();
  40244. var scene = this.getScene();
  40245. var engine = scene.getEngine();
  40246. // Fallbacks
  40247. var fallbacks = new BABYLON.EffectFallbacks();
  40248. var fallbackRank = 0;
  40249. if (defines.USESPHERICALINVERTEX) {
  40250. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40251. }
  40252. if (defines.FOG) {
  40253. fallbacks.addFallback(fallbackRank, "FOG");
  40254. }
  40255. if (defines.POINTSIZE) {
  40256. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40257. }
  40258. if (defines.LOGARITHMICDEPTH) {
  40259. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40260. }
  40261. if (defines.PARALLAX) {
  40262. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40263. }
  40264. if (defines.PARALLAXOCCLUSION) {
  40265. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40266. }
  40267. if (defines.ENVIRONMENTBRDF) {
  40268. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40269. }
  40270. if (defines.TANGENT) {
  40271. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40272. }
  40273. if (defines.BUMP) {
  40274. fallbacks.addFallback(fallbackRank++, "BUMP");
  40275. }
  40276. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40277. if (defines.SPECULARTERM) {
  40278. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40279. }
  40280. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40281. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40282. }
  40283. if (defines.LIGHTMAP) {
  40284. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40285. }
  40286. if (defines.NORMAL) {
  40287. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40288. }
  40289. if (defines.AMBIENT) {
  40290. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40291. }
  40292. if (defines.EMISSIVE) {
  40293. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40294. }
  40295. if (defines.VERTEXCOLOR) {
  40296. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40297. }
  40298. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40299. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40300. }
  40301. if (defines.MORPHTARGETS) {
  40302. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40303. }
  40304. //Attributes
  40305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40306. if (defines.NORMAL) {
  40307. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40308. }
  40309. if (defines.TANGENT) {
  40310. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40311. }
  40312. if (defines.UV1) {
  40313. attribs.push(BABYLON.VertexBuffer.UVKind);
  40314. }
  40315. if (defines.UV2) {
  40316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40317. }
  40318. if (defines.VERTEXCOLOR) {
  40319. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40320. }
  40321. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40322. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40323. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40324. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40325. "vFogInfos", "vFogColor", "pointSize",
  40326. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40327. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40328. "mBones",
  40329. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40330. "vLightingIntensity",
  40331. "logarithmicDepthConstant",
  40332. "vSphericalX", "vSphericalY", "vSphericalZ",
  40333. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40334. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40335. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40336. "vTangentSpaceParams"
  40337. ];
  40338. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40339. "bumpSampler", "lightmapSampler", "opacitySampler",
  40340. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40341. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40342. "microSurfaceSampler", "environmentBrdfSampler"];
  40343. var uniformBuffers = ["Material", "Scene"];
  40344. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40345. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40346. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40347. uniformsNames: uniforms,
  40348. uniformBuffersNames: uniformBuffers,
  40349. samplers: samplers,
  40350. defines: defines,
  40351. maxSimultaneousLights: this._maxSimultaneousLights
  40352. });
  40353. var join = defines.toString();
  40354. return engine.createEffect("pbr", {
  40355. attributes: attribs,
  40356. uniformsNames: uniforms,
  40357. uniformBuffersNames: uniformBuffers,
  40358. samplers: samplers,
  40359. defines: join,
  40360. fallbacks: fallbacks,
  40361. onCompiled: onCompiled,
  40362. onError: onError,
  40363. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40364. }, engine);
  40365. };
  40366. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40367. if (useInstances === void 0) { useInstances = null; }
  40368. if (useClipPlane === void 0) { useClipPlane = null; }
  40369. var scene = this.getScene();
  40370. var engine = scene.getEngine();
  40371. // Lights
  40372. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40373. defines._needNormals = true;
  40374. // Textures
  40375. if (defines._areTexturesDirty) {
  40376. defines._needUVs = false;
  40377. if (scene.texturesEnabled) {
  40378. if (scene.getEngine().getCaps().textureLOD) {
  40379. defines.LODBASEDMICROSFURACE = true;
  40380. }
  40381. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40383. }
  40384. else {
  40385. defines.ALBEDO = false;
  40386. }
  40387. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40389. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40390. }
  40391. else {
  40392. defines.AMBIENT = false;
  40393. }
  40394. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40396. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40397. }
  40398. else {
  40399. defines.OPACITY = false;
  40400. }
  40401. var reflectionTexture = this._getReflectionTexture();
  40402. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40403. defines.REFLECTION = true;
  40404. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40405. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40406. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40407. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40408. defines.INVERTCUBICMAP = true;
  40409. }
  40410. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40411. switch (reflectionTexture.coordinatesMode) {
  40412. case BABYLON.Texture.CUBIC_MODE:
  40413. case BABYLON.Texture.INVCUBIC_MODE:
  40414. defines.REFLECTIONMAP_CUBIC = true;
  40415. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40416. break;
  40417. case BABYLON.Texture.EXPLICIT_MODE:
  40418. defines.REFLECTIONMAP_EXPLICIT = true;
  40419. break;
  40420. case BABYLON.Texture.PLANAR_MODE:
  40421. defines.REFLECTIONMAP_PLANAR = true;
  40422. break;
  40423. case BABYLON.Texture.PROJECTION_MODE:
  40424. defines.REFLECTIONMAP_PROJECTION = true;
  40425. break;
  40426. case BABYLON.Texture.SKYBOX_MODE:
  40427. defines.REFLECTIONMAP_SKYBOX = true;
  40428. break;
  40429. case BABYLON.Texture.SPHERICAL_MODE:
  40430. defines.REFLECTIONMAP_SPHERICAL = true;
  40431. break;
  40432. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40433. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40434. break;
  40435. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40436. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40437. break;
  40438. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40439. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40440. break;
  40441. }
  40442. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40443. if (reflectionTexture.sphericalPolynomial) {
  40444. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40445. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40446. defines.USESPHERICALINVERTEX = false;
  40447. }
  40448. else {
  40449. defines.USESPHERICALINVERTEX = true;
  40450. }
  40451. }
  40452. }
  40453. }
  40454. else {
  40455. defines.REFLECTION = false;
  40456. defines.REFLECTIONMAP_3D = false;
  40457. defines.REFLECTIONMAP_SPHERICAL = false;
  40458. defines.REFLECTIONMAP_PLANAR = false;
  40459. defines.REFLECTIONMAP_CUBIC = false;
  40460. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40461. defines.REFLECTIONMAP_PROJECTION = false;
  40462. defines.REFLECTIONMAP_SKYBOX = false;
  40463. defines.REFLECTIONMAP_EXPLICIT = false;
  40464. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40465. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40466. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40467. defines.INVERTCUBICMAP = false;
  40468. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40469. defines.USESPHERICALINVERTEX = false;
  40470. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40471. defines.LODINREFLECTIONALPHA = false;
  40472. defines.GAMMAREFLECTION = false;
  40473. }
  40474. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40476. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40477. }
  40478. else {
  40479. defines.LIGHTMAP = false;
  40480. }
  40481. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40483. }
  40484. else {
  40485. defines.EMISSIVE = false;
  40486. }
  40487. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40488. if (this._metallicTexture) {
  40489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40490. defines.METALLICWORKFLOW = true;
  40491. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40492. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40493. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40494. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40495. }
  40496. else if (this._reflectivityTexture) {
  40497. defines.METALLICWORKFLOW = false;
  40498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40499. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40500. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40501. }
  40502. else {
  40503. defines.METALLICWORKFLOW = false;
  40504. defines.REFLECTIVITY = false;
  40505. }
  40506. if (this._microSurfaceTexture) {
  40507. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40508. }
  40509. else {
  40510. defines.MICROSURFACEMAP = false;
  40511. }
  40512. }
  40513. else {
  40514. defines.REFLECTIVITY = false;
  40515. defines.MICROSURFACEMAP = false;
  40516. }
  40517. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40518. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40519. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40520. defines.PARALLAX = true;
  40521. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40522. }
  40523. else {
  40524. defines.PARALLAX = false;
  40525. }
  40526. }
  40527. else {
  40528. defines.BUMP = false;
  40529. }
  40530. var refractionTexture = this._getRefractionTexture();
  40531. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40532. defines.REFRACTION = true;
  40533. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40534. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40535. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40536. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40537. if (this._linkRefractionWithTransparency) {
  40538. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40539. }
  40540. }
  40541. else {
  40542. defines.REFRACTION = false;
  40543. }
  40544. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40545. defines.ENVIRONMENTBRDF = true;
  40546. }
  40547. else {
  40548. defines.ENVIRONMENTBRDF = false;
  40549. }
  40550. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40551. defines.ALPHAFROMALBEDO = true;
  40552. }
  40553. else {
  40554. defines.ALPHAFROMALBEDO = false;
  40555. }
  40556. }
  40557. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40558. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40559. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40560. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40561. defines.METALLICWORKFLOW = true;
  40562. }
  40563. else {
  40564. defines.METALLICWORKFLOW = false;
  40565. }
  40566. if (!this.backFaceCulling && this._twoSidedLighting) {
  40567. defines.TWOSIDEDLIGHTING = true;
  40568. }
  40569. else {
  40570. defines.TWOSIDEDLIGHTING = false;
  40571. }
  40572. defines.ALPHATESTVALUE = this._alphaCutOff;
  40573. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40574. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40575. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40576. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40577. }
  40578. if (defines._areImageProcessingDirty) {
  40579. this._imageProcessingConfiguration.prepareDefines(defines);
  40580. }
  40581. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40582. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40583. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40584. // Misc.
  40585. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40586. // Values that need to be evaluated on every frame
  40587. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40588. // Attribs
  40589. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40590. };
  40591. /**
  40592. * Force shader compilation
  40593. */
  40594. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40595. var _this = this;
  40596. var localOptions = __assign({ clipPlane: false }, options);
  40597. var defines = new PBRMaterialDefines();
  40598. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40599. if (effect.isReady()) {
  40600. if (onCompiled) {
  40601. onCompiled(this);
  40602. }
  40603. }
  40604. else {
  40605. effect.onCompileObservable.add(function () {
  40606. if (onCompiled) {
  40607. onCompiled(_this);
  40608. }
  40609. });
  40610. }
  40611. };
  40612. /**
  40613. * Initializes the uniform buffer layout for the shader.
  40614. */
  40615. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40616. // Order is important !
  40617. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40618. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40619. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40620. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40621. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40622. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40623. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40624. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40625. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40626. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40627. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40628. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40629. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40630. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40631. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40632. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40633. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40634. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40635. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40636. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40637. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40638. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40639. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40640. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40641. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40642. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40643. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40644. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40645. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40646. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40647. this._uniformBuffer.addUniform("pointSize", 1);
  40648. this._uniformBuffer.create();
  40649. };
  40650. /**
  40651. * Unbinds the textures.
  40652. */
  40653. PBRBaseMaterial.prototype.unbind = function () {
  40654. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40655. this._uniformBuffer.setTexture("reflectionSampler", null);
  40656. }
  40657. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40658. this._uniformBuffer.setTexture("refractionSampler", null);
  40659. }
  40660. _super.prototype.unbind.call(this);
  40661. };
  40662. /**
  40663. * Binds to the world matrix.
  40664. * @param world - The world matrix.
  40665. */
  40666. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40667. this._activeEffect.setMatrix("world", world);
  40668. };
  40669. /**
  40670. * Binds the submesh data.
  40671. * @param world - The world matrix.
  40672. * @param mesh - The BJS mesh.
  40673. * @param subMesh - A submesh of the BJS mesh.
  40674. */
  40675. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40676. var scene = this.getScene();
  40677. var defines = subMesh._materialDefines;
  40678. if (!defines) {
  40679. return;
  40680. }
  40681. var effect = subMesh.effect;
  40682. if (!effect) {
  40683. return;
  40684. }
  40685. this._activeEffect = effect;
  40686. // Matrices
  40687. this.bindOnlyWorldMatrix(world);
  40688. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40689. // Bones
  40690. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40691. var reflectionTexture = null;
  40692. if (mustRebind) {
  40693. this._uniformBuffer.bindToEffect(effect, "Material");
  40694. this.bindViewProjection(effect);
  40695. reflectionTexture = this._getReflectionTexture();
  40696. var refractionTexture = this._getRefractionTexture();
  40697. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40698. // Texture uniforms
  40699. if (scene.texturesEnabled) {
  40700. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40701. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40702. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40703. }
  40704. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40705. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40706. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40707. }
  40708. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40709. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40710. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40711. }
  40712. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40713. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40714. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40715. if (reflectionTexture.boundingBoxSize) {
  40716. var cubeTexture = reflectionTexture;
  40717. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40718. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40719. }
  40720. var polynomials = reflectionTexture.sphericalPolynomial;
  40721. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40722. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40723. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40724. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40725. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40726. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40727. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40728. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40729. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40730. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40731. }
  40732. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40733. }
  40734. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40735. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40736. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40737. }
  40738. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40739. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40740. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40741. }
  40742. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40743. if (this._metallicTexture) {
  40744. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40745. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40746. }
  40747. else if (this._reflectivityTexture) {
  40748. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40749. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40750. }
  40751. if (this._microSurfaceTexture) {
  40752. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40753. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40754. }
  40755. }
  40756. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40757. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40758. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40759. if (scene._mirroredCameraPosition) {
  40760. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40761. }
  40762. else {
  40763. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40764. }
  40765. }
  40766. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40767. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40768. var depth = 1.0;
  40769. if (!refractionTexture.isCube) {
  40770. if (refractionTexture.depth) {
  40771. depth = refractionTexture.depth;
  40772. }
  40773. }
  40774. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40775. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40776. }
  40777. }
  40778. // Point size
  40779. if (this.pointsCloud) {
  40780. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40781. }
  40782. // Colors
  40783. if (defines.METALLICWORKFLOW) {
  40784. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40785. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40786. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40787. }
  40788. else {
  40789. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40790. }
  40791. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40792. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40793. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40794. // Misc
  40795. this._lightingInfos.x = this._directIntensity;
  40796. this._lightingInfos.y = this._emissiveIntensity;
  40797. this._lightingInfos.z = this._environmentIntensity;
  40798. this._lightingInfos.w = this._specularIntensity;
  40799. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40800. }
  40801. // Textures
  40802. if (scene.texturesEnabled) {
  40803. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40804. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40805. }
  40806. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40807. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40808. }
  40809. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40810. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40811. }
  40812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40813. if (defines.LODBASEDMICROSFURACE) {
  40814. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40815. }
  40816. else {
  40817. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40818. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40819. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40820. }
  40821. }
  40822. if (defines.ENVIRONMENTBRDF) {
  40823. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40824. }
  40825. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40826. if (defines.LODBASEDMICROSFURACE) {
  40827. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40828. }
  40829. else {
  40830. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40831. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40832. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40833. }
  40834. }
  40835. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40836. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40837. }
  40838. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40839. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40840. }
  40841. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40842. if (this._metallicTexture) {
  40843. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40844. }
  40845. else if (this._reflectivityTexture) {
  40846. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40847. }
  40848. if (this._microSurfaceTexture) {
  40849. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40850. }
  40851. }
  40852. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40853. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40854. }
  40855. }
  40856. // Clip plane
  40857. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40858. // Colors
  40859. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40860. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40861. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40862. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40863. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40864. }
  40865. if (mustRebind || !this.isFrozen) {
  40866. // Lights
  40867. if (scene.lightsEnabled && !this._disableLighting) {
  40868. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40869. }
  40870. // View
  40871. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40872. this.bindView(effect);
  40873. }
  40874. // Fog
  40875. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40876. // Morph targets
  40877. if (defines.NUM_MORPH_INFLUENCERS) {
  40878. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40879. }
  40880. // image processing
  40881. this._imageProcessingConfiguration.bind(this._activeEffect);
  40882. // Log. depth
  40883. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40884. }
  40885. this._uniformBuffer.update();
  40886. this._afterBind(mesh);
  40887. };
  40888. /**
  40889. * Returns the animatable textures.
  40890. * @returns - Array of animatable textures.
  40891. */
  40892. PBRBaseMaterial.prototype.getAnimatables = function () {
  40893. var results = [];
  40894. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40895. results.push(this._albedoTexture);
  40896. }
  40897. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40898. results.push(this._ambientTexture);
  40899. }
  40900. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40901. results.push(this._opacityTexture);
  40902. }
  40903. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40904. results.push(this._reflectionTexture);
  40905. }
  40906. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40907. results.push(this._emissiveTexture);
  40908. }
  40909. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40910. results.push(this._metallicTexture);
  40911. }
  40912. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40913. results.push(this._reflectivityTexture);
  40914. }
  40915. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40916. results.push(this._bumpTexture);
  40917. }
  40918. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40919. results.push(this._lightmapTexture);
  40920. }
  40921. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40922. results.push(this._refractionTexture);
  40923. }
  40924. return results;
  40925. };
  40926. /**
  40927. * Returns the texture used for reflections.
  40928. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40929. */
  40930. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40931. if (this._reflectionTexture) {
  40932. return this._reflectionTexture;
  40933. }
  40934. return this.getScene().environmentTexture;
  40935. };
  40936. /**
  40937. * Returns the texture used for refraction or null if none is used.
  40938. * @returns - Refection texture if present. If no refraction texture and refraction
  40939. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40940. */
  40941. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40942. if (this._refractionTexture) {
  40943. return this._refractionTexture;
  40944. }
  40945. if (this._linkRefractionWithTransparency) {
  40946. return this.getScene().environmentTexture;
  40947. }
  40948. return null;
  40949. };
  40950. /**
  40951. * Disposes the resources of the material.
  40952. * @param forceDisposeEffect - Forces the disposal of effects.
  40953. * @param forceDisposeTextures - Forces the disposal of all textures.
  40954. */
  40955. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40956. if (forceDisposeTextures) {
  40957. if (this._albedoTexture) {
  40958. this._albedoTexture.dispose();
  40959. }
  40960. if (this._ambientTexture) {
  40961. this._ambientTexture.dispose();
  40962. }
  40963. if (this._opacityTexture) {
  40964. this._opacityTexture.dispose();
  40965. }
  40966. if (this._reflectionTexture) {
  40967. this._reflectionTexture.dispose();
  40968. }
  40969. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40970. this._environmentBRDFTexture.dispose();
  40971. }
  40972. if (this._emissiveTexture) {
  40973. this._emissiveTexture.dispose();
  40974. }
  40975. if (this._metallicTexture) {
  40976. this._metallicTexture.dispose();
  40977. }
  40978. if (this._reflectivityTexture) {
  40979. this._reflectivityTexture.dispose();
  40980. }
  40981. if (this._bumpTexture) {
  40982. this._bumpTexture.dispose();
  40983. }
  40984. if (this._lightmapTexture) {
  40985. this._lightmapTexture.dispose();
  40986. }
  40987. if (this._refractionTexture) {
  40988. this._refractionTexture.dispose();
  40989. }
  40990. }
  40991. this._renderTargets.dispose();
  40992. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40993. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40994. }
  40995. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40996. };
  40997. /**
  40998. * Stores the reflectivity values based on metallic roughness workflow.
  40999. */
  41000. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41001. __decorate([
  41002. BABYLON.serializeAsImageProcessingConfiguration()
  41003. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41004. __decorate([
  41005. BABYLON.serialize()
  41006. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41007. __decorate([
  41008. BABYLON.serialize()
  41009. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41010. return PBRBaseMaterial;
  41011. }(BABYLON.PushMaterial));
  41012. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41013. })(BABYLON || (BABYLON = {}));
  41014. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41015. var BABYLON;
  41016. (function (BABYLON) {
  41017. /**
  41018. * The Physically based simple base material of BJS.
  41019. *
  41020. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41021. * It is used as the base class for both the specGloss and metalRough conventions.
  41022. */
  41023. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41024. __extends(PBRBaseSimpleMaterial, _super);
  41025. /**
  41026. * Instantiates a new PBRMaterial instance.
  41027. *
  41028. * @param name The material name
  41029. * @param scene The scene the material will be use in.
  41030. */
  41031. function PBRBaseSimpleMaterial(name, scene) {
  41032. var _this = _super.call(this, name, scene) || this;
  41033. /**
  41034. * Number of Simultaneous lights allowed on the material.
  41035. */
  41036. _this.maxSimultaneousLights = 4;
  41037. /**
  41038. * If sets to true, disables all the lights affecting the material.
  41039. */
  41040. _this.disableLighting = false;
  41041. /**
  41042. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41043. */
  41044. _this.invertNormalMapX = false;
  41045. /**
  41046. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41047. */
  41048. _this.invertNormalMapY = false;
  41049. /**
  41050. * Emissivie color used to self-illuminate the model.
  41051. */
  41052. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41053. /**
  41054. * Occlusion Channel Strenght.
  41055. */
  41056. _this.occlusionStrength = 1.0;
  41057. _this.useLightmapAsShadowmap = false;
  41058. _this._useAlphaFromAlbedoTexture = true;
  41059. _this._useAmbientInGrayScale = true;
  41060. return _this;
  41061. }
  41062. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41063. /**
  41064. * Gets the current double sided mode.
  41065. */
  41066. get: function () {
  41067. return this._twoSidedLighting;
  41068. },
  41069. /**
  41070. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41071. */
  41072. set: function (value) {
  41073. if (this._twoSidedLighting === value) {
  41074. return;
  41075. }
  41076. this._twoSidedLighting = value;
  41077. this.backFaceCulling = !value;
  41078. this._markAllSubMeshesAsTexturesDirty();
  41079. },
  41080. enumerable: true,
  41081. configurable: true
  41082. });
  41083. /**
  41084. * Return the active textures of the material.
  41085. */
  41086. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41087. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41088. if (this.environmentTexture) {
  41089. activeTextures.push(this.environmentTexture);
  41090. }
  41091. if (this.normalTexture) {
  41092. activeTextures.push(this.normalTexture);
  41093. }
  41094. if (this.emissiveTexture) {
  41095. activeTextures.push(this.emissiveTexture);
  41096. }
  41097. if (this.occlusionTexture) {
  41098. activeTextures.push(this.occlusionTexture);
  41099. }
  41100. if (this.lightmapTexture) {
  41101. activeTextures.push(this.lightmapTexture);
  41102. }
  41103. return activeTextures;
  41104. };
  41105. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41106. if (_super.prototype.hasTexture.call(this, texture)) {
  41107. return true;
  41108. }
  41109. if (this.lightmapTexture === texture) {
  41110. return true;
  41111. }
  41112. return false;
  41113. };
  41114. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41115. return "PBRBaseSimpleMaterial";
  41116. };
  41117. __decorate([
  41118. BABYLON.serialize(),
  41119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41120. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41121. __decorate([
  41122. BABYLON.serialize(),
  41123. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41124. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41125. __decorate([
  41126. BABYLON.serializeAsTexture(),
  41127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41128. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41129. __decorate([
  41130. BABYLON.serialize(),
  41131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41132. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41133. __decorate([
  41134. BABYLON.serialize(),
  41135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41136. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41137. __decorate([
  41138. BABYLON.serializeAsTexture(),
  41139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41140. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41141. __decorate([
  41142. BABYLON.serializeAsColor3("emissive"),
  41143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41144. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41145. __decorate([
  41146. BABYLON.serializeAsTexture(),
  41147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41148. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41149. __decorate([
  41150. BABYLON.serialize(),
  41151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41152. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41153. __decorate([
  41154. BABYLON.serializeAsTexture(),
  41155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41156. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41157. __decorate([
  41158. BABYLON.serialize(),
  41159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41160. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41161. __decorate([
  41162. BABYLON.serialize()
  41163. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41164. __decorate([
  41165. BABYLON.serializeAsTexture(),
  41166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41167. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41168. __decorate([
  41169. BABYLON.serialize(),
  41170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41171. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41172. return PBRBaseSimpleMaterial;
  41173. }(BABYLON.PBRBaseMaterial));
  41174. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41175. })(BABYLON || (BABYLON = {}));
  41176. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41177. var BABYLON;
  41178. (function (BABYLON) {
  41179. /**
  41180. * The Physically based material of BJS.
  41181. *
  41182. * This offers the main features of a standard PBR material.
  41183. * For more information, please refer to the documentation :
  41184. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41185. */
  41186. var PBRMaterial = /** @class */ (function (_super) {
  41187. __extends(PBRMaterial, _super);
  41188. /**
  41189. * Instantiates a new PBRMaterial instance.
  41190. *
  41191. * @param name The material name
  41192. * @param scene The scene the material will be use in.
  41193. */
  41194. function PBRMaterial(name, scene) {
  41195. var _this = _super.call(this, name, scene) || this;
  41196. /**
  41197. * Intensity of the direct lights e.g. the four lights available in your scene.
  41198. * This impacts both the direct diffuse and specular highlights.
  41199. */
  41200. _this.directIntensity = 1.0;
  41201. /**
  41202. * Intensity of the emissive part of the material.
  41203. * This helps controlling the emissive effect without modifying the emissive color.
  41204. */
  41205. _this.emissiveIntensity = 1.0;
  41206. /**
  41207. * Intensity of the environment e.g. how much the environment will light the object
  41208. * either through harmonics for rough material or through the refelction for shiny ones.
  41209. */
  41210. _this.environmentIntensity = 1.0;
  41211. /**
  41212. * This is a special control allowing the reduction of the specular highlights coming from the
  41213. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41214. */
  41215. _this.specularIntensity = 1.0;
  41216. /**
  41217. * Debug Control allowing disabling the bump map on this material.
  41218. */
  41219. _this.disableBumpMap = false;
  41220. /**
  41221. * AKA Occlusion Texture Intensity in other nomenclature.
  41222. */
  41223. _this.ambientTextureStrength = 1.0;
  41224. /**
  41225. * The color of a material in ambient lighting.
  41226. */
  41227. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41228. /**
  41229. * AKA Diffuse Color in other nomenclature.
  41230. */
  41231. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41232. /**
  41233. * AKA Specular Color in other nomenclature.
  41234. */
  41235. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41236. /**
  41237. * The color reflected from the material.
  41238. */
  41239. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41240. /**
  41241. * The color emitted from the material.
  41242. */
  41243. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41244. /**
  41245. * AKA Glossiness in other nomenclature.
  41246. */
  41247. _this.microSurface = 1.0;
  41248. /**
  41249. * source material index of refraction (IOR)' / 'destination material IOR.
  41250. */
  41251. _this.indexOfRefraction = 0.66;
  41252. /**
  41253. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41254. */
  41255. _this.invertRefractionY = false;
  41256. /**
  41257. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41258. * Materials half opaque for instance using refraction could benefit from this control.
  41259. */
  41260. _this.linkRefractionWithTransparency = false;
  41261. _this.useLightmapAsShadowmap = false;
  41262. /**
  41263. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41264. */
  41265. _this.useAlphaFromAlbedoTexture = false;
  41266. /**
  41267. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41268. */
  41269. _this.forceAlphaTest = false;
  41270. /**
  41271. * Defines the alpha limits in alpha test mode.
  41272. */
  41273. _this.alphaCutOff = 0.4;
  41274. /**
  41275. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41276. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41277. */
  41278. _this.useSpecularOverAlpha = true;
  41279. /**
  41280. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41281. */
  41282. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41283. /**
  41284. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41285. */
  41286. _this.useRoughnessFromMetallicTextureAlpha = true;
  41287. /**
  41288. * Specifies if the metallic texture contains the roughness information in its green channel.
  41289. */
  41290. _this.useRoughnessFromMetallicTextureGreen = false;
  41291. /**
  41292. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41293. */
  41294. _this.useMetallnessFromMetallicTextureBlue = false;
  41295. /**
  41296. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41297. */
  41298. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41299. /**
  41300. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41301. */
  41302. _this.useAmbientInGrayScale = false;
  41303. /**
  41304. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41305. * The material will try to infer what glossiness each pixel should be.
  41306. */
  41307. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41308. /**
  41309. * BJS is using an harcoded light falloff based on a manually sets up range.
  41310. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41311. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41312. */
  41313. _this.usePhysicalLightFalloff = true;
  41314. /**
  41315. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41316. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41317. */
  41318. _this.useRadianceOverAlpha = true;
  41319. /**
  41320. * Allows using the bump map in parallax mode.
  41321. */
  41322. _this.useParallax = false;
  41323. /**
  41324. * Allows using the bump map in parallax occlusion mode.
  41325. */
  41326. _this.useParallaxOcclusion = false;
  41327. /**
  41328. * Controls the scale bias of the parallax mode.
  41329. */
  41330. _this.parallaxScaleBias = 0.05;
  41331. /**
  41332. * If sets to true, disables all the lights affecting the material.
  41333. */
  41334. _this.disableLighting = false;
  41335. /**
  41336. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41337. */
  41338. _this.forceIrradianceInFragment = false;
  41339. /**
  41340. * Number of Simultaneous lights allowed on the material.
  41341. */
  41342. _this.maxSimultaneousLights = 4;
  41343. /**
  41344. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41345. */
  41346. _this.invertNormalMapX = false;
  41347. /**
  41348. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41349. */
  41350. _this.invertNormalMapY = false;
  41351. /**
  41352. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41353. */
  41354. _this.twoSidedLighting = false;
  41355. /**
  41356. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41357. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41358. */
  41359. _this.useAlphaFresnel = false;
  41360. /**
  41361. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41362. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41363. */
  41364. _this.useLinearAlphaFresnel = false;
  41365. /**
  41366. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41367. * And/Or occlude the blended part.
  41368. */
  41369. _this.environmentBRDFTexture = null;
  41370. /**
  41371. * Force normal to face away from face.
  41372. */
  41373. _this.forceNormalForward = false;
  41374. /**
  41375. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41376. * makes the reflect vector face the model (under horizon).
  41377. */
  41378. _this.useHorizonOcclusion = true;
  41379. /**
  41380. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41381. * too much the area relying on ambient texture to define their ambient occlusion.
  41382. */
  41383. _this.useRadianceOcclusion = true;
  41384. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41385. return _this;
  41386. }
  41387. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41388. /**
  41389. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41390. */
  41391. get: function () {
  41392. return this._PBRMATERIAL_OPAQUE;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41398. /**
  41399. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41400. */
  41401. get: function () {
  41402. return this._PBRMATERIAL_ALPHATEST;
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41408. /**
  41409. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41410. */
  41411. get: function () {
  41412. return this._PBRMATERIAL_ALPHABLEND;
  41413. },
  41414. enumerable: true,
  41415. configurable: true
  41416. });
  41417. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41418. /**
  41419. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41420. * They are also discarded below the alpha cutoff threshold to improve performances.
  41421. */
  41422. get: function () {
  41423. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41429. /**
  41430. * Gets the image processing configuration used either in this material.
  41431. */
  41432. get: function () {
  41433. return this._imageProcessingConfiguration;
  41434. },
  41435. /**
  41436. * Sets the Default image processing configuration used either in the this material.
  41437. *
  41438. * If sets to null, the scene one is in use.
  41439. */
  41440. set: function (value) {
  41441. this._attachImageProcessingConfiguration(value);
  41442. // Ensure the effect will be rebuilt.
  41443. this._markAllSubMeshesAsTexturesDirty();
  41444. },
  41445. enumerable: true,
  41446. configurable: true
  41447. });
  41448. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41449. /**
  41450. * Gets wether the color curves effect is enabled.
  41451. */
  41452. get: function () {
  41453. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41454. },
  41455. /**
  41456. * Sets wether the color curves effect is enabled.
  41457. */
  41458. set: function (value) {
  41459. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41465. /**
  41466. * Gets wether the color grading effect is enabled.
  41467. */
  41468. get: function () {
  41469. return this.imageProcessingConfiguration.colorGradingEnabled;
  41470. },
  41471. /**
  41472. * Gets wether the color grading effect is enabled.
  41473. */
  41474. set: function (value) {
  41475. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41476. },
  41477. enumerable: true,
  41478. configurable: true
  41479. });
  41480. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41481. /**
  41482. * Gets wether tonemapping is enabled or not.
  41483. */
  41484. get: function () {
  41485. return this._imageProcessingConfiguration.toneMappingEnabled;
  41486. },
  41487. /**
  41488. * Sets wether tonemapping is enabled or not
  41489. */
  41490. set: function (value) {
  41491. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. ;
  41497. ;
  41498. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41499. /**
  41500. * The camera exposure used on this material.
  41501. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41502. * This corresponds to a photographic exposure.
  41503. */
  41504. get: function () {
  41505. return this._imageProcessingConfiguration.exposure;
  41506. },
  41507. /**
  41508. * The camera exposure used on this material.
  41509. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41510. * This corresponds to a photographic exposure.
  41511. */
  41512. set: function (value) {
  41513. this._imageProcessingConfiguration.exposure = value;
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. ;
  41519. ;
  41520. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41521. /**
  41522. * Gets The camera contrast used on this material.
  41523. */
  41524. get: function () {
  41525. return this._imageProcessingConfiguration.contrast;
  41526. },
  41527. /**
  41528. * Sets The camera contrast used on this material.
  41529. */
  41530. set: function (value) {
  41531. this._imageProcessingConfiguration.contrast = value;
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41537. /**
  41538. * Gets the Color Grading 2D Lookup Texture.
  41539. */
  41540. get: function () {
  41541. return this._imageProcessingConfiguration.colorGradingTexture;
  41542. },
  41543. /**
  41544. * Sets the Color Grading 2D Lookup Texture.
  41545. */
  41546. set: function (value) {
  41547. this._imageProcessingConfiguration.colorGradingTexture = value;
  41548. },
  41549. enumerable: true,
  41550. configurable: true
  41551. });
  41552. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41553. /**
  41554. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41555. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41556. * 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;
  41557. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41558. */
  41559. get: function () {
  41560. return this._imageProcessingConfiguration.colorCurves;
  41561. },
  41562. /**
  41563. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41564. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41565. * 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;
  41566. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41567. */
  41568. set: function (value) {
  41569. this._imageProcessingConfiguration.colorCurves = value;
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. /**
  41575. * Returns the name of this material class.
  41576. */
  41577. PBRMaterial.prototype.getClassName = function () {
  41578. return "PBRMaterial";
  41579. };
  41580. /**
  41581. * Returns an array of the actively used textures.
  41582. * @returns - Array of BaseTextures
  41583. */
  41584. PBRMaterial.prototype.getActiveTextures = function () {
  41585. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41586. if (this._albedoTexture) {
  41587. activeTextures.push(this._albedoTexture);
  41588. }
  41589. if (this._ambientTexture) {
  41590. activeTextures.push(this._ambientTexture);
  41591. }
  41592. if (this._opacityTexture) {
  41593. activeTextures.push(this._opacityTexture);
  41594. }
  41595. if (this._reflectionTexture) {
  41596. activeTextures.push(this._reflectionTexture);
  41597. }
  41598. if (this._emissiveTexture) {
  41599. activeTextures.push(this._emissiveTexture);
  41600. }
  41601. if (this._reflectivityTexture) {
  41602. activeTextures.push(this._reflectivityTexture);
  41603. }
  41604. if (this._metallicTexture) {
  41605. activeTextures.push(this._metallicTexture);
  41606. }
  41607. if (this._microSurfaceTexture) {
  41608. activeTextures.push(this._microSurfaceTexture);
  41609. }
  41610. if (this._bumpTexture) {
  41611. activeTextures.push(this._bumpTexture);
  41612. }
  41613. if (this._lightmapTexture) {
  41614. activeTextures.push(this._lightmapTexture);
  41615. }
  41616. if (this._refractionTexture) {
  41617. activeTextures.push(this._refractionTexture);
  41618. }
  41619. return activeTextures;
  41620. };
  41621. /**
  41622. * Checks to see if a texture is used in the material.
  41623. * @param texture - Base texture to use.
  41624. * @returns - Boolean specifying if a texture is used in the material.
  41625. */
  41626. PBRMaterial.prototype.hasTexture = function (texture) {
  41627. if (_super.prototype.hasTexture.call(this, texture)) {
  41628. return true;
  41629. }
  41630. if (this._albedoTexture === texture) {
  41631. return true;
  41632. }
  41633. if (this._ambientTexture === texture) {
  41634. return true;
  41635. }
  41636. if (this._opacityTexture === texture) {
  41637. return true;
  41638. }
  41639. if (this._reflectionTexture === texture) {
  41640. return true;
  41641. }
  41642. if (this._reflectivityTexture === texture) {
  41643. return true;
  41644. }
  41645. if (this._metallicTexture === texture) {
  41646. return true;
  41647. }
  41648. if (this._microSurfaceTexture === texture) {
  41649. return true;
  41650. }
  41651. if (this._bumpTexture === texture) {
  41652. return true;
  41653. }
  41654. if (this._lightmapTexture === texture) {
  41655. return true;
  41656. }
  41657. if (this._refractionTexture === texture) {
  41658. return true;
  41659. }
  41660. return false;
  41661. };
  41662. /**
  41663. * Makes a duplicate of the current material.
  41664. * @param name - name to use for the new material.
  41665. */
  41666. PBRMaterial.prototype.clone = function (name) {
  41667. var _this = this;
  41668. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41669. clone.id = name;
  41670. clone.name = name;
  41671. return clone;
  41672. };
  41673. /**
  41674. * Serializes this PBR Material.
  41675. * @returns - An object with the serialized material.
  41676. */
  41677. PBRMaterial.prototype.serialize = function () {
  41678. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41679. serializationObject.customType = "BABYLON.PBRMaterial";
  41680. return serializationObject;
  41681. };
  41682. // Statics
  41683. /**
  41684. * Parses a PBR Material from a serialized object.
  41685. * @param source - Serialized object.
  41686. * @param scene - BJS scene instance.
  41687. * @param rootUrl - url for the scene object
  41688. * @returns - PBRMaterial
  41689. */
  41690. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41691. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41692. };
  41693. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41694. /**
  41695. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41696. */
  41697. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41698. /**
  41699. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41700. */
  41701. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41702. /**
  41703. * 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.
  41704. * They are also discarded below the alpha cutoff threshold to improve performances.
  41705. */
  41706. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41707. __decorate([
  41708. BABYLON.serialize(),
  41709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41710. ], PBRMaterial.prototype, "directIntensity", void 0);
  41711. __decorate([
  41712. BABYLON.serialize(),
  41713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41714. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41715. __decorate([
  41716. BABYLON.serialize(),
  41717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41718. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41719. __decorate([
  41720. BABYLON.serialize(),
  41721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41722. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41723. __decorate([
  41724. BABYLON.serialize(),
  41725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41726. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41727. __decorate([
  41728. BABYLON.serializeAsTexture(),
  41729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41730. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41731. __decorate([
  41732. BABYLON.serializeAsTexture(),
  41733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41734. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41735. __decorate([
  41736. BABYLON.serialize(),
  41737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41738. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41739. __decorate([
  41740. BABYLON.serializeAsTexture(),
  41741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41742. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41743. __decorate([
  41744. BABYLON.serializeAsTexture(),
  41745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41746. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41747. __decorate([
  41748. BABYLON.serializeAsTexture(),
  41749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41750. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41751. __decorate([
  41752. BABYLON.serializeAsTexture(),
  41753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41754. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41755. __decorate([
  41756. BABYLON.serializeAsTexture(),
  41757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41758. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41759. __decorate([
  41760. BABYLON.serialize(),
  41761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41762. ], PBRMaterial.prototype, "metallic", void 0);
  41763. __decorate([
  41764. BABYLON.serialize(),
  41765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41766. ], PBRMaterial.prototype, "roughness", void 0);
  41767. __decorate([
  41768. BABYLON.serializeAsTexture(),
  41769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41770. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41771. __decorate([
  41772. BABYLON.serializeAsTexture(),
  41773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41774. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41775. __decorate([
  41776. BABYLON.serializeAsTexture(),
  41777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41778. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41779. __decorate([
  41780. BABYLON.serializeAsTexture(),
  41781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41782. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41783. __decorate([
  41784. BABYLON.serializeAsColor3("ambient"),
  41785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41786. ], PBRMaterial.prototype, "ambientColor", void 0);
  41787. __decorate([
  41788. BABYLON.serializeAsColor3("albedo"),
  41789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41790. ], PBRMaterial.prototype, "albedoColor", void 0);
  41791. __decorate([
  41792. BABYLON.serializeAsColor3("reflectivity"),
  41793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41794. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41795. __decorate([
  41796. BABYLON.serializeAsColor3("reflection"),
  41797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41798. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41799. __decorate([
  41800. BABYLON.serializeAsColor3("emissive"),
  41801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41802. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41803. __decorate([
  41804. BABYLON.serialize(),
  41805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41806. ], PBRMaterial.prototype, "microSurface", void 0);
  41807. __decorate([
  41808. BABYLON.serialize(),
  41809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41810. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41811. __decorate([
  41812. BABYLON.serialize(),
  41813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41814. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41815. __decorate([
  41816. BABYLON.serialize(),
  41817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41818. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41819. __decorate([
  41820. BABYLON.serialize(),
  41821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41822. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41823. __decorate([
  41824. BABYLON.serialize(),
  41825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41826. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41827. __decorate([
  41828. BABYLON.serialize(),
  41829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41830. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41831. __decorate([
  41832. BABYLON.serialize(),
  41833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41834. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41835. __decorate([
  41836. BABYLON.serialize(),
  41837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41838. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41839. __decorate([
  41840. BABYLON.serialize(),
  41841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41842. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41843. __decorate([
  41844. BABYLON.serialize(),
  41845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41846. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41847. __decorate([
  41848. BABYLON.serialize(),
  41849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41850. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41851. __decorate([
  41852. BABYLON.serialize(),
  41853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41854. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41855. __decorate([
  41856. BABYLON.serialize(),
  41857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41858. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41859. __decorate([
  41860. BABYLON.serialize(),
  41861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41862. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41863. __decorate([
  41864. BABYLON.serialize(),
  41865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41866. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41867. __decorate([
  41868. BABYLON.serialize(),
  41869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41870. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41871. __decorate([
  41872. BABYLON.serialize(),
  41873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41874. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41875. __decorate([
  41876. BABYLON.serialize(),
  41877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41878. ], PBRMaterial.prototype, "useParallax", void 0);
  41879. __decorate([
  41880. BABYLON.serialize(),
  41881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41882. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41883. __decorate([
  41884. BABYLON.serialize(),
  41885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41886. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41887. __decorate([
  41888. BABYLON.serialize(),
  41889. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41890. ], PBRMaterial.prototype, "disableLighting", void 0);
  41891. __decorate([
  41892. BABYLON.serialize(),
  41893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41894. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41895. __decorate([
  41896. BABYLON.serialize(),
  41897. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41898. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41899. __decorate([
  41900. BABYLON.serialize(),
  41901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41902. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41903. __decorate([
  41904. BABYLON.serialize(),
  41905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41906. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41907. __decorate([
  41908. BABYLON.serialize(),
  41909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41910. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41911. __decorate([
  41912. BABYLON.serialize(),
  41913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41914. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41915. __decorate([
  41916. BABYLON.serialize(),
  41917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41918. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41919. __decorate([
  41920. BABYLON.serializeAsTexture(),
  41921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41922. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41923. __decorate([
  41924. BABYLON.serialize(),
  41925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41926. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41927. __decorate([
  41928. BABYLON.serialize(),
  41929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41930. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41931. __decorate([
  41932. BABYLON.serialize(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41934. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41935. return PBRMaterial;
  41936. }(BABYLON.PBRBaseMaterial));
  41937. BABYLON.PBRMaterial = PBRMaterial;
  41938. })(BABYLON || (BABYLON = {}));
  41939. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41940. var BABYLON;
  41941. (function (BABYLON) {
  41942. /**
  41943. * The PBR material of BJS following the metal roughness convention.
  41944. *
  41945. * This fits to the PBR convention in the GLTF definition:
  41946. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41947. */
  41948. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41949. __extends(PBRMetallicRoughnessMaterial, _super);
  41950. /**
  41951. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41952. *
  41953. * @param name The material name
  41954. * @param scene The scene the material will be use in.
  41955. */
  41956. function PBRMetallicRoughnessMaterial(name, scene) {
  41957. var _this = _super.call(this, name, scene) || this;
  41958. _this._useRoughnessFromMetallicTextureAlpha = false;
  41959. _this._useRoughnessFromMetallicTextureGreen = true;
  41960. _this._useMetallnessFromMetallicTextureBlue = true;
  41961. _this._forceMetallicWorkflow = true;
  41962. return _this;
  41963. }
  41964. /**
  41965. * Return the currrent class name of the material.
  41966. */
  41967. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41968. return "PBRMetallicRoughnessMaterial";
  41969. };
  41970. /**
  41971. * Return the active textures of the material.
  41972. */
  41973. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41975. if (this.baseTexture) {
  41976. activeTextures.push(this.baseTexture);
  41977. }
  41978. if (this.metallicRoughnessTexture) {
  41979. activeTextures.push(this.metallicRoughnessTexture);
  41980. }
  41981. return activeTextures;
  41982. };
  41983. /**
  41984. * Checks to see if a texture is used in the material.
  41985. * @param texture - Base texture to use.
  41986. * @returns - Boolean specifying if a texture is used in the material.
  41987. */
  41988. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41989. if (_super.prototype.hasTexture.call(this, texture)) {
  41990. return true;
  41991. }
  41992. if (this.baseTexture === texture) {
  41993. return true;
  41994. }
  41995. if (this.metallicRoughnessTexture === texture) {
  41996. return true;
  41997. }
  41998. return false;
  41999. };
  42000. /**
  42001. * Makes a duplicate of the current material.
  42002. * @param name - name to use for the new material.
  42003. */
  42004. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42005. var _this = this;
  42006. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42007. clone.id = name;
  42008. clone.name = name;
  42009. return clone;
  42010. };
  42011. /**
  42012. * Serialize the material to a parsable JSON object.
  42013. */
  42014. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42015. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42016. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42017. return serializationObject;
  42018. };
  42019. /**
  42020. * Parses a JSON object correponding to the serialize function.
  42021. */
  42022. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42023. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42024. };
  42025. __decorate([
  42026. BABYLON.serializeAsColor3(),
  42027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42028. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42029. __decorate([
  42030. BABYLON.serializeAsTexture(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42032. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42033. __decorate([
  42034. BABYLON.serialize(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42036. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42037. __decorate([
  42038. BABYLON.serialize(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42040. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42041. __decorate([
  42042. BABYLON.serializeAsTexture(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42044. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42045. return PBRMetallicRoughnessMaterial;
  42046. }(BABYLON.PBRBaseSimpleMaterial));
  42047. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42048. })(BABYLON || (BABYLON = {}));
  42049. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42050. var BABYLON;
  42051. (function (BABYLON) {
  42052. /**
  42053. * The PBR material of BJS following the specular glossiness convention.
  42054. *
  42055. * This fits to the PBR convention in the GLTF definition:
  42056. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42057. */
  42058. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42059. __extends(PBRSpecularGlossinessMaterial, _super);
  42060. /**
  42061. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42062. *
  42063. * @param name The material name
  42064. * @param scene The scene the material will be use in.
  42065. */
  42066. function PBRSpecularGlossinessMaterial(name, scene) {
  42067. var _this = _super.call(this, name, scene) || this;
  42068. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42069. return _this;
  42070. }
  42071. /**
  42072. * Return the currrent class name of the material.
  42073. */
  42074. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42075. return "PBRSpecularGlossinessMaterial";
  42076. };
  42077. /**
  42078. * Return the active textures of the material.
  42079. */
  42080. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42081. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42082. if (this.diffuseTexture) {
  42083. activeTextures.push(this.diffuseTexture);
  42084. }
  42085. if (this.specularGlossinessTexture) {
  42086. activeTextures.push(this.specularGlossinessTexture);
  42087. }
  42088. return activeTextures;
  42089. };
  42090. /**
  42091. * Checks to see if a texture is used in the material.
  42092. * @param texture - Base texture to use.
  42093. * @returns - Boolean specifying if a texture is used in the material.
  42094. */
  42095. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42096. if (_super.prototype.hasTexture.call(this, texture)) {
  42097. return true;
  42098. }
  42099. if (this.diffuseTexture === texture) {
  42100. return true;
  42101. }
  42102. if (this.specularGlossinessTexture === texture) {
  42103. return true;
  42104. }
  42105. return false;
  42106. };
  42107. /**
  42108. * Makes a duplicate of the current material.
  42109. * @param name - name to use for the new material.
  42110. */
  42111. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42112. var _this = this;
  42113. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42114. clone.id = name;
  42115. clone.name = name;
  42116. return clone;
  42117. };
  42118. /**
  42119. * Serialize the material to a parsable JSON object.
  42120. */
  42121. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42122. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42123. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42124. return serializationObject;
  42125. };
  42126. /**
  42127. * Parses a JSON object correponding to the serialize function.
  42128. */
  42129. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42130. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42131. };
  42132. __decorate([
  42133. BABYLON.serializeAsColor3("diffuse"),
  42134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42135. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42136. __decorate([
  42137. BABYLON.serializeAsTexture(),
  42138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42139. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42140. __decorate([
  42141. BABYLON.serializeAsColor3("specular"),
  42142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42143. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42144. __decorate([
  42145. BABYLON.serialize(),
  42146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42147. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42148. __decorate([
  42149. BABYLON.serializeAsTexture(),
  42150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42151. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42152. return PBRSpecularGlossinessMaterial;
  42153. }(BABYLON.PBRBaseSimpleMaterial));
  42154. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42155. })(BABYLON || (BABYLON = {}));
  42156. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42157. var BABYLON;
  42158. (function (BABYLON) {
  42159. BABYLON.CameraInputTypes = {};
  42160. var CameraInputsManager = /** @class */ (function () {
  42161. function CameraInputsManager(camera) {
  42162. this.attached = {};
  42163. this.camera = camera;
  42164. this.checkInputs = function () { };
  42165. }
  42166. /**
  42167. * Add an input method to a camera.
  42168. * builtin inputs example: camera.inputs.addGamepad();
  42169. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42170. * @param input camera input method
  42171. */
  42172. CameraInputsManager.prototype.add = function (input) {
  42173. var type = input.getSimpleName();
  42174. if (this.attached[type]) {
  42175. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42176. return;
  42177. }
  42178. this.attached[type] = input;
  42179. input.camera = this.camera;
  42180. //for checkInputs, we are dynamically creating a function
  42181. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42182. if (input.checkInputs) {
  42183. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42184. }
  42185. if (this.attachedElement) {
  42186. input.attachControl(this.attachedElement);
  42187. }
  42188. };
  42189. /**
  42190. * Remove a specific input method from a camera
  42191. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42192. * @param inputToRemove camera input method
  42193. */
  42194. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42195. for (var cam in this.attached) {
  42196. var input = this.attached[cam];
  42197. if (input === inputToRemove) {
  42198. input.detachControl(this.attachedElement);
  42199. input.camera = null;
  42200. delete this.attached[cam];
  42201. this.rebuildInputCheck();
  42202. }
  42203. }
  42204. };
  42205. CameraInputsManager.prototype.removeByType = function (inputType) {
  42206. for (var cam in this.attached) {
  42207. var input = this.attached[cam];
  42208. if (input.getClassName() === inputType) {
  42209. input.detachControl(this.attachedElement);
  42210. input.camera = null;
  42211. delete this.attached[cam];
  42212. this.rebuildInputCheck();
  42213. }
  42214. }
  42215. };
  42216. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42217. var current = this.checkInputs;
  42218. return function () {
  42219. current();
  42220. fn();
  42221. };
  42222. };
  42223. CameraInputsManager.prototype.attachInput = function (input) {
  42224. if (this.attachedElement) {
  42225. input.attachControl(this.attachedElement, this.noPreventDefault);
  42226. }
  42227. };
  42228. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42229. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42230. if (this.attachedElement) {
  42231. return;
  42232. }
  42233. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42234. this.attachedElement = element;
  42235. this.noPreventDefault = noPreventDefault;
  42236. for (var cam in this.attached) {
  42237. this.attached[cam].attachControl(element, noPreventDefault);
  42238. }
  42239. };
  42240. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42241. if (disconnect === void 0) { disconnect = false; }
  42242. if (this.attachedElement !== element) {
  42243. return;
  42244. }
  42245. for (var cam in this.attached) {
  42246. this.attached[cam].detachControl(element);
  42247. if (disconnect) {
  42248. this.attached[cam].camera = null;
  42249. }
  42250. }
  42251. this.attachedElement = null;
  42252. };
  42253. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42254. this.checkInputs = function () { };
  42255. for (var cam in this.attached) {
  42256. var input = this.attached[cam];
  42257. if (input.checkInputs) {
  42258. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42259. }
  42260. }
  42261. };
  42262. /**
  42263. * Remove all attached input methods from a camera
  42264. */
  42265. CameraInputsManager.prototype.clear = function () {
  42266. if (this.attachedElement) {
  42267. this.detachElement(this.attachedElement, true);
  42268. }
  42269. this.attached = {};
  42270. this.attachedElement = null;
  42271. this.checkInputs = function () { };
  42272. };
  42273. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42274. var inputs = {};
  42275. for (var cam in this.attached) {
  42276. var input = this.attached[cam];
  42277. var res = BABYLON.SerializationHelper.Serialize(input);
  42278. inputs[input.getClassName()] = res;
  42279. }
  42280. serializedCamera.inputsmgr = inputs;
  42281. };
  42282. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42283. var parsedInputs = parsedCamera.inputsmgr;
  42284. if (parsedInputs) {
  42285. this.clear();
  42286. for (var n in parsedInputs) {
  42287. var construct = BABYLON.CameraInputTypes[n];
  42288. if (construct) {
  42289. var parsedinput = parsedInputs[n];
  42290. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42291. this.add(input);
  42292. }
  42293. }
  42294. }
  42295. else {
  42296. //2016-03-08 this part is for managing backward compatibility
  42297. for (var n in this.attached) {
  42298. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42299. if (construct) {
  42300. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42301. this.remove(this.attached[n]);
  42302. this.add(input);
  42303. }
  42304. }
  42305. }
  42306. };
  42307. return CameraInputsManager;
  42308. }());
  42309. BABYLON.CameraInputsManager = CameraInputsManager;
  42310. })(BABYLON || (BABYLON = {}));
  42311. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42312. var BABYLON;
  42313. (function (BABYLON) {
  42314. var TargetCamera = /** @class */ (function (_super) {
  42315. __extends(TargetCamera, _super);
  42316. function TargetCamera(name, position, scene) {
  42317. var _this = _super.call(this, name, position, scene) || this;
  42318. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42319. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42320. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42321. _this.speed = 2.0;
  42322. _this.noRotationConstraint = false;
  42323. _this.lockedTarget = null;
  42324. _this._currentTarget = BABYLON.Vector3.Zero();
  42325. _this._viewMatrix = BABYLON.Matrix.Zero();
  42326. _this._camMatrix = BABYLON.Matrix.Zero();
  42327. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42328. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42329. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42330. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42331. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42332. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42333. _this._tempMatrix = BABYLON.Matrix.Zero();
  42334. return _this;
  42335. }
  42336. TargetCamera.prototype.getFrontPosition = function (distance) {
  42337. this.getWorldMatrix();
  42338. var direction = this.getTarget().subtract(this.position);
  42339. direction.normalize();
  42340. direction.scaleInPlace(distance);
  42341. return this.globalPosition.add(direction);
  42342. };
  42343. TargetCamera.prototype._getLockedTargetPosition = function () {
  42344. if (!this.lockedTarget) {
  42345. return null;
  42346. }
  42347. if (this.lockedTarget.absolutePosition) {
  42348. this.lockedTarget.computeWorldMatrix();
  42349. }
  42350. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42351. };
  42352. TargetCamera.prototype.storeState = function () {
  42353. this._storedPosition = this.position.clone();
  42354. this._storedRotation = this.rotation.clone();
  42355. if (this.rotationQuaternion) {
  42356. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42357. }
  42358. return _super.prototype.storeState.call(this);
  42359. };
  42360. /**
  42361. * Restored camera state. You must call storeState() first
  42362. */
  42363. TargetCamera.prototype._restoreStateValues = function () {
  42364. if (!_super.prototype._restoreStateValues.call(this)) {
  42365. return false;
  42366. }
  42367. this.position = this._storedPosition.clone();
  42368. this.rotation = this._storedRotation.clone();
  42369. if (this.rotationQuaternion) {
  42370. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42371. }
  42372. this.cameraDirection.copyFromFloats(0, 0, 0);
  42373. this.cameraRotation.copyFromFloats(0, 0);
  42374. return true;
  42375. };
  42376. // Cache
  42377. TargetCamera.prototype._initCache = function () {
  42378. _super.prototype._initCache.call(this);
  42379. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42380. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42381. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42382. };
  42383. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42384. if (!ignoreParentClass) {
  42385. _super.prototype._updateCache.call(this);
  42386. }
  42387. var lockedTargetPosition = this._getLockedTargetPosition();
  42388. if (!lockedTargetPosition) {
  42389. this._cache.lockedTarget = null;
  42390. }
  42391. else {
  42392. if (!this._cache.lockedTarget) {
  42393. this._cache.lockedTarget = lockedTargetPosition.clone();
  42394. }
  42395. else {
  42396. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42397. }
  42398. }
  42399. this._cache.rotation.copyFrom(this.rotation);
  42400. if (this.rotationQuaternion)
  42401. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42402. };
  42403. // Synchronized
  42404. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42405. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42406. return false;
  42407. }
  42408. var lockedTargetPosition = this._getLockedTargetPosition();
  42409. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42410. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42411. };
  42412. // Methods
  42413. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42414. var engine = this.getEngine();
  42415. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42416. };
  42417. // Target
  42418. TargetCamera.prototype.setTarget = function (target) {
  42419. this.upVector.normalize();
  42420. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42421. this._camMatrix.invert();
  42422. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42423. var vDir = target.subtract(this.position);
  42424. if (vDir.x >= 0.0) {
  42425. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42426. }
  42427. else {
  42428. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42429. }
  42430. this.rotation.z = 0;
  42431. if (isNaN(this.rotation.x)) {
  42432. this.rotation.x = 0;
  42433. }
  42434. if (isNaN(this.rotation.y)) {
  42435. this.rotation.y = 0;
  42436. }
  42437. if (isNaN(this.rotation.z)) {
  42438. this.rotation.z = 0;
  42439. }
  42440. if (this.rotationQuaternion) {
  42441. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42442. }
  42443. };
  42444. /**
  42445. * Return the current target position of the camera. This value is expressed in local space.
  42446. */
  42447. TargetCamera.prototype.getTarget = function () {
  42448. return this._currentTarget;
  42449. };
  42450. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42451. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42452. };
  42453. TargetCamera.prototype._updatePosition = function () {
  42454. if (this.parent) {
  42455. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42456. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42457. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42458. return;
  42459. }
  42460. this.position.addInPlace(this.cameraDirection);
  42461. };
  42462. TargetCamera.prototype._checkInputs = function () {
  42463. var needToMove = this._decideIfNeedsToMove();
  42464. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42465. // Move
  42466. if (needToMove) {
  42467. this._updatePosition();
  42468. }
  42469. // Rotate
  42470. if (needToRotate) {
  42471. this.rotation.x += this.cameraRotation.x;
  42472. this.rotation.y += this.cameraRotation.y;
  42473. //rotate, if quaternion is set and rotation was used
  42474. if (this.rotationQuaternion) {
  42475. var len = this.rotation.lengthSquared();
  42476. if (len) {
  42477. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42478. }
  42479. }
  42480. if (!this.noRotationConstraint) {
  42481. var limit = (Math.PI / 2) * 0.95;
  42482. if (this.rotation.x > limit)
  42483. this.rotation.x = limit;
  42484. if (this.rotation.x < -limit)
  42485. this.rotation.x = -limit;
  42486. }
  42487. }
  42488. // Inertia
  42489. if (needToMove) {
  42490. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42491. this.cameraDirection.x = 0;
  42492. }
  42493. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42494. this.cameraDirection.y = 0;
  42495. }
  42496. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42497. this.cameraDirection.z = 0;
  42498. }
  42499. this.cameraDirection.scaleInPlace(this.inertia);
  42500. }
  42501. if (needToRotate) {
  42502. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42503. this.cameraRotation.x = 0;
  42504. }
  42505. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42506. this.cameraRotation.y = 0;
  42507. }
  42508. this.cameraRotation.scaleInPlace(this.inertia);
  42509. }
  42510. _super.prototype._checkInputs.call(this);
  42511. };
  42512. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42513. if (this.rotationQuaternion) {
  42514. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42515. }
  42516. else {
  42517. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42518. }
  42519. //update the up vector!
  42520. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42521. };
  42522. TargetCamera.prototype._getViewMatrix = function () {
  42523. if (this.lockedTarget) {
  42524. this.setTarget(this._getLockedTargetPosition());
  42525. }
  42526. // Compute
  42527. this._updateCameraRotationMatrix();
  42528. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42529. // Computing target and final matrix
  42530. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42531. if (this.getScene().useRightHandedSystem) {
  42532. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42533. }
  42534. else {
  42535. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42536. }
  42537. return this._viewMatrix;
  42538. };
  42539. /**
  42540. * @override
  42541. * Override Camera.createRigCamera
  42542. */
  42543. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42544. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42545. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42546. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42547. if (!this.rotationQuaternion) {
  42548. this.rotationQuaternion = new BABYLON.Quaternion();
  42549. }
  42550. rigCamera._cameraRigParams = {};
  42551. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42552. }
  42553. return rigCamera;
  42554. }
  42555. return null;
  42556. };
  42557. /**
  42558. * @override
  42559. * Override Camera._updateRigCameras
  42560. */
  42561. TargetCamera.prototype._updateRigCameras = function () {
  42562. var camLeft = this._rigCameras[0];
  42563. var camRight = this._rigCameras[1];
  42564. switch (this.cameraRigMode) {
  42565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42566. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42567. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42569. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42570. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42571. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42572. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42573. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42574. camLeft.setTarget(this.getTarget());
  42575. camRight.setTarget(this.getTarget());
  42576. break;
  42577. case BABYLON.Camera.RIG_MODE_VR:
  42578. if (camLeft.rotationQuaternion) {
  42579. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42580. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42581. }
  42582. else {
  42583. camLeft.rotation.copyFrom(this.rotation);
  42584. camRight.rotation.copyFrom(this.rotation);
  42585. }
  42586. camLeft.position.copyFrom(this.position);
  42587. camRight.position.copyFrom(this.position);
  42588. break;
  42589. }
  42590. _super.prototype._updateRigCameras.call(this);
  42591. };
  42592. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42593. if (!this._rigCamTransformMatrix) {
  42594. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42595. }
  42596. var target = this.getTarget();
  42597. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42598. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42599. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42600. };
  42601. TargetCamera.prototype.getClassName = function () {
  42602. return "TargetCamera";
  42603. };
  42604. __decorate([
  42605. BABYLON.serializeAsVector3()
  42606. ], TargetCamera.prototype, "rotation", void 0);
  42607. __decorate([
  42608. BABYLON.serialize()
  42609. ], TargetCamera.prototype, "speed", void 0);
  42610. __decorate([
  42611. BABYLON.serializeAsMeshReference("lockedTargetId")
  42612. ], TargetCamera.prototype, "lockedTarget", void 0);
  42613. return TargetCamera;
  42614. }(BABYLON.Camera));
  42615. BABYLON.TargetCamera = TargetCamera;
  42616. })(BABYLON || (BABYLON = {}));
  42617. //# sourceMappingURL=babylon.targetCamera.js.map
  42618. var BABYLON;
  42619. (function (BABYLON) {
  42620. var FreeCameraMouseInput = /** @class */ (function () {
  42621. function FreeCameraMouseInput(touchEnabled) {
  42622. if (touchEnabled === void 0) { touchEnabled = true; }
  42623. this.touchEnabled = touchEnabled;
  42624. this.buttons = [0, 1, 2];
  42625. this.angularSensibility = 2000.0;
  42626. this.previousPosition = null;
  42627. }
  42628. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42629. var _this = this;
  42630. var engine = this.camera.getEngine();
  42631. if (!this._pointerInput) {
  42632. this._pointerInput = function (p, s) {
  42633. var evt = p.event;
  42634. if (engine.isInVRExclusivePointerMode) {
  42635. return;
  42636. }
  42637. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42638. return;
  42639. }
  42640. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42641. return;
  42642. }
  42643. var srcElement = (evt.srcElement || evt.target);
  42644. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42645. try {
  42646. srcElement.setPointerCapture(evt.pointerId);
  42647. }
  42648. catch (e) {
  42649. //Nothing to do with the error. Execution will continue.
  42650. }
  42651. _this.previousPosition = {
  42652. x: evt.clientX,
  42653. y: evt.clientY
  42654. };
  42655. if (!noPreventDefault) {
  42656. evt.preventDefault();
  42657. element.focus();
  42658. }
  42659. }
  42660. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42661. try {
  42662. srcElement.releasePointerCapture(evt.pointerId);
  42663. }
  42664. catch (e) {
  42665. //Nothing to do with the error.
  42666. }
  42667. _this.previousPosition = null;
  42668. if (!noPreventDefault) {
  42669. evt.preventDefault();
  42670. }
  42671. }
  42672. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42673. if (!_this.previousPosition || engine.isPointerLock) {
  42674. return;
  42675. }
  42676. var offsetX = evt.clientX - _this.previousPosition.x;
  42677. var offsetY = evt.clientY - _this.previousPosition.y;
  42678. if (_this.camera.getScene().useRightHandedSystem) {
  42679. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42680. }
  42681. else {
  42682. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42683. }
  42684. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42685. _this.previousPosition = {
  42686. x: evt.clientX,
  42687. y: evt.clientY
  42688. };
  42689. if (!noPreventDefault) {
  42690. evt.preventDefault();
  42691. }
  42692. }
  42693. };
  42694. }
  42695. this._onMouseMove = function (evt) {
  42696. if (!engine.isPointerLock) {
  42697. return;
  42698. }
  42699. if (engine.isInVRExclusivePointerMode) {
  42700. return;
  42701. }
  42702. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42703. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42704. if (_this.camera.getScene().useRightHandedSystem) {
  42705. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42706. }
  42707. else {
  42708. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42709. }
  42710. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42711. _this.previousPosition = null;
  42712. if (!noPreventDefault) {
  42713. evt.preventDefault();
  42714. }
  42715. };
  42716. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42717. element.addEventListener("mousemove", this._onMouseMove, false);
  42718. };
  42719. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42720. if (this._observer && element) {
  42721. this.camera.getScene().onPointerObservable.remove(this._observer);
  42722. if (this._onMouseMove) {
  42723. element.removeEventListener("mousemove", this._onMouseMove);
  42724. }
  42725. this._observer = null;
  42726. this._onMouseMove = null;
  42727. this.previousPosition = null;
  42728. }
  42729. };
  42730. FreeCameraMouseInput.prototype.getClassName = function () {
  42731. return "FreeCameraMouseInput";
  42732. };
  42733. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42734. return "mouse";
  42735. };
  42736. __decorate([
  42737. BABYLON.serialize()
  42738. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42739. __decorate([
  42740. BABYLON.serialize()
  42741. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42742. return FreeCameraMouseInput;
  42743. }());
  42744. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42745. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42746. })(BABYLON || (BABYLON = {}));
  42747. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42748. var BABYLON;
  42749. (function (BABYLON) {
  42750. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42751. function FreeCameraKeyboardMoveInput() {
  42752. this._keys = new Array();
  42753. this.keysUp = [38];
  42754. this.keysDown = [40];
  42755. this.keysLeft = [37];
  42756. this.keysRight = [39];
  42757. }
  42758. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42759. var _this = this;
  42760. if (this._onCanvasBlurObserver) {
  42761. return;
  42762. }
  42763. this._scene = this.camera.getScene();
  42764. this._engine = this._scene.getEngine();
  42765. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42766. _this._keys = [];
  42767. });
  42768. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42769. var evt = info.event;
  42770. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42771. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42772. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42773. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42774. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42775. var index = _this._keys.indexOf(evt.keyCode);
  42776. if (index === -1) {
  42777. _this._keys.push(evt.keyCode);
  42778. }
  42779. if (!noPreventDefault) {
  42780. evt.preventDefault();
  42781. }
  42782. }
  42783. }
  42784. else {
  42785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42788. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42789. var index = _this._keys.indexOf(evt.keyCode);
  42790. if (index >= 0) {
  42791. _this._keys.splice(index, 1);
  42792. }
  42793. if (!noPreventDefault) {
  42794. evt.preventDefault();
  42795. }
  42796. }
  42797. }
  42798. });
  42799. };
  42800. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42801. if (this._scene) {
  42802. if (this._onKeyboardObserver) {
  42803. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42804. }
  42805. if (this._onCanvasBlurObserver) {
  42806. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42807. }
  42808. this._onKeyboardObserver = null;
  42809. this._onCanvasBlurObserver = null;
  42810. }
  42811. this._keys = [];
  42812. };
  42813. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42814. if (this._onKeyboardObserver) {
  42815. var camera = this.camera;
  42816. // Keyboard
  42817. for (var index = 0; index < this._keys.length; index++) {
  42818. var keyCode = this._keys[index];
  42819. var speed = camera._computeLocalCameraSpeed();
  42820. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42821. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42822. }
  42823. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42824. camera._localDirection.copyFromFloats(0, 0, speed);
  42825. }
  42826. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42827. camera._localDirection.copyFromFloats(speed, 0, 0);
  42828. }
  42829. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42830. camera._localDirection.copyFromFloats(0, 0, -speed);
  42831. }
  42832. if (camera.getScene().useRightHandedSystem) {
  42833. camera._localDirection.z *= -1;
  42834. }
  42835. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42836. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42837. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42838. }
  42839. }
  42840. };
  42841. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42842. return "FreeCameraKeyboardMoveInput";
  42843. };
  42844. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42845. this._keys = [];
  42846. };
  42847. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42848. return "keyboard";
  42849. };
  42850. __decorate([
  42851. BABYLON.serialize()
  42852. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42853. __decorate([
  42854. BABYLON.serialize()
  42855. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42856. __decorate([
  42857. BABYLON.serialize()
  42858. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42859. __decorate([
  42860. BABYLON.serialize()
  42861. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42862. return FreeCameraKeyboardMoveInput;
  42863. }());
  42864. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42865. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42866. })(BABYLON || (BABYLON = {}));
  42867. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42868. var BABYLON;
  42869. (function (BABYLON) {
  42870. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42871. __extends(FreeCameraInputsManager, _super);
  42872. function FreeCameraInputsManager(camera) {
  42873. return _super.call(this, camera) || this;
  42874. }
  42875. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42876. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42877. return this;
  42878. };
  42879. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42880. if (touchEnabled === void 0) { touchEnabled = true; }
  42881. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42882. return this;
  42883. };
  42884. FreeCameraInputsManager.prototype.addGamepad = function () {
  42885. this.add(new BABYLON.FreeCameraGamepadInput());
  42886. return this;
  42887. };
  42888. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42889. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42890. return this;
  42891. };
  42892. FreeCameraInputsManager.prototype.addTouch = function () {
  42893. this.add(new BABYLON.FreeCameraTouchInput());
  42894. return this;
  42895. };
  42896. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42897. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42898. return this;
  42899. };
  42900. return FreeCameraInputsManager;
  42901. }(BABYLON.CameraInputsManager));
  42902. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42903. })(BABYLON || (BABYLON = {}));
  42904. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42905. var BABYLON;
  42906. (function (BABYLON) {
  42907. var FreeCamera = /** @class */ (function (_super) {
  42908. __extends(FreeCamera, _super);
  42909. function FreeCamera(name, position, scene) {
  42910. var _this = _super.call(this, name, position, scene) || this;
  42911. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42912. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42913. _this.checkCollisions = false;
  42914. _this.applyGravity = false;
  42915. _this._needMoveForGravity = false;
  42916. _this._oldPosition = BABYLON.Vector3.Zero();
  42917. _this._diffPosition = BABYLON.Vector3.Zero();
  42918. _this._newPosition = BABYLON.Vector3.Zero();
  42919. // Collisions
  42920. _this._collisionMask = -1;
  42921. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42922. if (collidedMesh === void 0) { collidedMesh = null; }
  42923. //TODO move this to the collision coordinator!
  42924. if (_this.getScene().workerCollisions)
  42925. newPosition.multiplyInPlace(_this._collider._radius);
  42926. var updatePosition = function (newPos) {
  42927. _this._newPosition.copyFrom(newPos);
  42928. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42929. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42930. _this.position.addInPlace(_this._diffPosition);
  42931. if (_this.onCollide && collidedMesh) {
  42932. _this.onCollide(collidedMesh);
  42933. }
  42934. }
  42935. };
  42936. updatePosition(newPosition);
  42937. };
  42938. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42939. _this.inputs.addKeyboard().addMouse();
  42940. return _this;
  42941. }
  42942. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42943. //-- begin properties for backward compatibility for inputs
  42944. /**
  42945. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42946. * Higher values reduce sensitivity.
  42947. */
  42948. get: function () {
  42949. var mouse = this.inputs.attached["mouse"];
  42950. if (mouse)
  42951. return mouse.angularSensibility;
  42952. return 0;
  42953. },
  42954. /**
  42955. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42956. * Higher values reduce sensitivity.
  42957. */
  42958. set: function (value) {
  42959. var mouse = this.inputs.attached["mouse"];
  42960. if (mouse)
  42961. mouse.angularSensibility = value;
  42962. },
  42963. enumerable: true,
  42964. configurable: true
  42965. });
  42966. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42967. get: function () {
  42968. var keyboard = this.inputs.attached["keyboard"];
  42969. if (keyboard)
  42970. return keyboard.keysUp;
  42971. return [];
  42972. },
  42973. set: function (value) {
  42974. var keyboard = this.inputs.attached["keyboard"];
  42975. if (keyboard)
  42976. keyboard.keysUp = value;
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42982. get: function () {
  42983. var keyboard = this.inputs.attached["keyboard"];
  42984. if (keyboard)
  42985. return keyboard.keysDown;
  42986. return [];
  42987. },
  42988. set: function (value) {
  42989. var keyboard = this.inputs.attached["keyboard"];
  42990. if (keyboard)
  42991. keyboard.keysDown = value;
  42992. },
  42993. enumerable: true,
  42994. configurable: true
  42995. });
  42996. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42997. get: function () {
  42998. var keyboard = this.inputs.attached["keyboard"];
  42999. if (keyboard)
  43000. return keyboard.keysLeft;
  43001. return [];
  43002. },
  43003. set: function (value) {
  43004. var keyboard = this.inputs.attached["keyboard"];
  43005. if (keyboard)
  43006. keyboard.keysLeft = value;
  43007. },
  43008. enumerable: true,
  43009. configurable: true
  43010. });
  43011. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43012. get: function () {
  43013. var keyboard = this.inputs.attached["keyboard"];
  43014. if (keyboard)
  43015. return keyboard.keysRight;
  43016. return [];
  43017. },
  43018. set: function (value) {
  43019. var keyboard = this.inputs.attached["keyboard"];
  43020. if (keyboard)
  43021. keyboard.keysRight = value;
  43022. },
  43023. enumerable: true,
  43024. configurable: true
  43025. });
  43026. // Controls
  43027. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43028. this.inputs.attachElement(element, noPreventDefault);
  43029. };
  43030. FreeCamera.prototype.detachControl = function (element) {
  43031. this.inputs.detachElement(element);
  43032. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43033. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43034. };
  43035. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43036. get: function () {
  43037. return this._collisionMask;
  43038. },
  43039. set: function (mask) {
  43040. this._collisionMask = !isNaN(mask) ? mask : -1;
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43046. var globalPosition;
  43047. if (this.parent) {
  43048. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43049. }
  43050. else {
  43051. globalPosition = this.position;
  43052. }
  43053. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43054. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43055. if (!this._collider) {
  43056. this._collider = new BABYLON.Collider();
  43057. }
  43058. this._collider._radius = this.ellipsoid;
  43059. this._collider.collisionMask = this._collisionMask;
  43060. //no need for clone, as long as gravity is not on.
  43061. var actualDisplacement = displacement;
  43062. //add gravity to the direction to prevent the dual-collision checking
  43063. if (this.applyGravity) {
  43064. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43065. actualDisplacement = displacement.add(this.getScene().gravity);
  43066. }
  43067. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43068. };
  43069. FreeCamera.prototype._checkInputs = function () {
  43070. if (!this._localDirection) {
  43071. this._localDirection = BABYLON.Vector3.Zero();
  43072. this._transformedDirection = BABYLON.Vector3.Zero();
  43073. }
  43074. this.inputs.checkInputs();
  43075. _super.prototype._checkInputs.call(this);
  43076. };
  43077. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43078. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43079. };
  43080. FreeCamera.prototype._updatePosition = function () {
  43081. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43082. this._collideWithWorld(this.cameraDirection);
  43083. }
  43084. else {
  43085. _super.prototype._updatePosition.call(this);
  43086. }
  43087. };
  43088. FreeCamera.prototype.dispose = function () {
  43089. this.inputs.clear();
  43090. _super.prototype.dispose.call(this);
  43091. };
  43092. FreeCamera.prototype.getClassName = function () {
  43093. return "FreeCamera";
  43094. };
  43095. __decorate([
  43096. BABYLON.serializeAsVector3()
  43097. ], FreeCamera.prototype, "ellipsoid", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsVector3()
  43100. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43101. __decorate([
  43102. BABYLON.serialize()
  43103. ], FreeCamera.prototype, "checkCollisions", void 0);
  43104. __decorate([
  43105. BABYLON.serialize()
  43106. ], FreeCamera.prototype, "applyGravity", void 0);
  43107. return FreeCamera;
  43108. }(BABYLON.TargetCamera));
  43109. BABYLON.FreeCamera = FreeCamera;
  43110. })(BABYLON || (BABYLON = {}));
  43111. //# sourceMappingURL=babylon.freeCamera.js.map
  43112. var BABYLON;
  43113. (function (BABYLON) {
  43114. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43115. function ArcRotateCameraKeyboardMoveInput() {
  43116. this._keys = new Array();
  43117. this.keysUp = [38];
  43118. this.keysDown = [40];
  43119. this.keysLeft = [37];
  43120. this.keysRight = [39];
  43121. this.keysReset = [220];
  43122. this.panningSensibility = 50.0;
  43123. this.zoomingSensibility = 25.0;
  43124. this.useAltToZoom = true;
  43125. }
  43126. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43127. var _this = this;
  43128. if (this._onCanvasBlurObserver) {
  43129. return;
  43130. }
  43131. this._scene = this.camera.getScene();
  43132. this._engine = this._scene.getEngine();
  43133. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43134. _this._keys = [];
  43135. });
  43136. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43137. var evt = info.event;
  43138. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43139. _this._ctrlPressed = evt.ctrlKey;
  43140. _this._altPressed = evt.altKey;
  43141. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43142. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43143. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43144. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43145. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43146. var index = _this._keys.indexOf(evt.keyCode);
  43147. if (index === -1) {
  43148. _this._keys.push(evt.keyCode);
  43149. }
  43150. if (evt.preventDefault) {
  43151. if (!noPreventDefault) {
  43152. evt.preventDefault();
  43153. }
  43154. }
  43155. }
  43156. }
  43157. else {
  43158. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43159. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43160. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43161. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43162. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43163. var index = _this._keys.indexOf(evt.keyCode);
  43164. if (index >= 0) {
  43165. _this._keys.splice(index, 1);
  43166. }
  43167. if (evt.preventDefault) {
  43168. if (!noPreventDefault) {
  43169. evt.preventDefault();
  43170. }
  43171. }
  43172. }
  43173. }
  43174. });
  43175. };
  43176. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43177. if (this._scene) {
  43178. if (this._onKeyboardObserver) {
  43179. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43180. }
  43181. if (this._onCanvasBlurObserver) {
  43182. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43183. }
  43184. this._onKeyboardObserver = null;
  43185. this._onCanvasBlurObserver = null;
  43186. }
  43187. this._keys = [];
  43188. };
  43189. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43190. if (this._onKeyboardObserver) {
  43191. var camera = this.camera;
  43192. for (var index = 0; index < this._keys.length; index++) {
  43193. var keyCode = this._keys[index];
  43194. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43195. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43196. camera.inertialPanningX -= 1 / this.panningSensibility;
  43197. }
  43198. else {
  43199. camera.inertialAlphaOffset -= 0.01;
  43200. }
  43201. }
  43202. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43203. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43204. camera.inertialPanningY += 1 / this.panningSensibility;
  43205. }
  43206. else if (this._altPressed && this.useAltToZoom) {
  43207. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43208. }
  43209. else {
  43210. camera.inertialBetaOffset -= 0.01;
  43211. }
  43212. }
  43213. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43214. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43215. camera.inertialPanningX += 1 / this.panningSensibility;
  43216. }
  43217. else {
  43218. camera.inertialAlphaOffset += 0.01;
  43219. }
  43220. }
  43221. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43222. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43223. camera.inertialPanningY -= 1 / this.panningSensibility;
  43224. }
  43225. else if (this._altPressed && this.useAltToZoom) {
  43226. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43227. }
  43228. else {
  43229. camera.inertialBetaOffset += 0.01;
  43230. }
  43231. }
  43232. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43233. camera.restoreState();
  43234. }
  43235. }
  43236. }
  43237. };
  43238. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43239. return "ArcRotateCameraKeyboardMoveInput";
  43240. };
  43241. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43242. return "keyboard";
  43243. };
  43244. __decorate([
  43245. BABYLON.serialize()
  43246. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43247. __decorate([
  43248. BABYLON.serialize()
  43249. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43250. __decorate([
  43251. BABYLON.serialize()
  43252. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43253. __decorate([
  43254. BABYLON.serialize()
  43255. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43256. __decorate([
  43257. BABYLON.serialize()
  43258. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43259. __decorate([
  43260. BABYLON.serialize()
  43261. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43262. __decorate([
  43263. BABYLON.serialize()
  43264. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43265. __decorate([
  43266. BABYLON.serialize()
  43267. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43268. return ArcRotateCameraKeyboardMoveInput;
  43269. }());
  43270. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43271. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43272. })(BABYLON || (BABYLON = {}));
  43273. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43277. function ArcRotateCameraMouseWheelInput() {
  43278. this.wheelPrecision = 3.0;
  43279. /**
  43280. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43281. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43282. */
  43283. this.wheelDeltaPercentage = 0;
  43284. }
  43285. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43286. var _this = this;
  43287. this._wheel = function (p, s) {
  43288. //sanity check - this should be a PointerWheel event.
  43289. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43290. return;
  43291. var event = p.event;
  43292. var delta = 0;
  43293. if (event.wheelDelta) {
  43294. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43295. }
  43296. else if (event.detail) {
  43297. delta = -event.detail / _this.wheelPrecision;
  43298. }
  43299. if (delta)
  43300. _this.camera.inertialRadiusOffset += delta;
  43301. if (event.preventDefault) {
  43302. if (!noPreventDefault) {
  43303. event.preventDefault();
  43304. }
  43305. }
  43306. };
  43307. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43308. };
  43309. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43310. if (this._observer && element) {
  43311. this.camera.getScene().onPointerObservable.remove(this._observer);
  43312. this._observer = null;
  43313. this._wheel = null;
  43314. }
  43315. };
  43316. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43317. return "ArcRotateCameraMouseWheelInput";
  43318. };
  43319. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43320. return "mousewheel";
  43321. };
  43322. __decorate([
  43323. BABYLON.serialize()
  43324. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43325. __decorate([
  43326. BABYLON.serialize()
  43327. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43328. return ArcRotateCameraMouseWheelInput;
  43329. }());
  43330. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43331. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43332. })(BABYLON || (BABYLON = {}));
  43333. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43334. var BABYLON;
  43335. (function (BABYLON) {
  43336. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43337. function ArcRotateCameraPointersInput() {
  43338. this.buttons = [0, 1, 2];
  43339. this.angularSensibilityX = 1000.0;
  43340. this.angularSensibilityY = 1000.0;
  43341. this.pinchPrecision = 12.0;
  43342. /**
  43343. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43344. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43345. */
  43346. this.pinchDeltaPercentage = 0;
  43347. this.panningSensibility = 1000.0;
  43348. this.multiTouchPanning = true;
  43349. this.multiTouchPanAndZoom = true;
  43350. this._isPanClick = false;
  43351. this.pinchInwards = true;
  43352. }
  43353. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43354. var _this = this;
  43355. var engine = this.camera.getEngine();
  43356. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43357. var pointA = null;
  43358. var pointB = null;
  43359. var previousPinchSquaredDistance = 0;
  43360. var initialDistance = 0;
  43361. var twoFingerActivityCount = 0;
  43362. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43363. this._pointerInput = function (p, s) {
  43364. var evt = p.event;
  43365. var isTouch = p.event.pointerType === "touch";
  43366. if (engine.isInVRExclusivePointerMode) {
  43367. return;
  43368. }
  43369. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43370. return;
  43371. }
  43372. var srcElement = (evt.srcElement || evt.target);
  43373. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43374. try {
  43375. srcElement.setPointerCapture(evt.pointerId);
  43376. }
  43377. catch (e) {
  43378. //Nothing to do with the error. Execution will continue.
  43379. }
  43380. // Manage panning with pan button click
  43381. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43382. // manage pointers
  43383. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43384. if (pointA === null) {
  43385. pointA = cacheSoloPointer;
  43386. }
  43387. else if (pointB === null) {
  43388. pointB = cacheSoloPointer;
  43389. }
  43390. if (!noPreventDefault) {
  43391. evt.preventDefault();
  43392. element.focus();
  43393. }
  43394. }
  43395. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43396. _this.camera.restoreState();
  43397. }
  43398. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43399. try {
  43400. srcElement.releasePointerCapture(evt.pointerId);
  43401. }
  43402. catch (e) {
  43403. //Nothing to do with the error.
  43404. }
  43405. cacheSoloPointer = null;
  43406. previousPinchSquaredDistance = 0;
  43407. previousMultiTouchPanPosition.isPaning = false;
  43408. previousMultiTouchPanPosition.isPinching = false;
  43409. twoFingerActivityCount = 0;
  43410. initialDistance = 0;
  43411. if (!isTouch) {
  43412. pointB = null; // Mouse and pen are mono pointer
  43413. }
  43414. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43415. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43416. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43417. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43418. if (engine.badOS) {
  43419. pointA = pointB = null;
  43420. }
  43421. else {
  43422. //only remove the impacted pointer in case of multitouch allowing on most
  43423. //platforms switching from rotate to zoom and pan seamlessly.
  43424. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43425. pointA = pointB;
  43426. pointB = null;
  43427. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43428. }
  43429. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43430. pointB = null;
  43431. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43432. }
  43433. else {
  43434. pointA = pointB = null;
  43435. }
  43436. }
  43437. if (!noPreventDefault) {
  43438. evt.preventDefault();
  43439. }
  43440. }
  43441. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43442. if (!noPreventDefault) {
  43443. evt.preventDefault();
  43444. }
  43445. // One button down
  43446. if (pointA && pointB === null && cacheSoloPointer) {
  43447. if (_this.panningSensibility !== 0 &&
  43448. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43449. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43450. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43451. }
  43452. else {
  43453. var offsetX = evt.clientX - cacheSoloPointer.x;
  43454. var offsetY = evt.clientY - cacheSoloPointer.y;
  43455. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43456. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43457. }
  43458. cacheSoloPointer.x = evt.clientX;
  43459. cacheSoloPointer.y = evt.clientY;
  43460. }
  43461. else if (pointA && pointB) {
  43462. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43463. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43464. ed.x = evt.clientX;
  43465. ed.y = evt.clientY;
  43466. var direction = _this.pinchInwards ? 1 : -1;
  43467. var distX = pointA.x - pointB.x;
  43468. var distY = pointA.y - pointB.y;
  43469. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43470. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43471. if (previousPinchSquaredDistance === 0) {
  43472. initialDistance = pinchDistance;
  43473. previousPinchSquaredDistance = pinchSquaredDistance;
  43474. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43475. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43476. return;
  43477. }
  43478. if (_this.multiTouchPanAndZoom) {
  43479. if (_this.pinchDeltaPercentage) {
  43480. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43481. }
  43482. else {
  43483. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43484. (_this.pinchPrecision *
  43485. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43486. direction);
  43487. }
  43488. if (_this.panningSensibility !== 0) {
  43489. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43490. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43491. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43492. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43493. previousMultiTouchPanPosition.x = pointersCenterX;
  43494. previousMultiTouchPanPosition.y = pointersCenterY;
  43495. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43496. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43497. }
  43498. }
  43499. else {
  43500. twoFingerActivityCount++;
  43501. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43502. if (_this.pinchDeltaPercentage) {
  43503. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43504. }
  43505. else {
  43506. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43507. (_this.pinchPrecision *
  43508. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43509. direction);
  43510. }
  43511. previousMultiTouchPanPosition.isPaning = false;
  43512. previousMultiTouchPanPosition.isPinching = true;
  43513. }
  43514. else {
  43515. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43516. if (!previousMultiTouchPanPosition.isPaning) {
  43517. previousMultiTouchPanPosition.isPaning = true;
  43518. previousMultiTouchPanPosition.isPinching = false;
  43519. previousMultiTouchPanPosition.x = ed.x;
  43520. previousMultiTouchPanPosition.y = ed.y;
  43521. return;
  43522. }
  43523. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43524. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43525. }
  43526. }
  43527. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43528. previousMultiTouchPanPosition.x = ed.x;
  43529. previousMultiTouchPanPosition.y = ed.y;
  43530. }
  43531. }
  43532. previousPinchSquaredDistance = pinchSquaredDistance;
  43533. }
  43534. }
  43535. };
  43536. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43537. this._onContextMenu = function (evt) {
  43538. evt.preventDefault();
  43539. };
  43540. if (!this.camera._useCtrlForPanning) {
  43541. element.addEventListener("contextmenu", this._onContextMenu, false);
  43542. }
  43543. this._onLostFocus = function () {
  43544. //this._keys = [];
  43545. pointA = pointB = null;
  43546. previousPinchSquaredDistance = 0;
  43547. previousMultiTouchPanPosition.isPaning = false;
  43548. previousMultiTouchPanPosition.isPinching = false;
  43549. twoFingerActivityCount = 0;
  43550. cacheSoloPointer = null;
  43551. initialDistance = 0;
  43552. };
  43553. this._onMouseMove = function (evt) {
  43554. if (!engine.isPointerLock) {
  43555. return;
  43556. }
  43557. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43558. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43559. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43560. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43561. if (!noPreventDefault) {
  43562. evt.preventDefault();
  43563. }
  43564. };
  43565. this._onGestureStart = function (e) {
  43566. if (window.MSGesture === undefined) {
  43567. return;
  43568. }
  43569. if (!_this._MSGestureHandler) {
  43570. _this._MSGestureHandler = new MSGesture();
  43571. _this._MSGestureHandler.target = element;
  43572. }
  43573. _this._MSGestureHandler.addPointer(e.pointerId);
  43574. };
  43575. this._onGesture = function (e) {
  43576. _this.camera.radius *= e.scale;
  43577. if (e.preventDefault) {
  43578. if (!noPreventDefault) {
  43579. e.stopPropagation();
  43580. e.preventDefault();
  43581. }
  43582. }
  43583. };
  43584. element.addEventListener("mousemove", this._onMouseMove, false);
  43585. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43586. element.addEventListener("MSGestureChange", this._onGesture, false);
  43587. BABYLON.Tools.RegisterTopRootEvents([
  43588. { name: "blur", handler: this._onLostFocus }
  43589. ]);
  43590. };
  43591. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43592. if (this._onLostFocus) {
  43593. BABYLON.Tools.UnregisterTopRootEvents([
  43594. { name: "blur", handler: this._onLostFocus }
  43595. ]);
  43596. }
  43597. if (element && this._observer) {
  43598. this.camera.getScene().onPointerObservable.remove(this._observer);
  43599. this._observer = null;
  43600. if (this._onContextMenu) {
  43601. element.removeEventListener("contextmenu", this._onContextMenu);
  43602. }
  43603. if (this._onMouseMove) {
  43604. element.removeEventListener("mousemove", this._onMouseMove);
  43605. }
  43606. if (this._onGestureStart) {
  43607. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43608. }
  43609. if (this._onGesture) {
  43610. element.removeEventListener("MSGestureChange", this._onGesture);
  43611. }
  43612. this._isPanClick = false;
  43613. this.pinchInwards = true;
  43614. this._onMouseMove = null;
  43615. this._onGestureStart = null;
  43616. this._onGesture = null;
  43617. this._MSGestureHandler = null;
  43618. this._onLostFocus = null;
  43619. this._onContextMenu = null;
  43620. }
  43621. };
  43622. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43623. return "ArcRotateCameraPointersInput";
  43624. };
  43625. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43626. return "pointers";
  43627. };
  43628. __decorate([
  43629. BABYLON.serialize()
  43630. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43631. __decorate([
  43632. BABYLON.serialize()
  43633. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43634. __decorate([
  43635. BABYLON.serialize()
  43636. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43637. __decorate([
  43638. BABYLON.serialize()
  43639. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43640. __decorate([
  43641. BABYLON.serialize()
  43642. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43643. __decorate([
  43644. BABYLON.serialize()
  43645. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43646. __decorate([
  43647. BABYLON.serialize()
  43648. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43649. __decorate([
  43650. BABYLON.serialize()
  43651. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43652. return ArcRotateCameraPointersInput;
  43653. }());
  43654. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43655. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43656. })(BABYLON || (BABYLON = {}));
  43657. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43658. var BABYLON;
  43659. (function (BABYLON) {
  43660. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43661. __extends(ArcRotateCameraInputsManager, _super);
  43662. function ArcRotateCameraInputsManager(camera) {
  43663. return _super.call(this, camera) || this;
  43664. }
  43665. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43666. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43667. return this;
  43668. };
  43669. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43670. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43671. return this;
  43672. };
  43673. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43674. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43675. return this;
  43676. };
  43677. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43678. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43679. return this;
  43680. };
  43681. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43682. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43683. return this;
  43684. };
  43685. return ArcRotateCameraInputsManager;
  43686. }(BABYLON.CameraInputsManager));
  43687. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43688. })(BABYLON || (BABYLON = {}));
  43689. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43690. var BABYLON;
  43691. (function (BABYLON) {
  43692. var ArcRotateCamera = /** @class */ (function (_super) {
  43693. __extends(ArcRotateCamera, _super);
  43694. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43695. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43696. _this.inertialAlphaOffset = 0;
  43697. _this.inertialBetaOffset = 0;
  43698. _this.inertialRadiusOffset = 0;
  43699. _this.lowerAlphaLimit = null;
  43700. _this.upperAlphaLimit = null;
  43701. _this.lowerBetaLimit = 0.01;
  43702. _this.upperBetaLimit = Math.PI;
  43703. _this.lowerRadiusLimit = null;
  43704. _this.upperRadiusLimit = null;
  43705. _this.inertialPanningX = 0;
  43706. _this.inertialPanningY = 0;
  43707. _this.pinchToPanMaxDistance = 20;
  43708. _this.panningDistanceLimit = null;
  43709. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43710. _this.panningInertia = 0.9;
  43711. //-- end properties for backward compatibility for inputs
  43712. _this.zoomOnFactor = 1;
  43713. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43714. _this.allowUpsideDown = true;
  43715. _this._viewMatrix = new BABYLON.Matrix();
  43716. // Panning
  43717. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43718. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43719. _this.checkCollisions = false;
  43720. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43721. _this._previousPosition = BABYLON.Vector3.Zero();
  43722. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43723. _this._newPosition = BABYLON.Vector3.Zero();
  43724. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43725. if (collidedMesh === void 0) { collidedMesh = null; }
  43726. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43727. newPosition.multiplyInPlace(_this._collider._radius);
  43728. }
  43729. if (!collidedMesh) {
  43730. _this._previousPosition.copyFrom(_this.position);
  43731. }
  43732. else {
  43733. _this.setPosition(newPosition);
  43734. if (_this.onCollide) {
  43735. _this.onCollide(collidedMesh);
  43736. }
  43737. }
  43738. // Recompute because of constraints
  43739. var cosa = Math.cos(_this.alpha);
  43740. var sina = Math.sin(_this.alpha);
  43741. var cosb = Math.cos(_this.beta);
  43742. var sinb = Math.sin(_this.beta);
  43743. if (sinb === 0) {
  43744. sinb = 0.0001;
  43745. }
  43746. var target = _this._getTargetPosition();
  43747. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43748. _this.position.copyFrom(_this._newPosition);
  43749. var up = _this.upVector;
  43750. if (_this.allowUpsideDown && _this.beta < 0) {
  43751. up = up.clone();
  43752. up = up.negate();
  43753. }
  43754. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43755. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43756. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43757. _this._collisionTriggered = false;
  43758. };
  43759. _this._target = BABYLON.Vector3.Zero();
  43760. if (target) {
  43761. _this.setTarget(target);
  43762. }
  43763. _this.alpha = alpha;
  43764. _this.beta = beta;
  43765. _this.radius = radius;
  43766. _this.getViewMatrix();
  43767. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43768. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43769. return _this;
  43770. }
  43771. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43772. get: function () {
  43773. return this._target;
  43774. },
  43775. set: function (value) {
  43776. this.setTarget(value);
  43777. },
  43778. enumerable: true,
  43779. configurable: true
  43780. });
  43781. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43782. //-- begin properties for backward compatibility for inputs
  43783. get: function () {
  43784. var pointers = this.inputs.attached["pointers"];
  43785. if (pointers)
  43786. return pointers.angularSensibilityX;
  43787. return 0;
  43788. },
  43789. set: function (value) {
  43790. var pointers = this.inputs.attached["pointers"];
  43791. if (pointers) {
  43792. pointers.angularSensibilityX = value;
  43793. }
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43799. get: function () {
  43800. var pointers = this.inputs.attached["pointers"];
  43801. if (pointers)
  43802. return pointers.angularSensibilityY;
  43803. return 0;
  43804. },
  43805. set: function (value) {
  43806. var pointers = this.inputs.attached["pointers"];
  43807. if (pointers) {
  43808. pointers.angularSensibilityY = value;
  43809. }
  43810. },
  43811. enumerable: true,
  43812. configurable: true
  43813. });
  43814. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43815. get: function () {
  43816. var pointers = this.inputs.attached["pointers"];
  43817. if (pointers)
  43818. return pointers.pinchPrecision;
  43819. return 0;
  43820. },
  43821. set: function (value) {
  43822. var pointers = this.inputs.attached["pointers"];
  43823. if (pointers) {
  43824. pointers.pinchPrecision = value;
  43825. }
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43831. get: function () {
  43832. var pointers = this.inputs.attached["pointers"];
  43833. if (pointers)
  43834. return pointers.pinchDeltaPercentage;
  43835. return 0;
  43836. },
  43837. set: function (value) {
  43838. var pointers = this.inputs.attached["pointers"];
  43839. if (pointers) {
  43840. pointers.pinchDeltaPercentage = value;
  43841. }
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43847. get: function () {
  43848. var pointers = this.inputs.attached["pointers"];
  43849. if (pointers)
  43850. return pointers.panningSensibility;
  43851. return 0;
  43852. },
  43853. set: function (value) {
  43854. var pointers = this.inputs.attached["pointers"];
  43855. if (pointers) {
  43856. pointers.panningSensibility = value;
  43857. }
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43863. get: function () {
  43864. var keyboard = this.inputs.attached["keyboard"];
  43865. if (keyboard)
  43866. return keyboard.keysUp;
  43867. return [];
  43868. },
  43869. set: function (value) {
  43870. var keyboard = this.inputs.attached["keyboard"];
  43871. if (keyboard)
  43872. keyboard.keysUp = value;
  43873. },
  43874. enumerable: true,
  43875. configurable: true
  43876. });
  43877. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43878. get: function () {
  43879. var keyboard = this.inputs.attached["keyboard"];
  43880. if (keyboard)
  43881. return keyboard.keysDown;
  43882. return [];
  43883. },
  43884. set: function (value) {
  43885. var keyboard = this.inputs.attached["keyboard"];
  43886. if (keyboard)
  43887. keyboard.keysDown = value;
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43893. get: function () {
  43894. var keyboard = this.inputs.attached["keyboard"];
  43895. if (keyboard)
  43896. return keyboard.keysLeft;
  43897. return [];
  43898. },
  43899. set: function (value) {
  43900. var keyboard = this.inputs.attached["keyboard"];
  43901. if (keyboard)
  43902. keyboard.keysLeft = value;
  43903. },
  43904. enumerable: true,
  43905. configurable: true
  43906. });
  43907. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43908. get: function () {
  43909. var keyboard = this.inputs.attached["keyboard"];
  43910. if (keyboard)
  43911. return keyboard.keysRight;
  43912. return [];
  43913. },
  43914. set: function (value) {
  43915. var keyboard = this.inputs.attached["keyboard"];
  43916. if (keyboard)
  43917. keyboard.keysRight = value;
  43918. },
  43919. enumerable: true,
  43920. configurable: true
  43921. });
  43922. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43923. get: function () {
  43924. var mousewheel = this.inputs.attached["mousewheel"];
  43925. if (mousewheel)
  43926. return mousewheel.wheelPrecision;
  43927. return 0;
  43928. },
  43929. set: function (value) {
  43930. var mousewheel = this.inputs.attached["mousewheel"];
  43931. if (mousewheel)
  43932. mousewheel.wheelPrecision = value;
  43933. },
  43934. enumerable: true,
  43935. configurable: true
  43936. });
  43937. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43938. get: function () {
  43939. var mousewheel = this.inputs.attached["mousewheel"];
  43940. if (mousewheel)
  43941. return mousewheel.wheelDeltaPercentage;
  43942. return 0;
  43943. },
  43944. set: function (value) {
  43945. var mousewheel = this.inputs.attached["mousewheel"];
  43946. if (mousewheel)
  43947. mousewheel.wheelDeltaPercentage = value;
  43948. },
  43949. enumerable: true,
  43950. configurable: true
  43951. });
  43952. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43953. get: function () {
  43954. return this._bouncingBehavior;
  43955. },
  43956. enumerable: true,
  43957. configurable: true
  43958. });
  43959. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43960. get: function () {
  43961. return this._bouncingBehavior != null;
  43962. },
  43963. set: function (value) {
  43964. if (value === this.useBouncingBehavior) {
  43965. return;
  43966. }
  43967. if (value) {
  43968. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43969. this.addBehavior(this._bouncingBehavior);
  43970. }
  43971. else if (this._bouncingBehavior) {
  43972. this.removeBehavior(this._bouncingBehavior);
  43973. this._bouncingBehavior = null;
  43974. }
  43975. },
  43976. enumerable: true,
  43977. configurable: true
  43978. });
  43979. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43980. get: function () {
  43981. return this._framingBehavior;
  43982. },
  43983. enumerable: true,
  43984. configurable: true
  43985. });
  43986. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43987. get: function () {
  43988. return this._framingBehavior != null;
  43989. },
  43990. set: function (value) {
  43991. if (value === this.useFramingBehavior) {
  43992. return;
  43993. }
  43994. if (value) {
  43995. this._framingBehavior = new BABYLON.FramingBehavior();
  43996. this.addBehavior(this._framingBehavior);
  43997. }
  43998. else if (this._framingBehavior) {
  43999. this.removeBehavior(this._framingBehavior);
  44000. this._framingBehavior = null;
  44001. }
  44002. },
  44003. enumerable: true,
  44004. configurable: true
  44005. });
  44006. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44007. get: function () {
  44008. return this._autoRotationBehavior;
  44009. },
  44010. enumerable: true,
  44011. configurable: true
  44012. });
  44013. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44014. get: function () {
  44015. return this._autoRotationBehavior != null;
  44016. },
  44017. set: function (value) {
  44018. if (value === this.useAutoRotationBehavior) {
  44019. return;
  44020. }
  44021. if (value) {
  44022. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44023. this.addBehavior(this._autoRotationBehavior);
  44024. }
  44025. else if (this._autoRotationBehavior) {
  44026. this.removeBehavior(this._autoRotationBehavior);
  44027. this._autoRotationBehavior = null;
  44028. }
  44029. },
  44030. enumerable: true,
  44031. configurable: true
  44032. });
  44033. // Cache
  44034. ArcRotateCamera.prototype._initCache = function () {
  44035. _super.prototype._initCache.call(this);
  44036. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44037. this._cache.alpha = undefined;
  44038. this._cache.beta = undefined;
  44039. this._cache.radius = undefined;
  44040. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44041. };
  44042. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44043. if (!ignoreParentClass) {
  44044. _super.prototype._updateCache.call(this);
  44045. }
  44046. this._cache._target.copyFrom(this._getTargetPosition());
  44047. this._cache.alpha = this.alpha;
  44048. this._cache.beta = this.beta;
  44049. this._cache.radius = this.radius;
  44050. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44051. };
  44052. ArcRotateCamera.prototype._getTargetPosition = function () {
  44053. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44054. var pos = this._targetHost.getAbsolutePosition();
  44055. if (this._targetBoundingCenter) {
  44056. pos.addToRef(this._targetBoundingCenter, this._target);
  44057. }
  44058. else {
  44059. this._target.copyFrom(pos);
  44060. }
  44061. }
  44062. var lockedTargetPosition = this._getLockedTargetPosition();
  44063. if (lockedTargetPosition) {
  44064. return lockedTargetPosition;
  44065. }
  44066. return this._target;
  44067. };
  44068. ArcRotateCamera.prototype.storeState = function () {
  44069. this._storedAlpha = this.alpha;
  44070. this._storedBeta = this.beta;
  44071. this._storedRadius = this.radius;
  44072. this._storedTarget = this._getTargetPosition().clone();
  44073. return _super.prototype.storeState.call(this);
  44074. };
  44075. /**
  44076. * Restored camera state. You must call storeState() first
  44077. */
  44078. ArcRotateCamera.prototype._restoreStateValues = function () {
  44079. if (!_super.prototype._restoreStateValues.call(this)) {
  44080. return false;
  44081. }
  44082. this.alpha = this._storedAlpha;
  44083. this.beta = this._storedBeta;
  44084. this.radius = this._storedRadius;
  44085. this.setTarget(this._storedTarget.clone());
  44086. this.inertialAlphaOffset = 0;
  44087. this.inertialBetaOffset = 0;
  44088. this.inertialRadiusOffset = 0;
  44089. this.inertialPanningX = 0;
  44090. this.inertialPanningY = 0;
  44091. return true;
  44092. };
  44093. // Synchronized
  44094. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44095. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44096. return false;
  44097. return this._cache._target.equals(this._getTargetPosition())
  44098. && this._cache.alpha === this.alpha
  44099. && this._cache.beta === this.beta
  44100. && this._cache.radius === this.radius
  44101. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44102. };
  44103. // Methods
  44104. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44105. var _this = this;
  44106. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44107. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44108. this._useCtrlForPanning = useCtrlForPanning;
  44109. this._panningMouseButton = panningMouseButton;
  44110. this.inputs.attachElement(element, noPreventDefault);
  44111. this._reset = function () {
  44112. _this.inertialAlphaOffset = 0;
  44113. _this.inertialBetaOffset = 0;
  44114. _this.inertialRadiusOffset = 0;
  44115. _this.inertialPanningX = 0;
  44116. _this.inertialPanningY = 0;
  44117. };
  44118. };
  44119. ArcRotateCamera.prototype.detachControl = function (element) {
  44120. this.inputs.detachElement(element);
  44121. if (this._reset) {
  44122. this._reset();
  44123. }
  44124. };
  44125. ArcRotateCamera.prototype._checkInputs = function () {
  44126. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44127. if (this._collisionTriggered) {
  44128. return;
  44129. }
  44130. this.inputs.checkInputs();
  44131. // Inertia
  44132. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44133. if (this.getScene().useRightHandedSystem) {
  44134. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44135. }
  44136. else {
  44137. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44138. }
  44139. this.beta += this.inertialBetaOffset;
  44140. this.radius -= this.inertialRadiusOffset;
  44141. this.inertialAlphaOffset *= this.inertia;
  44142. this.inertialBetaOffset *= this.inertia;
  44143. this.inertialRadiusOffset *= this.inertia;
  44144. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44145. this.inertialAlphaOffset = 0;
  44146. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44147. this.inertialBetaOffset = 0;
  44148. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44149. this.inertialRadiusOffset = 0;
  44150. }
  44151. // Panning inertia
  44152. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44153. if (!this._localDirection) {
  44154. this._localDirection = BABYLON.Vector3.Zero();
  44155. this._transformedDirection = BABYLON.Vector3.Zero();
  44156. }
  44157. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44158. this._localDirection.multiplyInPlace(this.panningAxis);
  44159. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44160. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44161. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44162. if (!this.panningAxis.y) {
  44163. this._transformedDirection.y = 0;
  44164. }
  44165. if (!this._targetHost) {
  44166. if (this.panningDistanceLimit) {
  44167. this._transformedDirection.addInPlace(this._target);
  44168. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44169. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44170. this._target.copyFrom(this._transformedDirection);
  44171. }
  44172. }
  44173. else {
  44174. this._target.addInPlace(this._transformedDirection);
  44175. }
  44176. }
  44177. this.inertialPanningX *= this.panningInertia;
  44178. this.inertialPanningY *= this.panningInertia;
  44179. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44180. this.inertialPanningX = 0;
  44181. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44182. this.inertialPanningY = 0;
  44183. }
  44184. // Limits
  44185. this._checkLimits();
  44186. _super.prototype._checkInputs.call(this);
  44187. };
  44188. ArcRotateCamera.prototype._checkLimits = function () {
  44189. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44190. if (this.allowUpsideDown && this.beta > Math.PI) {
  44191. this.beta = this.beta - (2 * Math.PI);
  44192. }
  44193. }
  44194. else {
  44195. if (this.beta < this.lowerBetaLimit) {
  44196. this.beta = this.lowerBetaLimit;
  44197. }
  44198. }
  44199. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44200. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44201. this.beta = this.beta + (2 * Math.PI);
  44202. }
  44203. }
  44204. else {
  44205. if (this.beta > this.upperBetaLimit) {
  44206. this.beta = this.upperBetaLimit;
  44207. }
  44208. }
  44209. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44210. this.alpha = this.lowerAlphaLimit;
  44211. }
  44212. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44213. this.alpha = this.upperAlphaLimit;
  44214. }
  44215. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44216. this.radius = this.lowerRadiusLimit;
  44217. }
  44218. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44219. this.radius = this.upperRadiusLimit;
  44220. }
  44221. };
  44222. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44223. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44224. this.radius = radiusv3.length();
  44225. if (this.radius === 0) {
  44226. this.radius = 0.0001; // Just to avoid division by zero
  44227. }
  44228. // Alpha
  44229. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44230. if (radiusv3.z < 0) {
  44231. this.alpha = 2 * Math.PI - this.alpha;
  44232. }
  44233. // Beta
  44234. this.beta = Math.acos(radiusv3.y / this.radius);
  44235. this._checkLimits();
  44236. };
  44237. ArcRotateCamera.prototype.setPosition = function (position) {
  44238. if (this.position.equals(position)) {
  44239. return;
  44240. }
  44241. this.position.copyFrom(position);
  44242. this.rebuildAnglesAndRadius();
  44243. };
  44244. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44245. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44246. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44247. if (target.getBoundingInfo) {
  44248. if (toBoundingCenter) {
  44249. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44250. }
  44251. else {
  44252. this._targetBoundingCenter = null;
  44253. }
  44254. this._targetHost = target;
  44255. this._target = this._getTargetPosition();
  44256. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44257. }
  44258. else {
  44259. var newTarget = target;
  44260. var currentTarget = this._getTargetPosition();
  44261. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44262. return;
  44263. }
  44264. this._targetHost = null;
  44265. this._target = newTarget;
  44266. this._targetBoundingCenter = null;
  44267. this.onMeshTargetChangedObservable.notifyObservers(null);
  44268. }
  44269. this.rebuildAnglesAndRadius();
  44270. };
  44271. ArcRotateCamera.prototype._getViewMatrix = function () {
  44272. // Compute
  44273. var cosa = Math.cos(this.alpha);
  44274. var sina = Math.sin(this.alpha);
  44275. var cosb = Math.cos(this.beta);
  44276. var sinb = Math.sin(this.beta);
  44277. if (sinb === 0) {
  44278. sinb = 0.0001;
  44279. }
  44280. var target = this._getTargetPosition();
  44281. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44282. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44283. if (!this._collider) {
  44284. this._collider = new BABYLON.Collider();
  44285. }
  44286. this._collider._radius = this.collisionRadius;
  44287. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44288. this._collisionTriggered = true;
  44289. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44290. }
  44291. else {
  44292. this.position.copyFrom(this._newPosition);
  44293. var up = this.upVector;
  44294. if (this.allowUpsideDown && sinb < 0) {
  44295. up = up.clone();
  44296. up = up.negate();
  44297. }
  44298. if (this.getScene().useRightHandedSystem) {
  44299. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44300. }
  44301. else {
  44302. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44303. }
  44304. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44305. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44306. }
  44307. this._currentTarget = target;
  44308. return this._viewMatrix;
  44309. };
  44310. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44311. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44312. meshes = meshes || this.getScene().meshes;
  44313. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44314. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44315. this.radius = distance * this.zoomOnFactor;
  44316. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44317. };
  44318. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44319. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44320. var meshesOrMinMaxVector;
  44321. var distance;
  44322. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44323. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44324. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44325. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44326. }
  44327. else {
  44328. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44329. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44330. distance = minMaxVectorAndDistance.distance;
  44331. }
  44332. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44333. if (!doNotUpdateMaxZ) {
  44334. this.maxZ = distance * 2;
  44335. }
  44336. };
  44337. /**
  44338. * @override
  44339. * Override Camera.createRigCamera
  44340. */
  44341. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44342. var alphaShift = 0;
  44343. switch (this.cameraRigMode) {
  44344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44347. case BABYLON.Camera.RIG_MODE_VR:
  44348. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44349. break;
  44350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44351. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44352. break;
  44353. }
  44354. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44355. rigCam._cameraRigParams = {};
  44356. return rigCam;
  44357. };
  44358. /**
  44359. * @override
  44360. * Override Camera._updateRigCameras
  44361. */
  44362. ArcRotateCamera.prototype._updateRigCameras = function () {
  44363. var camLeft = this._rigCameras[0];
  44364. var camRight = this._rigCameras[1];
  44365. camLeft.beta = camRight.beta = this.beta;
  44366. camLeft.radius = camRight.radius = this.radius;
  44367. switch (this.cameraRigMode) {
  44368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44369. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44370. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44371. case BABYLON.Camera.RIG_MODE_VR:
  44372. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44373. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44374. break;
  44375. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44376. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44377. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44378. break;
  44379. }
  44380. _super.prototype._updateRigCameras.call(this);
  44381. };
  44382. ArcRotateCamera.prototype.dispose = function () {
  44383. this.inputs.clear();
  44384. _super.prototype.dispose.call(this);
  44385. };
  44386. ArcRotateCamera.prototype.getClassName = function () {
  44387. return "ArcRotateCamera";
  44388. };
  44389. __decorate([
  44390. BABYLON.serialize()
  44391. ], ArcRotateCamera.prototype, "alpha", void 0);
  44392. __decorate([
  44393. BABYLON.serialize()
  44394. ], ArcRotateCamera.prototype, "beta", void 0);
  44395. __decorate([
  44396. BABYLON.serialize()
  44397. ], ArcRotateCamera.prototype, "radius", void 0);
  44398. __decorate([
  44399. BABYLON.serializeAsVector3("target")
  44400. ], ArcRotateCamera.prototype, "_target", void 0);
  44401. __decorate([
  44402. BABYLON.serialize()
  44403. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44404. __decorate([
  44405. BABYLON.serialize()
  44406. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44407. __decorate([
  44408. BABYLON.serialize()
  44409. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44410. __decorate([
  44411. BABYLON.serialize()
  44412. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44413. __decorate([
  44414. BABYLON.serialize()
  44415. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44416. __decorate([
  44417. BABYLON.serialize()
  44418. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44419. __decorate([
  44420. BABYLON.serialize()
  44421. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44422. __decorate([
  44423. BABYLON.serialize()
  44424. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44425. __decorate([
  44426. BABYLON.serialize()
  44427. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44428. __decorate([
  44429. BABYLON.serialize()
  44430. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44431. __decorate([
  44432. BABYLON.serialize()
  44433. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44434. __decorate([
  44435. BABYLON.serialize()
  44436. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44437. __decorate([
  44438. BABYLON.serialize()
  44439. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44440. __decorate([
  44441. BABYLON.serializeAsVector3()
  44442. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44443. __decorate([
  44444. BABYLON.serialize()
  44445. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44446. __decorate([
  44447. BABYLON.serialize()
  44448. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44449. __decorate([
  44450. BABYLON.serialize()
  44451. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44452. return ArcRotateCamera;
  44453. }(BABYLON.TargetCamera));
  44454. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44455. })(BABYLON || (BABYLON = {}));
  44456. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44457. var BABYLON;
  44458. (function (BABYLON) {
  44459. /**
  44460. * The HemisphericLight simulates the ambient environment light,
  44461. * so the passed direction is the light reflection direction, not the incoming direction.
  44462. */
  44463. var HemisphericLight = /** @class */ (function (_super) {
  44464. __extends(HemisphericLight, _super);
  44465. /**
  44466. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44467. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44468. * The HemisphericLight can't cast shadows.
  44469. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44470. * @param name The friendly name of the light
  44471. * @param direction The direction of the light reflection
  44472. * @param scene The scene the light belongs to
  44473. */
  44474. function HemisphericLight(name, direction, scene) {
  44475. var _this = _super.call(this, name, scene) || this;
  44476. /**
  44477. * The groundColor is the light in the opposite direction to the one specified during creation.
  44478. * 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.
  44479. */
  44480. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44481. _this.direction = direction || BABYLON.Vector3.Up();
  44482. return _this;
  44483. }
  44484. HemisphericLight.prototype._buildUniformLayout = function () {
  44485. this._uniformBuffer.addUniform("vLightData", 4);
  44486. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44487. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44488. this._uniformBuffer.addUniform("vLightGround", 3);
  44489. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44490. this._uniformBuffer.addUniform("depthValues", 2);
  44491. this._uniformBuffer.create();
  44492. };
  44493. /**
  44494. * Returns the string "HemisphericLight".
  44495. * @return The class name
  44496. */
  44497. HemisphericLight.prototype.getClassName = function () {
  44498. return "HemisphericLight";
  44499. };
  44500. /**
  44501. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44502. * Returns the updated direction.
  44503. * @param target The target the direction should point to
  44504. * @return The computed direction
  44505. */
  44506. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44507. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44508. return this.direction;
  44509. };
  44510. /**
  44511. * Returns the shadow generator associated to the light.
  44512. * @returns Always null for hemispheric lights because it does not support shadows.
  44513. */
  44514. HemisphericLight.prototype.getShadowGenerator = function () {
  44515. return null;
  44516. };
  44517. /**
  44518. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44519. * @param effect The effect to update
  44520. * @param lightIndex The index of the light in the effect to update
  44521. * @returns The hemispheric light
  44522. */
  44523. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44524. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44525. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44526. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44527. return this;
  44528. };
  44529. /**
  44530. * @ignore internal use only.
  44531. */
  44532. HemisphericLight.prototype._getWorldMatrix = function () {
  44533. if (!this._worldMatrix) {
  44534. this._worldMatrix = BABYLON.Matrix.Identity();
  44535. }
  44536. return this._worldMatrix;
  44537. };
  44538. /**
  44539. * Returns the integer 3.
  44540. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44541. */
  44542. HemisphericLight.prototype.getTypeID = function () {
  44543. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44544. };
  44545. __decorate([
  44546. BABYLON.serializeAsColor3()
  44547. ], HemisphericLight.prototype, "groundColor", void 0);
  44548. __decorate([
  44549. BABYLON.serializeAsVector3()
  44550. ], HemisphericLight.prototype, "direction", void 0);
  44551. return HemisphericLight;
  44552. }(BABYLON.Light));
  44553. BABYLON.HemisphericLight = HemisphericLight;
  44554. })(BABYLON || (BABYLON = {}));
  44555. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44556. var BABYLON;
  44557. (function (BABYLON) {
  44558. /**
  44559. * Base implementation of @see IShadowLight
  44560. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44561. */
  44562. var ShadowLight = /** @class */ (function (_super) {
  44563. __extends(ShadowLight, _super);
  44564. function ShadowLight() {
  44565. var _this = _super !== null && _super.apply(this, arguments) || this;
  44566. _this._needProjectionMatrixCompute = true;
  44567. return _this;
  44568. }
  44569. ShadowLight.prototype._setPosition = function (value) {
  44570. this._position = value;
  44571. };
  44572. Object.defineProperty(ShadowLight.prototype, "position", {
  44573. /**
  44574. * Sets the position the shadow will be casted from. Also use as the light position for both
  44575. * point and spot lights.
  44576. */
  44577. get: function () {
  44578. return this._position;
  44579. },
  44580. /**
  44581. * Sets the position the shadow will be casted from. Also use as the light position for both
  44582. * point and spot lights.
  44583. */
  44584. set: function (value) {
  44585. this._setPosition(value);
  44586. },
  44587. enumerable: true,
  44588. configurable: true
  44589. });
  44590. ShadowLight.prototype._setDirection = function (value) {
  44591. this._direction = value;
  44592. };
  44593. Object.defineProperty(ShadowLight.prototype, "direction", {
  44594. /**
  44595. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44596. * Also use as the light direction on spot and directional lights.
  44597. */
  44598. get: function () {
  44599. return this._direction;
  44600. },
  44601. /**
  44602. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44603. * Also use as the light direction on spot and directional lights.
  44604. */
  44605. set: function (value) {
  44606. this._setDirection(value);
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44612. /**
  44613. * Gets the shadow projection clipping minimum z value.
  44614. */
  44615. get: function () {
  44616. return this._shadowMinZ;
  44617. },
  44618. /**
  44619. * Sets the shadow projection clipping minimum z value.
  44620. */
  44621. set: function (value) {
  44622. this._shadowMinZ = value;
  44623. this.forceProjectionMatrixCompute();
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44629. /**
  44630. * Sets the shadow projection clipping maximum z value.
  44631. */
  44632. get: function () {
  44633. return this._shadowMaxZ;
  44634. },
  44635. /**
  44636. * Gets the shadow projection clipping maximum z value.
  44637. */
  44638. set: function (value) {
  44639. this._shadowMaxZ = value;
  44640. this.forceProjectionMatrixCompute();
  44641. },
  44642. enumerable: true,
  44643. configurable: true
  44644. });
  44645. /**
  44646. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44647. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44648. */
  44649. ShadowLight.prototype.computeTransformedInformation = function () {
  44650. if (this.parent && this.parent.getWorldMatrix) {
  44651. if (!this.transformedPosition) {
  44652. this.transformedPosition = BABYLON.Vector3.Zero();
  44653. }
  44654. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44655. // In case the direction is present.
  44656. if (this.direction) {
  44657. if (!this.transformedDirection) {
  44658. this.transformedDirection = BABYLON.Vector3.Zero();
  44659. }
  44660. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44661. }
  44662. return true;
  44663. }
  44664. return false;
  44665. };
  44666. /**
  44667. * Return the depth scale used for the shadow map.
  44668. * @returns the depth scale.
  44669. */
  44670. ShadowLight.prototype.getDepthScale = function () {
  44671. return 50.0;
  44672. };
  44673. /**
  44674. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44675. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44676. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44677. */
  44678. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44679. return this.transformedDirection ? this.transformedDirection : this.direction;
  44680. };
  44681. /**
  44682. * Returns the ShadowLight absolute position in the World.
  44683. * @returns the position vector in world space
  44684. */
  44685. ShadowLight.prototype.getAbsolutePosition = function () {
  44686. return this.transformedPosition ? this.transformedPosition : this.position;
  44687. };
  44688. /**
  44689. * Sets the ShadowLight direction toward the passed target.
  44690. * @param target The point tot target in local space
  44691. * @returns the updated ShadowLight direction
  44692. */
  44693. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44694. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44695. return this.direction;
  44696. };
  44697. /**
  44698. * Returns the light rotation in euler definition.
  44699. * @returns the x y z rotation in local space.
  44700. */
  44701. ShadowLight.prototype.getRotation = function () {
  44702. this.direction.normalize();
  44703. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44704. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44705. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44706. };
  44707. /**
  44708. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44709. * @returns true if a cube texture needs to be use
  44710. */
  44711. ShadowLight.prototype.needCube = function () {
  44712. return false;
  44713. };
  44714. /**
  44715. * Detects if the projection matrix requires to be recomputed this frame.
  44716. * @returns true if it requires to be recomputed otherwise, false.
  44717. */
  44718. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44719. return this._needProjectionMatrixCompute;
  44720. };
  44721. /**
  44722. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44723. */
  44724. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44725. this._needProjectionMatrixCompute = true;
  44726. };
  44727. /**
  44728. * Get the world matrix of the sahdow lights.
  44729. * @ignore Internal Use Only
  44730. */
  44731. ShadowLight.prototype._getWorldMatrix = function () {
  44732. if (!this._worldMatrix) {
  44733. this._worldMatrix = BABYLON.Matrix.Identity();
  44734. }
  44735. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44736. return this._worldMatrix;
  44737. };
  44738. /**
  44739. * Gets the minZ used for shadow according to both the scene and the light.
  44740. * @param activeCamera The camera we are returning the min for
  44741. * @returns the depth min z
  44742. */
  44743. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44744. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44745. };
  44746. /**
  44747. * Gets the maxZ used for shadow according to both the scene and the light.
  44748. * @param activeCamera The camera we are returning the max for
  44749. * @returns the depth max z
  44750. */
  44751. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44752. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44753. };
  44754. /**
  44755. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44756. * @param matrix The materix to updated with the projection information
  44757. * @param viewMatrix The transform matrix of the light
  44758. * @param renderList The list of mesh to render in the map
  44759. * @returns The current light
  44760. */
  44761. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44762. if (this.customProjectionMatrixBuilder) {
  44763. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44764. }
  44765. else {
  44766. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44767. }
  44768. return this;
  44769. };
  44770. __decorate([
  44771. BABYLON.serializeAsVector3()
  44772. ], ShadowLight.prototype, "position", null);
  44773. __decorate([
  44774. BABYLON.serializeAsVector3()
  44775. ], ShadowLight.prototype, "direction", null);
  44776. __decorate([
  44777. BABYLON.serialize()
  44778. ], ShadowLight.prototype, "shadowMinZ", null);
  44779. __decorate([
  44780. BABYLON.serialize()
  44781. ], ShadowLight.prototype, "shadowMaxZ", null);
  44782. return ShadowLight;
  44783. }(BABYLON.Light));
  44784. BABYLON.ShadowLight = ShadowLight;
  44785. })(BABYLON || (BABYLON = {}));
  44786. //# sourceMappingURL=babylon.shadowLight.js.map
  44787. var BABYLON;
  44788. (function (BABYLON) {
  44789. /**
  44790. * A point light is a light defined by an unique point in world space.
  44791. * The light is emitted in every direction from this point.
  44792. * A good example of a point light is a standard light bulb.
  44793. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44794. */
  44795. var PointLight = /** @class */ (function (_super) {
  44796. __extends(PointLight, _super);
  44797. /**
  44798. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44799. * A PointLight emits the light in every direction.
  44800. * It can cast shadows.
  44801. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44802. * ```javascript
  44803. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44804. * ```
  44805. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44806. * @param name The light friendly name
  44807. * @param position The position of the point light in the scene
  44808. * @param scene The scene the lights belongs to
  44809. */
  44810. function PointLight(name, position, scene) {
  44811. var _this = _super.call(this, name, scene) || this;
  44812. _this._shadowAngle = Math.PI / 2;
  44813. _this.position = position;
  44814. return _this;
  44815. }
  44816. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44817. /**
  44818. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44819. * This specifies what angle the shadow will use to be created.
  44820. *
  44821. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44822. */
  44823. get: function () {
  44824. return this._shadowAngle;
  44825. },
  44826. /**
  44827. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44828. * This specifies what angle the shadow will use to be created.
  44829. *
  44830. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44831. */
  44832. set: function (value) {
  44833. this._shadowAngle = value;
  44834. this.forceProjectionMatrixCompute();
  44835. },
  44836. enumerable: true,
  44837. configurable: true
  44838. });
  44839. Object.defineProperty(PointLight.prototype, "direction", {
  44840. /**
  44841. * Gets the direction if it has been set.
  44842. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44843. */
  44844. get: function () {
  44845. return this._direction;
  44846. },
  44847. /**
  44848. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44849. */
  44850. set: function (value) {
  44851. var previousNeedCube = this.needCube();
  44852. this._direction = value;
  44853. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44854. this._shadowGenerator.recreateShadowMap();
  44855. }
  44856. },
  44857. enumerable: true,
  44858. configurable: true
  44859. });
  44860. /**
  44861. * Returns the string "PointLight"
  44862. * @returns the class name
  44863. */
  44864. PointLight.prototype.getClassName = function () {
  44865. return "PointLight";
  44866. };
  44867. /**
  44868. * Returns the integer 0.
  44869. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44870. */
  44871. PointLight.prototype.getTypeID = function () {
  44872. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44873. };
  44874. /**
  44875. * Specifies wether or not the shadowmap should be a cube texture.
  44876. * @returns true if the shadowmap needs to be a cube texture.
  44877. */
  44878. PointLight.prototype.needCube = function () {
  44879. return !this.direction;
  44880. };
  44881. /**
  44882. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44883. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44884. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44885. */
  44886. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44887. if (this.direction) {
  44888. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44889. }
  44890. else {
  44891. switch (faceIndex) {
  44892. case 0:
  44893. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44894. case 1:
  44895. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44896. case 2:
  44897. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44898. case 3:
  44899. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44900. case 4:
  44901. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44902. case 5:
  44903. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44904. }
  44905. }
  44906. return BABYLON.Vector3.Zero();
  44907. };
  44908. /**
  44909. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44910. * - fov = PI / 2
  44911. * - aspect ratio : 1.0
  44912. * - z-near and far equal to the active camera minZ and maxZ.
  44913. * Returns the PointLight.
  44914. */
  44915. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44916. var activeCamera = this.getScene().activeCamera;
  44917. if (!activeCamera) {
  44918. return;
  44919. }
  44920. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44921. };
  44922. PointLight.prototype._buildUniformLayout = function () {
  44923. this._uniformBuffer.addUniform("vLightData", 4);
  44924. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44925. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44926. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44927. this._uniformBuffer.addUniform("depthValues", 2);
  44928. this._uniformBuffer.create();
  44929. };
  44930. /**
  44931. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44932. * @param effect The effect to update
  44933. * @param lightIndex The index of the light in the effect to update
  44934. * @returns The point light
  44935. */
  44936. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44937. if (this.computeTransformedInformation()) {
  44938. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44939. return this;
  44940. }
  44941. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44942. return this;
  44943. };
  44944. __decorate([
  44945. BABYLON.serialize()
  44946. ], PointLight.prototype, "shadowAngle", null);
  44947. return PointLight;
  44948. }(BABYLON.ShadowLight));
  44949. BABYLON.PointLight = PointLight;
  44950. })(BABYLON || (BABYLON = {}));
  44951. //# sourceMappingURL=babylon.pointLight.js.map
  44952. var BABYLON;
  44953. (function (BABYLON) {
  44954. /**
  44955. * A directional light is defined by a direction (what a surprise!).
  44956. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44957. * 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.
  44958. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44959. */
  44960. var DirectionalLight = /** @class */ (function (_super) {
  44961. __extends(DirectionalLight, _super);
  44962. /**
  44963. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44964. * The directional light is emitted from everywhere in the given direction.
  44965. * It can cast shawdows.
  44966. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44967. * @param name The friendly name of the light
  44968. * @param direction The direction of the light
  44969. * @param scene The scene the light belongs to
  44970. */
  44971. function DirectionalLight(name, direction, scene) {
  44972. var _this = _super.call(this, name, scene) || this;
  44973. _this._shadowFrustumSize = 0;
  44974. _this._shadowOrthoScale = 0.5;
  44975. /**
  44976. * Automatically compute the projection matrix to best fit (including all the casters)
  44977. * on each frame.
  44978. */
  44979. _this.autoUpdateExtends = true;
  44980. // Cache
  44981. _this._orthoLeft = Number.MAX_VALUE;
  44982. _this._orthoRight = Number.MIN_VALUE;
  44983. _this._orthoTop = Number.MIN_VALUE;
  44984. _this._orthoBottom = Number.MAX_VALUE;
  44985. _this.position = direction.scale(-1.0);
  44986. _this.direction = direction;
  44987. return _this;
  44988. }
  44989. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44990. /**
  44991. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44992. */
  44993. get: function () {
  44994. return this._shadowFrustumSize;
  44995. },
  44996. /**
  44997. * Specifies a fix frustum size for the shadow generation.
  44998. */
  44999. set: function (value) {
  45000. this._shadowFrustumSize = value;
  45001. this.forceProjectionMatrixCompute();
  45002. },
  45003. enumerable: true,
  45004. configurable: true
  45005. });
  45006. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45007. /**
  45008. * Gets the shadow projection scale against the optimal computed one.
  45009. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45010. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45011. */
  45012. get: function () {
  45013. return this._shadowOrthoScale;
  45014. },
  45015. /**
  45016. * Sets the shadow projection scale against the optimal computed one.
  45017. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45018. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45019. */
  45020. set: function (value) {
  45021. this._shadowOrthoScale = value;
  45022. this.forceProjectionMatrixCompute();
  45023. },
  45024. enumerable: true,
  45025. configurable: true
  45026. });
  45027. /**
  45028. * Returns the string "DirectionalLight".
  45029. * @return The class name
  45030. */
  45031. DirectionalLight.prototype.getClassName = function () {
  45032. return "DirectionalLight";
  45033. };
  45034. /**
  45035. * Returns the integer 1.
  45036. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45037. */
  45038. DirectionalLight.prototype.getTypeID = function () {
  45039. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45040. };
  45041. /**
  45042. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45043. * Returns the DirectionalLight Shadow projection matrix.
  45044. */
  45045. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45046. if (this.shadowFrustumSize > 0) {
  45047. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45048. }
  45049. else {
  45050. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45051. }
  45052. };
  45053. /**
  45054. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45055. * Returns the DirectionalLight Shadow projection matrix.
  45056. */
  45057. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45058. var activeCamera = this.getScene().activeCamera;
  45059. if (!activeCamera) {
  45060. return;
  45061. }
  45062. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45063. };
  45064. /**
  45065. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45066. * Returns the DirectionalLight Shadow projection matrix.
  45067. */
  45068. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45069. var activeCamera = this.getScene().activeCamera;
  45070. if (!activeCamera) {
  45071. return;
  45072. }
  45073. // Check extends
  45074. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45075. var tempVector3 = BABYLON.Vector3.Zero();
  45076. this._orthoLeft = Number.MAX_VALUE;
  45077. this._orthoRight = Number.MIN_VALUE;
  45078. this._orthoTop = Number.MIN_VALUE;
  45079. this._orthoBottom = Number.MAX_VALUE;
  45080. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45081. var mesh = renderList[meshIndex];
  45082. if (!mesh) {
  45083. continue;
  45084. }
  45085. var boundingInfo = mesh.getBoundingInfo();
  45086. var boundingBox = boundingInfo.boundingBox;
  45087. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45088. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45089. if (tempVector3.x < this._orthoLeft)
  45090. this._orthoLeft = tempVector3.x;
  45091. if (tempVector3.y < this._orthoBottom)
  45092. this._orthoBottom = tempVector3.y;
  45093. if (tempVector3.x > this._orthoRight)
  45094. this._orthoRight = tempVector3.x;
  45095. if (tempVector3.y > this._orthoTop)
  45096. this._orthoTop = tempVector3.y;
  45097. }
  45098. }
  45099. }
  45100. var xOffset = this._orthoRight - this._orthoLeft;
  45101. var yOffset = this._orthoTop - this._orthoBottom;
  45102. 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);
  45103. };
  45104. DirectionalLight.prototype._buildUniformLayout = function () {
  45105. this._uniformBuffer.addUniform("vLightData", 4);
  45106. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45107. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45109. this._uniformBuffer.addUniform("depthValues", 2);
  45110. this._uniformBuffer.create();
  45111. };
  45112. /**
  45113. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45114. * @param effect The effect to update
  45115. * @param lightIndex The index of the light in the effect to update
  45116. * @returns The directional light
  45117. */
  45118. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45119. if (this.computeTransformedInformation()) {
  45120. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45121. return this;
  45122. }
  45123. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45124. return this;
  45125. };
  45126. /**
  45127. * Gets the minZ used for shadow according to both the scene and the light.
  45128. *
  45129. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45130. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45131. * @param activeCamera The camera we are returning the min for
  45132. * @returns the depth min z
  45133. */
  45134. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45135. return 1;
  45136. };
  45137. /**
  45138. * Gets the maxZ used for shadow according to both the scene and the light.
  45139. *
  45140. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45141. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45142. * @param activeCamera The camera we are returning the max for
  45143. * @returns the depth max z
  45144. */
  45145. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45146. return 1;
  45147. };
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45151. __decorate([
  45152. BABYLON.serialize()
  45153. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45154. __decorate([
  45155. BABYLON.serialize()
  45156. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45157. return DirectionalLight;
  45158. }(BABYLON.ShadowLight));
  45159. BABYLON.DirectionalLight = DirectionalLight;
  45160. })(BABYLON || (BABYLON = {}));
  45161. //# sourceMappingURL=babylon.directionalLight.js.map
  45162. var BABYLON;
  45163. (function (BABYLON) {
  45164. /**
  45165. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45166. * These values define a cone of light starting from the position, emitting toward the direction.
  45167. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45168. * and the exponent defines the speed of the decay of the light with distance (reach).
  45169. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45170. */
  45171. var SpotLight = /** @class */ (function (_super) {
  45172. __extends(SpotLight, _super);
  45173. /**
  45174. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45175. * It can cast shadows.
  45176. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45177. * @param name The light friendly name
  45178. * @param position The position of the spot light in the scene
  45179. * @param direction The direction of the light in the scene
  45180. * @param angle The cone angle of the light in Radians
  45181. * @param exponent The light decay speed with the distance from the emission spot
  45182. * @param scene The scene the lights belongs to
  45183. */
  45184. function SpotLight(name, position, direction, angle, exponent, scene) {
  45185. var _this = _super.call(this, name, scene) || this;
  45186. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45187. _this._projectionTextureLightNear = 1e-6;
  45188. _this._projectionTextureLightFar = 1000.0;
  45189. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45190. _this._projectionTextureViewLightDirty = true;
  45191. _this._projectionTextureProjectionLightDirty = true;
  45192. _this._projectionTextureDirty = true;
  45193. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45194. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45195. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45196. _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);
  45197. _this.position = position;
  45198. _this.direction = direction;
  45199. _this.angle = angle;
  45200. _this.exponent = exponent;
  45201. return _this;
  45202. }
  45203. Object.defineProperty(SpotLight.prototype, "angle", {
  45204. /**
  45205. * Gets the cone angle of the spot light in Radians.
  45206. */
  45207. get: function () {
  45208. return this._angle;
  45209. },
  45210. /**
  45211. * Sets the cone angle of the spot light in Radians.
  45212. */
  45213. set: function (value) {
  45214. this._angle = value;
  45215. this._projectionTextureProjectionLightDirty = true;
  45216. this.forceProjectionMatrixCompute();
  45217. },
  45218. enumerable: true,
  45219. configurable: true
  45220. });
  45221. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45222. /**
  45223. * Allows scaling the angle of the light for shadow generation only.
  45224. */
  45225. get: function () {
  45226. return this._shadowAngleScale;
  45227. },
  45228. /**
  45229. * Allows scaling the angle of the light for shadow generation only.
  45230. */
  45231. set: function (value) {
  45232. this._shadowAngleScale = value;
  45233. this.forceProjectionMatrixCompute();
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45239. /**
  45240. * Allows reading the projecton texture
  45241. */
  45242. get: function () {
  45243. return this._projectionTextureMatrix;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. ;
  45249. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45250. /**
  45251. * Gets the near clip of the Spotlight for texture projection.
  45252. */
  45253. get: function () {
  45254. return this._projectionTextureLightNear;
  45255. },
  45256. /**
  45257. * Sets the near clip of the Spotlight for texture projection.
  45258. */
  45259. set: function (value) {
  45260. this._projectionTextureLightNear = value;
  45261. this._projectionTextureProjectionLightDirty = true;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45267. /**
  45268. * Gets the far clip of the Spotlight for texture projection.
  45269. */
  45270. get: function () {
  45271. return this._projectionTextureLightFar;
  45272. },
  45273. /**
  45274. * Sets the far clip of the Spotlight for texture projection.
  45275. */
  45276. set: function (value) {
  45277. this._projectionTextureLightFar = value;
  45278. this._projectionTextureProjectionLightDirty = true;
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45284. /**
  45285. * Gets the Up vector of the Spotlight for texture projection.
  45286. */
  45287. get: function () {
  45288. return this._projectionTextureUpDirection;
  45289. },
  45290. /**
  45291. * Sets the Up vector of the Spotlight for texture projection.
  45292. */
  45293. set: function (value) {
  45294. this._projectionTextureUpDirection = value;
  45295. this._projectionTextureProjectionLightDirty = true;
  45296. },
  45297. enumerable: true,
  45298. configurable: true
  45299. });
  45300. ;
  45301. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45302. /**
  45303. * Gets the projection texture of the light.
  45304. */
  45305. get: function () {
  45306. return this._projectionTexture;
  45307. },
  45308. /**
  45309. * Sets the projection texture of the light.
  45310. */
  45311. set: function (value) {
  45312. this._projectionTexture = value;
  45313. this._projectionTextureDirty = true;
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. /**
  45319. * Returns the string "SpotLight".
  45320. * @returns the class name
  45321. */
  45322. SpotLight.prototype.getClassName = function () {
  45323. return "SpotLight";
  45324. };
  45325. /**
  45326. * Returns the integer 2.
  45327. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45328. */
  45329. SpotLight.prototype.getTypeID = function () {
  45330. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45331. };
  45332. /**
  45333. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45334. */
  45335. SpotLight.prototype._setDirection = function (value) {
  45336. _super.prototype._setDirection.call(this, value);
  45337. this._projectionTextureViewLightDirty = true;
  45338. };
  45339. /**
  45340. * Overrides the position setter to recompute the projection texture view light Matrix.
  45341. */
  45342. SpotLight.prototype._setPosition = function (value) {
  45343. _super.prototype._setPosition.call(this, value);
  45344. this._projectionTextureViewLightDirty = true;
  45345. };
  45346. /**
  45347. * 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.
  45348. * Returns the SpotLight.
  45349. */
  45350. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45351. var activeCamera = this.getScene().activeCamera;
  45352. if (!activeCamera) {
  45353. return;
  45354. }
  45355. this._shadowAngleScale = this._shadowAngleScale || 1;
  45356. var angle = this._shadowAngleScale * this._angle;
  45357. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45358. };
  45359. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45360. this._projectionTextureViewLightDirty = false;
  45361. this._projectionTextureDirty = true;
  45362. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45363. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45364. };
  45365. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45366. this._projectionTextureProjectionLightDirty = false;
  45367. this._projectionTextureDirty = true;
  45368. var light_far = this.projectionTextureLightFar;
  45369. var light_near = this.projectionTextureLightNear;
  45370. var P = light_far / (light_far - light_near);
  45371. var Q = -P * light_near;
  45372. var S = 1.0 / Math.tan(this._angle / 2.0);
  45373. var A = 1.0;
  45374. 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);
  45375. };
  45376. /**
  45377. * Main function for light texture projection matrix computing.
  45378. */
  45379. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45380. this._projectionTextureDirty = false;
  45381. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45382. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45383. };
  45384. SpotLight.prototype._buildUniformLayout = function () {
  45385. this._uniformBuffer.addUniform("vLightData", 4);
  45386. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45387. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45388. this._uniformBuffer.addUniform("vLightDirection", 3);
  45389. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45390. this._uniformBuffer.addUniform("depthValues", 2);
  45391. this._uniformBuffer.create();
  45392. };
  45393. /**
  45394. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45395. * @param effect The effect to update
  45396. * @param lightIndex The index of the light in the effect to update
  45397. * @returns The spot light
  45398. */
  45399. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45400. var normalizeDirection;
  45401. if (this.computeTransformedInformation()) {
  45402. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45403. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45404. }
  45405. else {
  45406. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45407. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45408. }
  45409. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45410. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45411. if (this._projectionTextureViewLightDirty) {
  45412. this._computeProjectionTextureViewLightMatrix();
  45413. }
  45414. if (this._projectionTextureProjectionLightDirty) {
  45415. this._computeProjectionTextureProjectionLightMatrix();
  45416. }
  45417. if (this._projectionTextureDirty) {
  45418. this._computeProjectionTextureMatrix();
  45419. }
  45420. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45421. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45422. }
  45423. return this;
  45424. };
  45425. /**
  45426. * Disposes the light and the associated resources.
  45427. */
  45428. SpotLight.prototype.dispose = function () {
  45429. _super.prototype.dispose.call(this);
  45430. if (this._projectionTexture) {
  45431. this._projectionTexture.dispose();
  45432. }
  45433. };
  45434. __decorate([
  45435. BABYLON.serialize()
  45436. ], SpotLight.prototype, "angle", null);
  45437. __decorate([
  45438. BABYLON.serialize()
  45439. ], SpotLight.prototype, "shadowAngleScale", null);
  45440. __decorate([
  45441. BABYLON.serialize()
  45442. ], SpotLight.prototype, "exponent", void 0);
  45443. __decorate([
  45444. BABYLON.serialize()
  45445. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45446. __decorate([
  45447. BABYLON.serialize()
  45448. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45449. __decorate([
  45450. BABYLON.serialize()
  45451. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45452. __decorate([
  45453. BABYLON.serializeAsTexture("projectedLightTexture")
  45454. ], SpotLight.prototype, "_projectionTexture", void 0);
  45455. return SpotLight;
  45456. }(BABYLON.ShadowLight));
  45457. BABYLON.SpotLight = SpotLight;
  45458. })(BABYLON || (BABYLON = {}));
  45459. //# sourceMappingURL=babylon.spotLight.js.map
  45460. var BABYLON;
  45461. (function (BABYLON) {
  45462. var AnimationRange = /** @class */ (function () {
  45463. function AnimationRange(name, from, to) {
  45464. this.name = name;
  45465. this.from = from;
  45466. this.to = to;
  45467. }
  45468. AnimationRange.prototype.clone = function () {
  45469. return new AnimationRange(this.name, this.from, this.to);
  45470. };
  45471. return AnimationRange;
  45472. }());
  45473. BABYLON.AnimationRange = AnimationRange;
  45474. /**
  45475. * Composed of a frame, and an action function
  45476. */
  45477. var AnimationEvent = /** @class */ (function () {
  45478. function AnimationEvent(frame, action, onlyOnce) {
  45479. this.frame = frame;
  45480. this.action = action;
  45481. this.onlyOnce = onlyOnce;
  45482. this.isDone = false;
  45483. }
  45484. return AnimationEvent;
  45485. }());
  45486. BABYLON.AnimationEvent = AnimationEvent;
  45487. var PathCursor = /** @class */ (function () {
  45488. function PathCursor(path) {
  45489. this.path = path;
  45490. this._onchange = new Array();
  45491. this.value = 0;
  45492. this.animations = new Array();
  45493. }
  45494. PathCursor.prototype.getPoint = function () {
  45495. var point = this.path.getPointAtLengthPosition(this.value);
  45496. return new BABYLON.Vector3(point.x, 0, point.y);
  45497. };
  45498. PathCursor.prototype.moveAhead = function (step) {
  45499. if (step === void 0) { step = 0.002; }
  45500. this.move(step);
  45501. return this;
  45502. };
  45503. PathCursor.prototype.moveBack = function (step) {
  45504. if (step === void 0) { step = 0.002; }
  45505. this.move(-step);
  45506. return this;
  45507. };
  45508. PathCursor.prototype.move = function (step) {
  45509. if (Math.abs(step) > 1) {
  45510. throw "step size should be less than 1.";
  45511. }
  45512. this.value += step;
  45513. this.ensureLimits();
  45514. this.raiseOnChange();
  45515. return this;
  45516. };
  45517. PathCursor.prototype.ensureLimits = function () {
  45518. while (this.value > 1) {
  45519. this.value -= 1;
  45520. }
  45521. while (this.value < 0) {
  45522. this.value += 1;
  45523. }
  45524. return this;
  45525. };
  45526. // used by animation engine
  45527. PathCursor.prototype.raiseOnChange = function () {
  45528. var _this = this;
  45529. this._onchange.forEach(function (f) { return f(_this); });
  45530. return this;
  45531. };
  45532. PathCursor.prototype.onchange = function (f) {
  45533. this._onchange.push(f);
  45534. return this;
  45535. };
  45536. return PathCursor;
  45537. }());
  45538. BABYLON.PathCursor = PathCursor;
  45539. var AnimationKeyInterpolation;
  45540. (function (AnimationKeyInterpolation) {
  45541. /**
  45542. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45543. */
  45544. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45545. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45546. var Animation = /** @class */ (function () {
  45547. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45548. this.name = name;
  45549. this.targetProperty = targetProperty;
  45550. this.framePerSecond = framePerSecond;
  45551. this.dataType = dataType;
  45552. this.loopMode = loopMode;
  45553. this.enableBlending = enableBlending;
  45554. this._runtimeAnimations = new Array();
  45555. // The set of event that will be linked to this animation
  45556. this._events = new Array();
  45557. this.blendingSpeed = 0.01;
  45558. this._ranges = {};
  45559. this.targetPropertyPath = targetProperty.split(".");
  45560. this.dataType = dataType;
  45561. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45562. }
  45563. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45564. var dataType = undefined;
  45565. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45566. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45567. }
  45568. else if (from instanceof BABYLON.Quaternion) {
  45569. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45570. }
  45571. else if (from instanceof BABYLON.Vector3) {
  45572. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45573. }
  45574. else if (from instanceof BABYLON.Vector2) {
  45575. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45576. }
  45577. else if (from instanceof BABYLON.Color3) {
  45578. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45579. }
  45580. else if (from instanceof BABYLON.Size) {
  45581. dataType = Animation.ANIMATIONTYPE_SIZE;
  45582. }
  45583. if (dataType == undefined) {
  45584. return null;
  45585. }
  45586. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45587. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45588. animation.setKeys(keys);
  45589. if (easingFunction !== undefined) {
  45590. animation.setEasingFunction(easingFunction);
  45591. }
  45592. return animation;
  45593. };
  45594. /**
  45595. * Sets up an animation.
  45596. * @param property the property to animate
  45597. * @param animationType the animation type to apply
  45598. * @param easingFunction the easing function used in the animation
  45599. * @returns The created animation
  45600. */
  45601. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45602. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45603. animation.setEasingFunction(easingFunction);
  45604. return animation;
  45605. };
  45606. /**
  45607. * Create and start an animation on a node
  45608. * @param {string} name defines the name of the global animation that will be run on all nodes
  45609. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45610. * @param {string} targetProperty defines property to animate
  45611. * @param {number} framePerSecond defines the number of frame per second yo use
  45612. * @param {number} totalFrame defines the number of frames in total
  45613. * @param {any} from defines the initial value
  45614. * @param {any} to defines the final value
  45615. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45616. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45617. * @param onAnimationEnd defines the callback to call when animation end
  45618. * @returns the animatable created for this animation
  45619. */
  45620. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45621. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45622. if (!animation) {
  45623. return null;
  45624. }
  45625. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45626. };
  45627. /**
  45628. * Create and start an animation on a node and its descendants
  45629. * @param {string} name defines the name of the global animation that will be run on all nodes
  45630. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45631. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  45632. * @param {string} targetProperty defines property to animate
  45633. * @param {number} framePerSecond defines the number of frame per second yo use
  45634. * @param {number} totalFrame defines the number of frames in total
  45635. * @param {any} from defines the initial value
  45636. * @param {any} to defines the final value
  45637. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45638. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45639. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45640. * @returns the list of animatables created for all nodes
  45641. * @example https://www.babylonjs-playground.com/#MH0VLI
  45642. */
  45643. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45644. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45645. if (!animation) {
  45646. return null;
  45647. }
  45648. var scene = node.getScene();
  45649. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45650. };
  45651. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45652. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45653. if (!animation) {
  45654. return null;
  45655. }
  45656. node.animations.push(animation);
  45657. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45658. };
  45659. /**
  45660. * Transition property of the Camera to the target Value.
  45661. * @param property The property to transition
  45662. * @param targetValue The target Value of the property
  45663. * @param host The object where the property to animate belongs
  45664. * @param scene Scene used to run the animation
  45665. * @param frameRate Framerate (in frame/s) to use
  45666. * @param transition The transition type we want to use
  45667. * @param duration The duration of the animation, in milliseconds
  45668. * @param onAnimationEnd Call back trigger at the end of the animation.
  45669. */
  45670. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45671. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45672. if (duration <= 0) {
  45673. host[property] = targetValue;
  45674. if (onAnimationEnd) {
  45675. onAnimationEnd();
  45676. }
  45677. return null;
  45678. }
  45679. var endFrame = frameRate * (duration / 1000);
  45680. transition.setKeys([{
  45681. frame: 0,
  45682. value: host[property].clone ? host[property].clone() : host[property]
  45683. },
  45684. {
  45685. frame: endFrame,
  45686. value: targetValue
  45687. }]);
  45688. if (!host.animations) {
  45689. host.animations = [];
  45690. }
  45691. host.animations.push(transition);
  45692. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45693. animation.onAnimationEnd = onAnimationEnd;
  45694. return animation;
  45695. };
  45696. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45697. /**
  45698. * Return the array of runtime animations currently using this animation
  45699. */
  45700. get: function () {
  45701. return this._runtimeAnimations;
  45702. },
  45703. enumerable: true,
  45704. configurable: true
  45705. });
  45706. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45707. get: function () {
  45708. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45709. var runtimeAnimation = _a[_i];
  45710. if (!runtimeAnimation.isStopped) {
  45711. return true;
  45712. }
  45713. }
  45714. return false;
  45715. },
  45716. enumerable: true,
  45717. configurable: true
  45718. });
  45719. // Methods
  45720. /**
  45721. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45722. */
  45723. Animation.prototype.toString = function (fullDetails) {
  45724. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45725. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45726. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45727. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45728. if (fullDetails) {
  45729. ret += ", Ranges: {";
  45730. var first = true;
  45731. for (var name in this._ranges) {
  45732. if (first) {
  45733. ret += ", ";
  45734. first = false;
  45735. }
  45736. ret += name;
  45737. }
  45738. ret += "}";
  45739. }
  45740. return ret;
  45741. };
  45742. /**
  45743. * Add an event to this animation.
  45744. */
  45745. Animation.prototype.addEvent = function (event) {
  45746. this._events.push(event);
  45747. };
  45748. /**
  45749. * Remove all events found at the given frame
  45750. * @param frame
  45751. */
  45752. Animation.prototype.removeEvents = function (frame) {
  45753. for (var index = 0; index < this._events.length; index++) {
  45754. if (this._events[index].frame === frame) {
  45755. this._events.splice(index, 1);
  45756. index--;
  45757. }
  45758. }
  45759. };
  45760. Animation.prototype.getEvents = function () {
  45761. return this._events;
  45762. };
  45763. Animation.prototype.createRange = function (name, from, to) {
  45764. // check name not already in use; could happen for bones after serialized
  45765. if (!this._ranges[name]) {
  45766. this._ranges[name] = new AnimationRange(name, from, to);
  45767. }
  45768. };
  45769. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45770. if (deleteFrames === void 0) { deleteFrames = true; }
  45771. var range = this._ranges[name];
  45772. if (!range) {
  45773. return;
  45774. }
  45775. if (deleteFrames) {
  45776. var from = range.from;
  45777. var to = range.to;
  45778. // this loop MUST go high to low for multiple splices to work
  45779. for (var key = this._keys.length - 1; key >= 0; key--) {
  45780. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45781. this._keys.splice(key, 1);
  45782. }
  45783. }
  45784. }
  45785. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45786. };
  45787. Animation.prototype.getRange = function (name) {
  45788. return this._ranges[name];
  45789. };
  45790. Animation.prototype.getKeys = function () {
  45791. return this._keys;
  45792. };
  45793. Animation.prototype.getHighestFrame = function () {
  45794. var ret = 0;
  45795. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45796. if (ret < this._keys[key].frame) {
  45797. ret = this._keys[key].frame;
  45798. }
  45799. }
  45800. return ret;
  45801. };
  45802. Animation.prototype.getEasingFunction = function () {
  45803. return this._easingFunction;
  45804. };
  45805. Animation.prototype.setEasingFunction = function (easingFunction) {
  45806. this._easingFunction = easingFunction;
  45807. };
  45808. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45809. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45810. };
  45811. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45812. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45813. };
  45814. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45815. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45816. };
  45817. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45818. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45819. };
  45820. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45821. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45822. };
  45823. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45824. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45825. };
  45826. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45827. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45828. };
  45829. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45830. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45831. };
  45832. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45833. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45834. };
  45835. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45836. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45837. };
  45838. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45839. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45840. };
  45841. Animation.prototype.clone = function () {
  45842. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45843. clone.enableBlending = this.enableBlending;
  45844. clone.blendingSpeed = this.blendingSpeed;
  45845. if (this._keys) {
  45846. clone.setKeys(this._keys);
  45847. }
  45848. if (this._ranges) {
  45849. clone._ranges = {};
  45850. for (var name in this._ranges) {
  45851. var range = this._ranges[name];
  45852. if (!range) {
  45853. continue;
  45854. }
  45855. clone._ranges[name] = range.clone();
  45856. }
  45857. }
  45858. return clone;
  45859. };
  45860. Animation.prototype.setKeys = function (values) {
  45861. this._keys = values.slice(0);
  45862. };
  45863. Animation.prototype.serialize = function () {
  45864. var serializationObject = {};
  45865. serializationObject.name = this.name;
  45866. serializationObject.property = this.targetProperty;
  45867. serializationObject.framePerSecond = this.framePerSecond;
  45868. serializationObject.dataType = this.dataType;
  45869. serializationObject.loopBehavior = this.loopMode;
  45870. serializationObject.enableBlending = this.enableBlending;
  45871. serializationObject.blendingSpeed = this.blendingSpeed;
  45872. var dataType = this.dataType;
  45873. serializationObject.keys = [];
  45874. var keys = this.getKeys();
  45875. for (var index = 0; index < keys.length; index++) {
  45876. var animationKey = keys[index];
  45877. var key = {};
  45878. key.frame = animationKey.frame;
  45879. switch (dataType) {
  45880. case Animation.ANIMATIONTYPE_FLOAT:
  45881. key.values = [animationKey.value];
  45882. break;
  45883. case Animation.ANIMATIONTYPE_QUATERNION:
  45884. case Animation.ANIMATIONTYPE_MATRIX:
  45885. case Animation.ANIMATIONTYPE_VECTOR3:
  45886. case Animation.ANIMATIONTYPE_COLOR3:
  45887. key.values = animationKey.value.asArray();
  45888. break;
  45889. }
  45890. serializationObject.keys.push(key);
  45891. }
  45892. serializationObject.ranges = [];
  45893. for (var name in this._ranges) {
  45894. var source = this._ranges[name];
  45895. if (!source) {
  45896. continue;
  45897. }
  45898. var range = {};
  45899. range.name = name;
  45900. range.from = source.from;
  45901. range.to = source.to;
  45902. serializationObject.ranges.push(range);
  45903. }
  45904. return serializationObject;
  45905. };
  45906. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45907. get: function () {
  45908. return Animation._ANIMATIONTYPE_FLOAT;
  45909. },
  45910. enumerable: true,
  45911. configurable: true
  45912. });
  45913. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45914. get: function () {
  45915. return Animation._ANIMATIONTYPE_VECTOR3;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45921. get: function () {
  45922. return Animation._ANIMATIONTYPE_VECTOR2;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45928. get: function () {
  45929. return Animation._ANIMATIONTYPE_SIZE;
  45930. },
  45931. enumerable: true,
  45932. configurable: true
  45933. });
  45934. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45935. get: function () {
  45936. return Animation._ANIMATIONTYPE_QUATERNION;
  45937. },
  45938. enumerable: true,
  45939. configurable: true
  45940. });
  45941. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45942. get: function () {
  45943. return Animation._ANIMATIONTYPE_MATRIX;
  45944. },
  45945. enumerable: true,
  45946. configurable: true
  45947. });
  45948. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45949. get: function () {
  45950. return Animation._ANIMATIONTYPE_COLOR3;
  45951. },
  45952. enumerable: true,
  45953. configurable: true
  45954. });
  45955. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45956. get: function () {
  45957. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45963. get: function () {
  45964. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45965. },
  45966. enumerable: true,
  45967. configurable: true
  45968. });
  45969. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45970. get: function () {
  45971. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45972. },
  45973. enumerable: true,
  45974. configurable: true
  45975. });
  45976. Animation.Parse = function (parsedAnimation) {
  45977. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45978. var dataType = parsedAnimation.dataType;
  45979. var keys = [];
  45980. var data;
  45981. var index;
  45982. if (parsedAnimation.enableBlending) {
  45983. animation.enableBlending = parsedAnimation.enableBlending;
  45984. }
  45985. if (parsedAnimation.blendingSpeed) {
  45986. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45987. }
  45988. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45989. var key = parsedAnimation.keys[index];
  45990. var inTangent;
  45991. var outTangent;
  45992. switch (dataType) {
  45993. case Animation.ANIMATIONTYPE_FLOAT:
  45994. data = key.values[0];
  45995. if (key.values.length >= 1) {
  45996. inTangent = key.values[1];
  45997. }
  45998. if (key.values.length >= 2) {
  45999. outTangent = key.values[2];
  46000. }
  46001. break;
  46002. case Animation.ANIMATIONTYPE_QUATERNION:
  46003. data = BABYLON.Quaternion.FromArray(key.values);
  46004. if (key.values.length >= 8) {
  46005. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46006. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46007. inTangent = _inTangent;
  46008. }
  46009. }
  46010. if (key.values.length >= 12) {
  46011. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46012. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46013. outTangent = _outTangent;
  46014. }
  46015. }
  46016. break;
  46017. case Animation.ANIMATIONTYPE_MATRIX:
  46018. data = BABYLON.Matrix.FromArray(key.values);
  46019. break;
  46020. case Animation.ANIMATIONTYPE_COLOR3:
  46021. data = BABYLON.Color3.FromArray(key.values);
  46022. break;
  46023. case Animation.ANIMATIONTYPE_VECTOR3:
  46024. default:
  46025. data = BABYLON.Vector3.FromArray(key.values);
  46026. break;
  46027. }
  46028. var keyData = {};
  46029. keyData.frame = key.frame;
  46030. keyData.value = data;
  46031. if (inTangent != undefined) {
  46032. keyData.inTangent = inTangent;
  46033. }
  46034. if (outTangent != undefined) {
  46035. keyData.outTangent = outTangent;
  46036. }
  46037. keys.push(keyData);
  46038. }
  46039. animation.setKeys(keys);
  46040. if (parsedAnimation.ranges) {
  46041. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46042. data = parsedAnimation.ranges[index];
  46043. animation.createRange(data.name, data.from, data.to);
  46044. }
  46045. }
  46046. return animation;
  46047. };
  46048. Animation.AppendSerializedAnimations = function (source, destination) {
  46049. if (source.animations) {
  46050. destination.animations = [];
  46051. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46052. var animation = source.animations[animationIndex];
  46053. destination.animations.push(animation.serialize());
  46054. }
  46055. }
  46056. };
  46057. Animation.AllowMatricesInterpolation = false;
  46058. // Statics
  46059. Animation._ANIMATIONTYPE_FLOAT = 0;
  46060. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46061. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46062. Animation._ANIMATIONTYPE_MATRIX = 3;
  46063. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46064. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46065. Animation._ANIMATIONTYPE_SIZE = 6;
  46066. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46067. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46068. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46069. return Animation;
  46070. }());
  46071. BABYLON.Animation = Animation;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.animation.js.map
  46074. var BABYLON;
  46075. (function (BABYLON) {
  46076. /**
  46077. * This class defines the direct association between an animation and a target
  46078. */
  46079. var TargetedAnimation = /** @class */ (function () {
  46080. function TargetedAnimation() {
  46081. }
  46082. return TargetedAnimation;
  46083. }());
  46084. BABYLON.TargetedAnimation = TargetedAnimation;
  46085. /**
  46086. * Use this class to create coordinated animations on multiple targets
  46087. */
  46088. var AnimationGroup = /** @class */ (function () {
  46089. function AnimationGroup(name, scene) {
  46090. if (scene === void 0) { scene = null; }
  46091. this.name = name;
  46092. this._targetedAnimations = new Array();
  46093. this._animatables = new Array();
  46094. this._from = Number.MAX_VALUE;
  46095. this._to = -Number.MAX_VALUE;
  46096. this._speedRatio = 1;
  46097. this.onAnimationEndObservable = new BABYLON.Observable();
  46098. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46099. this._scene.animationGroups.push(this);
  46100. }
  46101. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46102. /**
  46103. * Define if the animations are started
  46104. */
  46105. get: function () {
  46106. return this._isStarted;
  46107. },
  46108. enumerable: true,
  46109. configurable: true
  46110. });
  46111. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46112. /**
  46113. * Gets or sets the speed ratio to use for all animations
  46114. */
  46115. get: function () {
  46116. return this._speedRatio;
  46117. },
  46118. /**
  46119. * Gets or sets the speed ratio to use for all animations
  46120. */
  46121. set: function (value) {
  46122. if (this._speedRatio === value) {
  46123. return;
  46124. }
  46125. this._speedRatio = value;
  46126. for (var index = 0; index < this._animatables.length; index++) {
  46127. var animatable = this._animatables[index];
  46128. animatable.speedRatio = this._speedRatio;
  46129. }
  46130. },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46135. /**
  46136. * Gets the targeted animations for this animation group
  46137. */
  46138. get: function () {
  46139. return this._targetedAnimations;
  46140. },
  46141. enumerable: true,
  46142. configurable: true
  46143. });
  46144. /**
  46145. * Add an animation (with its target) in the group
  46146. * @param animation defines the animation we want to add
  46147. * @param target defines the target of the animation
  46148. * @returns the {BABYLON.TargetedAnimation} object
  46149. */
  46150. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46151. var targetedAnimation = {
  46152. animation: animation,
  46153. target: target
  46154. };
  46155. var keys = animation.getKeys();
  46156. if (this._from > keys[0].frame) {
  46157. this._from = keys[0].frame;
  46158. }
  46159. if (this._to < keys[keys.length - 1].frame) {
  46160. this._to = keys[keys.length - 1].frame;
  46161. }
  46162. this._targetedAnimations.push(targetedAnimation);
  46163. return targetedAnimation;
  46164. };
  46165. /**
  46166. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46167. * It can add constant keys at begin or end
  46168. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46169. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46170. */
  46171. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46172. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46173. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46174. beginFrame = Math.max(beginFrame, this._from);
  46175. endFrame = Math.min(endFrame, this._to);
  46176. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46177. var targetedAnimation = this._targetedAnimations[index];
  46178. var keys = targetedAnimation.animation.getKeys();
  46179. var startKey = keys[0];
  46180. var endKey = keys[keys.length - 1];
  46181. if (startKey.frame > beginFrame) {
  46182. var newKey = {
  46183. frame: beginFrame,
  46184. value: startKey.value,
  46185. inTangent: startKey.inTangent,
  46186. outTangent: startKey.outTangent,
  46187. interpolation: startKey.interpolation
  46188. };
  46189. keys.splice(0, 0, newKey);
  46190. }
  46191. if (endKey.frame < endFrame) {
  46192. var newKey = {
  46193. frame: endFrame,
  46194. value: endKey.value,
  46195. inTangent: endKey.outTangent,
  46196. outTangent: endKey.outTangent,
  46197. interpolation: endKey.interpolation
  46198. };
  46199. keys.push(newKey);
  46200. }
  46201. }
  46202. return this;
  46203. };
  46204. /**
  46205. * Start all animations on given targets
  46206. * @param loop defines if animations must loop
  46207. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46208. */
  46209. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46210. var _this = this;
  46211. if (loop === void 0) { loop = false; }
  46212. if (speedRatio === void 0) { speedRatio = 1; }
  46213. if (this._isStarted || this._targetedAnimations.length === 0) {
  46214. return this;
  46215. }
  46216. var _loop_1 = function () {
  46217. var targetedAnimation = this_1._targetedAnimations[index];
  46218. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46219. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46220. }));
  46221. };
  46222. var this_1 = this;
  46223. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46224. _loop_1();
  46225. }
  46226. this._speedRatio = speedRatio;
  46227. this._isStarted = true;
  46228. return this;
  46229. };
  46230. /**
  46231. * Pause all animations
  46232. */
  46233. AnimationGroup.prototype.pause = function () {
  46234. if (!this._isStarted) {
  46235. return this;
  46236. }
  46237. for (var index = 0; index < this._animatables.length; index++) {
  46238. var animatable = this._animatables[index];
  46239. animatable.pause();
  46240. }
  46241. return this;
  46242. };
  46243. /**
  46244. * Play all animations to initial state
  46245. * This function will start() the animations if they were not started or will restart() them if they were paused
  46246. * @param loop defines if animations must loop
  46247. */
  46248. AnimationGroup.prototype.play = function (loop) {
  46249. if (this.isStarted) {
  46250. if (loop !== undefined) {
  46251. for (var index = 0; index < this._animatables.length; index++) {
  46252. var animatable = this._animatables[index];
  46253. animatable.loopAnimation = loop;
  46254. }
  46255. }
  46256. this.restart();
  46257. }
  46258. else {
  46259. this.start(loop, this._speedRatio);
  46260. }
  46261. return this;
  46262. };
  46263. /**
  46264. * Reset all animations to initial state
  46265. */
  46266. AnimationGroup.prototype.reset = function () {
  46267. if (!this._isStarted) {
  46268. return this;
  46269. }
  46270. for (var index = 0; index < this._animatables.length; index++) {
  46271. var animatable = this._animatables[index];
  46272. animatable.reset();
  46273. }
  46274. return this;
  46275. };
  46276. /**
  46277. * Restart animations from key 0
  46278. */
  46279. AnimationGroup.prototype.restart = function () {
  46280. if (!this._isStarted) {
  46281. return this;
  46282. }
  46283. for (var index = 0; index < this._animatables.length; index++) {
  46284. var animatable = this._animatables[index];
  46285. animatable.restart();
  46286. }
  46287. return this;
  46288. };
  46289. /**
  46290. * Stop all animations
  46291. */
  46292. AnimationGroup.prototype.stop = function () {
  46293. if (!this._isStarted) {
  46294. return this;
  46295. }
  46296. for (var index = 0; index < this._animatables.length; index++) {
  46297. var animatable = this._animatables[index];
  46298. animatable.stop();
  46299. }
  46300. this._isStarted = false;
  46301. return this;
  46302. };
  46303. /**
  46304. * Dispose all associated resources
  46305. */
  46306. AnimationGroup.prototype.dispose = function () {
  46307. this._targetedAnimations = [];
  46308. this._animatables = [];
  46309. var index = this._scene.animationGroups.indexOf(this);
  46310. if (index > -1) {
  46311. this._scene.animationGroups.splice(index, 1);
  46312. }
  46313. };
  46314. return AnimationGroup;
  46315. }());
  46316. BABYLON.AnimationGroup = AnimationGroup;
  46317. })(BABYLON || (BABYLON = {}));
  46318. //# sourceMappingURL=babylon.animationGroup.js.map
  46319. var BABYLON;
  46320. (function (BABYLON) {
  46321. var RuntimeAnimation = /** @class */ (function () {
  46322. function RuntimeAnimation(target, animation) {
  46323. this._offsetsCache = {};
  46324. this._highLimitsCache = {};
  46325. this._stopped = false;
  46326. this._blendingFactor = 0;
  46327. this._ratioOffset = 0;
  46328. this._animation = animation;
  46329. this._target = target;
  46330. animation._runtimeAnimations.push(this);
  46331. }
  46332. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46333. get: function () {
  46334. return this._animation;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. RuntimeAnimation.prototype.reset = function () {
  46340. this._offsetsCache = {};
  46341. this._highLimitsCache = {};
  46342. this.currentFrame = 0;
  46343. this._blendingFactor = 0;
  46344. this._originalBlendValue = null;
  46345. };
  46346. RuntimeAnimation.prototype.isStopped = function () {
  46347. return this._stopped;
  46348. };
  46349. RuntimeAnimation.prototype.dispose = function () {
  46350. var index = this._animation.runtimeAnimations.indexOf(this);
  46351. if (index > -1) {
  46352. this._animation.runtimeAnimations.splice(index, 1);
  46353. }
  46354. };
  46355. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46356. if (typeof value === "function") {
  46357. return value();
  46358. }
  46359. return value;
  46360. };
  46361. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46362. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46363. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46364. }
  46365. this.currentFrame = currentFrame;
  46366. var keys = this._animation.getKeys();
  46367. // Try to get a hash to find the right key
  46368. 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));
  46369. if (keys[startKeyIndex].frame >= currentFrame) {
  46370. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46371. startKeyIndex--;
  46372. }
  46373. }
  46374. for (var key = startKeyIndex; key < keys.length; key++) {
  46375. var endKey = keys[key + 1];
  46376. if (endKey.frame >= currentFrame) {
  46377. var startKey = keys[key];
  46378. var startValue = this._getKeyValue(startKey.value);
  46379. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46380. return startValue;
  46381. }
  46382. var endValue = this._getKeyValue(endKey.value);
  46383. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46384. var frameDelta = endKey.frame - startKey.frame;
  46385. // gradient : percent of currentFrame between the frame inf and the frame sup
  46386. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46387. // check for easingFunction and correction of gradient
  46388. var easingFunction = this._animation.getEasingFunction();
  46389. if (easingFunction != null) {
  46390. gradient = easingFunction.ease(gradient);
  46391. }
  46392. switch (this._animation.dataType) {
  46393. // Float
  46394. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46395. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46396. switch (loopMode) {
  46397. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46398. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46399. return floatValue;
  46400. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46401. return offsetValue * repeatCount + floatValue;
  46402. }
  46403. break;
  46404. // Quaternion
  46405. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46406. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46407. switch (loopMode) {
  46408. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46409. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46410. return quatValue;
  46411. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46412. return quatValue.add(offsetValue.scale(repeatCount));
  46413. }
  46414. return quatValue;
  46415. // Vector3
  46416. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46417. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46418. switch (loopMode) {
  46419. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46420. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46421. return vec3Value;
  46422. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46423. return vec3Value.add(offsetValue.scale(repeatCount));
  46424. }
  46425. // Vector2
  46426. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46427. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46428. switch (loopMode) {
  46429. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46430. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46431. return vec2Value;
  46432. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46433. return vec2Value.add(offsetValue.scale(repeatCount));
  46434. }
  46435. // Size
  46436. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46437. switch (loopMode) {
  46438. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46439. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46440. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46441. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46442. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46443. }
  46444. // Color3
  46445. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46446. switch (loopMode) {
  46447. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46448. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46449. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46450. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46451. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46452. }
  46453. // Matrix
  46454. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46455. switch (loopMode) {
  46456. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46457. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46458. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46459. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46460. }
  46461. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46462. return startValue;
  46463. }
  46464. default:
  46465. break;
  46466. }
  46467. break;
  46468. }
  46469. }
  46470. return this._getKeyValue(keys[keys.length - 1].value);
  46471. };
  46472. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46473. if (blend === void 0) { blend = false; }
  46474. // Set value
  46475. var path;
  46476. var destination;
  46477. var targetPropertyPath = this._animation.targetPropertyPath;
  46478. if (targetPropertyPath.length > 1) {
  46479. var property = this._target[targetPropertyPath[0]];
  46480. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46481. property = property[targetPropertyPath[index]];
  46482. }
  46483. path = targetPropertyPath[targetPropertyPath.length - 1];
  46484. destination = property;
  46485. }
  46486. else {
  46487. path = targetPropertyPath[0];
  46488. destination = this._target;
  46489. }
  46490. // Blending
  46491. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46492. if (!this._originalBlendValue) {
  46493. if (destination[path].clone) {
  46494. this._originalBlendValue = destination[path].clone();
  46495. }
  46496. else {
  46497. this._originalBlendValue = destination[path];
  46498. }
  46499. }
  46500. if (this._originalBlendValue.prototype) {
  46501. if (this._originalBlendValue.prototype.Lerp) {
  46502. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46503. }
  46504. else {
  46505. destination[path] = currentValue;
  46506. }
  46507. }
  46508. else if (this._originalBlendValue.m) {
  46509. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46510. }
  46511. else {
  46512. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46513. }
  46514. this._blendingFactor += this._animation.blendingSpeed;
  46515. }
  46516. else {
  46517. destination[path] = currentValue;
  46518. }
  46519. if (this._target.markAsDirty) {
  46520. this._target.markAsDirty(this._animation.targetProperty);
  46521. }
  46522. };
  46523. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46524. var keys = this._animation.getKeys();
  46525. if (frame < keys[0].frame) {
  46526. frame = keys[0].frame;
  46527. }
  46528. else if (frame > keys[keys.length - 1].frame) {
  46529. frame = keys[keys.length - 1].frame;
  46530. }
  46531. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46532. this.setValue(currentValue);
  46533. };
  46534. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46535. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46536. this._ratioOffset = this._previousRatio - newRatio;
  46537. };
  46538. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46539. if (blend === void 0) { blend = false; }
  46540. var targetPropertyPath = this._animation.targetPropertyPath;
  46541. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46542. this._stopped = true;
  46543. return false;
  46544. }
  46545. var returnValue = true;
  46546. var keys = this._animation.getKeys();
  46547. // Adding a start key at frame 0 if missing
  46548. if (keys[0].frame !== 0) {
  46549. var newKey = { frame: 0, value: keys[0].value };
  46550. keys.splice(0, 0, newKey);
  46551. }
  46552. // Check limits
  46553. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46554. from = keys[0].frame;
  46555. }
  46556. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46557. to = keys[keys.length - 1].frame;
  46558. }
  46559. //to and from cannot be the same key
  46560. if (from === to) {
  46561. if (from > keys[0].frame) {
  46562. from--;
  46563. }
  46564. else if (to < keys[keys.length - 1].frame) {
  46565. to++;
  46566. }
  46567. }
  46568. // Compute ratio
  46569. var range = to - from;
  46570. var offsetValue;
  46571. // ratio represents the frame delta between from and to
  46572. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46573. var highLimitValue = 0;
  46574. this._previousDelay = delay;
  46575. this._previousRatio = ratio;
  46576. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46577. returnValue = false;
  46578. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46579. }
  46580. else {
  46581. // Get max value if required
  46582. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46583. var keyOffset = to.toString() + from.toString();
  46584. if (!this._offsetsCache[keyOffset]) {
  46585. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46586. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46587. switch (this._animation.dataType) {
  46588. // Float
  46589. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46590. this._offsetsCache[keyOffset] = toValue - fromValue;
  46591. break;
  46592. // Quaternion
  46593. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46594. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46595. break;
  46596. // Vector3
  46597. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46599. // Vector2
  46600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46601. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46602. // Size
  46603. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46604. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46605. // Color3
  46606. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46607. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46608. default:
  46609. break;
  46610. }
  46611. this._highLimitsCache[keyOffset] = toValue;
  46612. }
  46613. highLimitValue = this._highLimitsCache[keyOffset];
  46614. offsetValue = this._offsetsCache[keyOffset];
  46615. }
  46616. }
  46617. if (offsetValue === undefined) {
  46618. switch (this._animation.dataType) {
  46619. // Float
  46620. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46621. offsetValue = 0;
  46622. break;
  46623. // Quaternion
  46624. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46625. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46626. break;
  46627. // Vector3
  46628. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46629. offsetValue = BABYLON.Vector3.Zero();
  46630. break;
  46631. // Vector2
  46632. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46633. offsetValue = BABYLON.Vector2.Zero();
  46634. break;
  46635. // Size
  46636. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46637. offsetValue = BABYLON.Size.Zero();
  46638. break;
  46639. // Color3
  46640. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46641. offsetValue = BABYLON.Color3.Black();
  46642. }
  46643. }
  46644. // Compute value
  46645. var repeatCount = (ratio / range) >> 0;
  46646. var currentFrame = returnValue ? from + ratio % range : to;
  46647. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46648. // Set value
  46649. this.setValue(currentValue);
  46650. // Check events
  46651. var events = this._animation.getEvents();
  46652. for (var index = 0; index < events.length; index++) {
  46653. // Make sure current frame has passed event frame and that event frame is within the current range
  46654. // Also, handle both forward and reverse animations
  46655. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46656. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46657. var event = events[index];
  46658. if (!event.isDone) {
  46659. // If event should be done only once, remove it.
  46660. if (event.onlyOnce) {
  46661. events.splice(index, 1);
  46662. index--;
  46663. }
  46664. event.isDone = true;
  46665. event.action();
  46666. } // Don't do anything if the event has already be done.
  46667. }
  46668. else if (events[index].isDone && !events[index].onlyOnce) {
  46669. // reset event, the animation is looping
  46670. events[index].isDone = false;
  46671. }
  46672. }
  46673. if (!returnValue) {
  46674. this._stopped = true;
  46675. }
  46676. return returnValue;
  46677. };
  46678. return RuntimeAnimation;
  46679. }());
  46680. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46681. })(BABYLON || (BABYLON = {}));
  46682. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46683. var BABYLON;
  46684. (function (BABYLON) {
  46685. var Animatable = /** @class */ (function () {
  46686. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46687. if (fromFrame === void 0) { fromFrame = 0; }
  46688. if (toFrame === void 0) { toFrame = 100; }
  46689. if (loopAnimation === void 0) { loopAnimation = false; }
  46690. if (speedRatio === void 0) { speedRatio = 1.0; }
  46691. this.target = target;
  46692. this.fromFrame = fromFrame;
  46693. this.toFrame = toFrame;
  46694. this.loopAnimation = loopAnimation;
  46695. this.onAnimationEnd = onAnimationEnd;
  46696. this._localDelayOffset = null;
  46697. this._pausedDelay = null;
  46698. this._runtimeAnimations = new Array();
  46699. this._paused = false;
  46700. this._speedRatio = 1;
  46701. this.animationStarted = false;
  46702. if (animations) {
  46703. this.appendAnimations(target, animations);
  46704. }
  46705. this._speedRatio = speedRatio;
  46706. this._scene = scene;
  46707. scene._activeAnimatables.push(this);
  46708. }
  46709. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46710. get: function () {
  46711. return this._speedRatio;
  46712. },
  46713. set: function (value) {
  46714. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46715. var animation = this._runtimeAnimations[index];
  46716. animation._prepareForSpeedRatioChange(value);
  46717. }
  46718. this._speedRatio = value;
  46719. },
  46720. enumerable: true,
  46721. configurable: true
  46722. });
  46723. // Methods
  46724. Animatable.prototype.getAnimations = function () {
  46725. return this._runtimeAnimations;
  46726. };
  46727. Animatable.prototype.appendAnimations = function (target, animations) {
  46728. for (var index = 0; index < animations.length; index++) {
  46729. var animation = animations[index];
  46730. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46731. }
  46732. };
  46733. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46734. var runtimeAnimations = this._runtimeAnimations;
  46735. for (var index = 0; index < runtimeAnimations.length; index++) {
  46736. if (runtimeAnimations[index].animation.targetProperty === property) {
  46737. return runtimeAnimations[index].animation;
  46738. }
  46739. }
  46740. return null;
  46741. };
  46742. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46743. var runtimeAnimations = this._runtimeAnimations;
  46744. for (var index = 0; index < runtimeAnimations.length; index++) {
  46745. if (runtimeAnimations[index].animation.targetProperty === property) {
  46746. return runtimeAnimations[index];
  46747. }
  46748. }
  46749. return null;
  46750. };
  46751. Animatable.prototype.reset = function () {
  46752. var runtimeAnimations = this._runtimeAnimations;
  46753. for (var index = 0; index < runtimeAnimations.length; index++) {
  46754. runtimeAnimations[index].reset();
  46755. }
  46756. // Reset to original value
  46757. for (index = 0; index < runtimeAnimations.length; index++) {
  46758. var animation = runtimeAnimations[index];
  46759. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46760. }
  46761. this._localDelayOffset = null;
  46762. this._pausedDelay = null;
  46763. };
  46764. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46765. var runtimeAnimations = this._runtimeAnimations;
  46766. for (var index = 0; index < runtimeAnimations.length; index++) {
  46767. runtimeAnimations[index].animation.enableBlending = true;
  46768. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46769. }
  46770. };
  46771. Animatable.prototype.disableBlending = function () {
  46772. var runtimeAnimations = this._runtimeAnimations;
  46773. for (var index = 0; index < runtimeAnimations.length; index++) {
  46774. runtimeAnimations[index].animation.enableBlending = false;
  46775. }
  46776. };
  46777. Animatable.prototype.goToFrame = function (frame) {
  46778. var runtimeAnimations = this._runtimeAnimations;
  46779. if (runtimeAnimations[0]) {
  46780. var fps = runtimeAnimations[0].animation.framePerSecond;
  46781. var currentFrame = runtimeAnimations[0].currentFrame;
  46782. var adjustTime = frame - currentFrame;
  46783. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46784. if (this._localDelayOffset === null) {
  46785. this._localDelayOffset = 0;
  46786. }
  46787. this._localDelayOffset -= delay;
  46788. }
  46789. for (var index = 0; index < runtimeAnimations.length; index++) {
  46790. runtimeAnimations[index].goToFrame(frame);
  46791. }
  46792. };
  46793. Animatable.prototype.pause = function () {
  46794. if (this._paused) {
  46795. return;
  46796. }
  46797. this._paused = true;
  46798. };
  46799. Animatable.prototype.restart = function () {
  46800. this._paused = false;
  46801. };
  46802. Animatable.prototype.stop = function (animationName) {
  46803. if (animationName) {
  46804. var idx = this._scene._activeAnimatables.indexOf(this);
  46805. if (idx > -1) {
  46806. var runtimeAnimations = this._runtimeAnimations;
  46807. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46808. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46809. continue;
  46810. }
  46811. runtimeAnimations[index].dispose();
  46812. runtimeAnimations.splice(index, 1);
  46813. }
  46814. if (runtimeAnimations.length == 0) {
  46815. this._scene._activeAnimatables.splice(idx, 1);
  46816. if (this.onAnimationEnd) {
  46817. this.onAnimationEnd();
  46818. }
  46819. }
  46820. }
  46821. }
  46822. else {
  46823. var index = this._scene._activeAnimatables.indexOf(this);
  46824. if (index > -1) {
  46825. this._scene._activeAnimatables.splice(index, 1);
  46826. var runtimeAnimations = this._runtimeAnimations;
  46827. for (var index = 0; index < runtimeAnimations.length; index++) {
  46828. runtimeAnimations[index].dispose();
  46829. }
  46830. if (this.onAnimationEnd) {
  46831. this.onAnimationEnd();
  46832. }
  46833. }
  46834. }
  46835. };
  46836. Animatable.prototype._animate = function (delay) {
  46837. if (this._paused) {
  46838. this.animationStarted = false;
  46839. if (this._pausedDelay === null) {
  46840. this._pausedDelay = delay;
  46841. }
  46842. return true;
  46843. }
  46844. if (this._localDelayOffset === null) {
  46845. this._localDelayOffset = delay;
  46846. this._pausedDelay = null;
  46847. }
  46848. else if (this._pausedDelay !== null) {
  46849. this._localDelayOffset += delay - this._pausedDelay;
  46850. this._pausedDelay = null;
  46851. }
  46852. // Animating
  46853. var running = false;
  46854. var runtimeAnimations = this._runtimeAnimations;
  46855. var index;
  46856. for (index = 0; index < runtimeAnimations.length; index++) {
  46857. var animation = runtimeAnimations[index];
  46858. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46859. running = running || isRunning;
  46860. }
  46861. this.animationStarted = running;
  46862. if (!running) {
  46863. // Remove from active animatables
  46864. index = this._scene._activeAnimatables.indexOf(this);
  46865. this._scene._activeAnimatables.splice(index, 1);
  46866. // Dispose all runtime animations
  46867. for (index = 0; index < runtimeAnimations.length; index++) {
  46868. runtimeAnimations[index].dispose();
  46869. }
  46870. }
  46871. if (!running && this.onAnimationEnd) {
  46872. this.onAnimationEnd();
  46873. this.onAnimationEnd = null;
  46874. }
  46875. return running;
  46876. };
  46877. return Animatable;
  46878. }());
  46879. BABYLON.Animatable = Animatable;
  46880. })(BABYLON || (BABYLON = {}));
  46881. //# sourceMappingURL=babylon.animatable.js.map
  46882. var BABYLON;
  46883. (function (BABYLON) {
  46884. var EasingFunction = /** @class */ (function () {
  46885. function EasingFunction() {
  46886. // Properties
  46887. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46888. }
  46889. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46890. get: function () {
  46891. return EasingFunction._EASINGMODE_EASEIN;
  46892. },
  46893. enumerable: true,
  46894. configurable: true
  46895. });
  46896. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46897. get: function () {
  46898. return EasingFunction._EASINGMODE_EASEOUT;
  46899. },
  46900. enumerable: true,
  46901. configurable: true
  46902. });
  46903. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46904. get: function () {
  46905. return EasingFunction._EASINGMODE_EASEINOUT;
  46906. },
  46907. enumerable: true,
  46908. configurable: true
  46909. });
  46910. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46911. var n = Math.min(Math.max(easingMode, 0), 2);
  46912. this._easingMode = n;
  46913. };
  46914. EasingFunction.prototype.getEasingMode = function () {
  46915. return this._easingMode;
  46916. };
  46917. EasingFunction.prototype.easeInCore = function (gradient) {
  46918. throw new Error('You must implement this method');
  46919. };
  46920. EasingFunction.prototype.ease = function (gradient) {
  46921. switch (this._easingMode) {
  46922. case EasingFunction.EASINGMODE_EASEIN:
  46923. return this.easeInCore(gradient);
  46924. case EasingFunction.EASINGMODE_EASEOUT:
  46925. return (1 - this.easeInCore(1 - gradient));
  46926. }
  46927. if (gradient >= 0.5) {
  46928. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46929. }
  46930. return (this.easeInCore(gradient * 2) * 0.5);
  46931. };
  46932. //Statics
  46933. EasingFunction._EASINGMODE_EASEIN = 0;
  46934. EasingFunction._EASINGMODE_EASEOUT = 1;
  46935. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46936. return EasingFunction;
  46937. }());
  46938. BABYLON.EasingFunction = EasingFunction;
  46939. var CircleEase = /** @class */ (function (_super) {
  46940. __extends(CircleEase, _super);
  46941. function CircleEase() {
  46942. return _super !== null && _super.apply(this, arguments) || this;
  46943. }
  46944. CircleEase.prototype.easeInCore = function (gradient) {
  46945. gradient = Math.max(0, Math.min(1, gradient));
  46946. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46947. };
  46948. return CircleEase;
  46949. }(EasingFunction));
  46950. BABYLON.CircleEase = CircleEase;
  46951. var BackEase = /** @class */ (function (_super) {
  46952. __extends(BackEase, _super);
  46953. function BackEase(amplitude) {
  46954. if (amplitude === void 0) { amplitude = 1; }
  46955. var _this = _super.call(this) || this;
  46956. _this.amplitude = amplitude;
  46957. return _this;
  46958. }
  46959. BackEase.prototype.easeInCore = function (gradient) {
  46960. var num = Math.max(0, this.amplitude);
  46961. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46962. };
  46963. return BackEase;
  46964. }(EasingFunction));
  46965. BABYLON.BackEase = BackEase;
  46966. var BounceEase = /** @class */ (function (_super) {
  46967. __extends(BounceEase, _super);
  46968. function BounceEase(bounces, bounciness) {
  46969. if (bounces === void 0) { bounces = 3; }
  46970. if (bounciness === void 0) { bounciness = 2; }
  46971. var _this = _super.call(this) || this;
  46972. _this.bounces = bounces;
  46973. _this.bounciness = bounciness;
  46974. return _this;
  46975. }
  46976. BounceEase.prototype.easeInCore = function (gradient) {
  46977. var y = Math.max(0.0, this.bounces);
  46978. var bounciness = this.bounciness;
  46979. if (bounciness <= 1.0) {
  46980. bounciness = 1.001;
  46981. }
  46982. var num9 = Math.pow(bounciness, y);
  46983. var num5 = 1.0 - bounciness;
  46984. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46985. var num15 = gradient * num4;
  46986. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46987. var num3 = Math.floor(num65);
  46988. var num13 = num3 + 1.0;
  46989. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46990. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46991. var num7 = (num8 + num12) * 0.5;
  46992. var num6 = gradient - num7;
  46993. var num2 = num7 - num8;
  46994. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46995. };
  46996. return BounceEase;
  46997. }(EasingFunction));
  46998. BABYLON.BounceEase = BounceEase;
  46999. var CubicEase = /** @class */ (function (_super) {
  47000. __extends(CubicEase, _super);
  47001. function CubicEase() {
  47002. return _super !== null && _super.apply(this, arguments) || this;
  47003. }
  47004. CubicEase.prototype.easeInCore = function (gradient) {
  47005. return (gradient * gradient * gradient);
  47006. };
  47007. return CubicEase;
  47008. }(EasingFunction));
  47009. BABYLON.CubicEase = CubicEase;
  47010. var ElasticEase = /** @class */ (function (_super) {
  47011. __extends(ElasticEase, _super);
  47012. function ElasticEase(oscillations, springiness) {
  47013. if (oscillations === void 0) { oscillations = 3; }
  47014. if (springiness === void 0) { springiness = 3; }
  47015. var _this = _super.call(this) || this;
  47016. _this.oscillations = oscillations;
  47017. _this.springiness = springiness;
  47018. return _this;
  47019. }
  47020. ElasticEase.prototype.easeInCore = function (gradient) {
  47021. var num2;
  47022. var num3 = Math.max(0.0, this.oscillations);
  47023. var num = Math.max(0.0, this.springiness);
  47024. if (num == 0) {
  47025. num2 = gradient;
  47026. }
  47027. else {
  47028. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47029. }
  47030. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47031. };
  47032. return ElasticEase;
  47033. }(EasingFunction));
  47034. BABYLON.ElasticEase = ElasticEase;
  47035. var ExponentialEase = /** @class */ (function (_super) {
  47036. __extends(ExponentialEase, _super);
  47037. function ExponentialEase(exponent) {
  47038. if (exponent === void 0) { exponent = 2; }
  47039. var _this = _super.call(this) || this;
  47040. _this.exponent = exponent;
  47041. return _this;
  47042. }
  47043. ExponentialEase.prototype.easeInCore = function (gradient) {
  47044. if (this.exponent <= 0) {
  47045. return gradient;
  47046. }
  47047. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47048. };
  47049. return ExponentialEase;
  47050. }(EasingFunction));
  47051. BABYLON.ExponentialEase = ExponentialEase;
  47052. var PowerEase = /** @class */ (function (_super) {
  47053. __extends(PowerEase, _super);
  47054. function PowerEase(power) {
  47055. if (power === void 0) { power = 2; }
  47056. var _this = _super.call(this) || this;
  47057. _this.power = power;
  47058. return _this;
  47059. }
  47060. PowerEase.prototype.easeInCore = function (gradient) {
  47061. var y = Math.max(0.0, this.power);
  47062. return Math.pow(gradient, y);
  47063. };
  47064. return PowerEase;
  47065. }(EasingFunction));
  47066. BABYLON.PowerEase = PowerEase;
  47067. var QuadraticEase = /** @class */ (function (_super) {
  47068. __extends(QuadraticEase, _super);
  47069. function QuadraticEase() {
  47070. return _super !== null && _super.apply(this, arguments) || this;
  47071. }
  47072. QuadraticEase.prototype.easeInCore = function (gradient) {
  47073. return (gradient * gradient);
  47074. };
  47075. return QuadraticEase;
  47076. }(EasingFunction));
  47077. BABYLON.QuadraticEase = QuadraticEase;
  47078. var QuarticEase = /** @class */ (function (_super) {
  47079. __extends(QuarticEase, _super);
  47080. function QuarticEase() {
  47081. return _super !== null && _super.apply(this, arguments) || this;
  47082. }
  47083. QuarticEase.prototype.easeInCore = function (gradient) {
  47084. return (gradient * gradient * gradient * gradient);
  47085. };
  47086. return QuarticEase;
  47087. }(EasingFunction));
  47088. BABYLON.QuarticEase = QuarticEase;
  47089. var QuinticEase = /** @class */ (function (_super) {
  47090. __extends(QuinticEase, _super);
  47091. function QuinticEase() {
  47092. return _super !== null && _super.apply(this, arguments) || this;
  47093. }
  47094. QuinticEase.prototype.easeInCore = function (gradient) {
  47095. return (gradient * gradient * gradient * gradient * gradient);
  47096. };
  47097. return QuinticEase;
  47098. }(EasingFunction));
  47099. BABYLON.QuinticEase = QuinticEase;
  47100. var SineEase = /** @class */ (function (_super) {
  47101. __extends(SineEase, _super);
  47102. function SineEase() {
  47103. return _super !== null && _super.apply(this, arguments) || this;
  47104. }
  47105. SineEase.prototype.easeInCore = function (gradient) {
  47106. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47107. };
  47108. return SineEase;
  47109. }(EasingFunction));
  47110. BABYLON.SineEase = SineEase;
  47111. var BezierCurveEase = /** @class */ (function (_super) {
  47112. __extends(BezierCurveEase, _super);
  47113. function BezierCurveEase(x1, y1, x2, y2) {
  47114. if (x1 === void 0) { x1 = 0; }
  47115. if (y1 === void 0) { y1 = 0; }
  47116. if (x2 === void 0) { x2 = 1; }
  47117. if (y2 === void 0) { y2 = 1; }
  47118. var _this = _super.call(this) || this;
  47119. _this.x1 = x1;
  47120. _this.y1 = y1;
  47121. _this.x2 = x2;
  47122. _this.y2 = y2;
  47123. return _this;
  47124. }
  47125. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47126. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47127. };
  47128. return BezierCurveEase;
  47129. }(EasingFunction));
  47130. BABYLON.BezierCurveEase = BezierCurveEase;
  47131. })(BABYLON || (BABYLON = {}));
  47132. //# sourceMappingURL=babylon.easing.js.map
  47133. var BABYLON;
  47134. (function (BABYLON) {
  47135. var Condition = /** @class */ (function () {
  47136. function Condition(actionManager) {
  47137. this._actionManager = actionManager;
  47138. }
  47139. Condition.prototype.isValid = function () {
  47140. return true;
  47141. };
  47142. Condition.prototype._getProperty = function (propertyPath) {
  47143. return this._actionManager._getProperty(propertyPath);
  47144. };
  47145. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47146. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47147. };
  47148. Condition.prototype.serialize = function () {
  47149. };
  47150. Condition.prototype._serialize = function (serializedCondition) {
  47151. return {
  47152. type: 2,
  47153. children: [],
  47154. name: serializedCondition.name,
  47155. properties: serializedCondition.properties
  47156. };
  47157. };
  47158. return Condition;
  47159. }());
  47160. BABYLON.Condition = Condition;
  47161. var ValueCondition = /** @class */ (function (_super) {
  47162. __extends(ValueCondition, _super);
  47163. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47164. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47165. var _this = _super.call(this, actionManager) || this;
  47166. _this.propertyPath = propertyPath;
  47167. _this.value = value;
  47168. _this.operator = operator;
  47169. _this._target = target;
  47170. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47171. _this._property = _this._getProperty(_this.propertyPath);
  47172. return _this;
  47173. }
  47174. Object.defineProperty(ValueCondition, "IsEqual", {
  47175. get: function () {
  47176. return ValueCondition._IsEqual;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. Object.defineProperty(ValueCondition, "IsDifferent", {
  47182. get: function () {
  47183. return ValueCondition._IsDifferent;
  47184. },
  47185. enumerable: true,
  47186. configurable: true
  47187. });
  47188. Object.defineProperty(ValueCondition, "IsGreater", {
  47189. get: function () {
  47190. return ValueCondition._IsGreater;
  47191. },
  47192. enumerable: true,
  47193. configurable: true
  47194. });
  47195. Object.defineProperty(ValueCondition, "IsLesser", {
  47196. get: function () {
  47197. return ValueCondition._IsLesser;
  47198. },
  47199. enumerable: true,
  47200. configurable: true
  47201. });
  47202. // Methods
  47203. ValueCondition.prototype.isValid = function () {
  47204. switch (this.operator) {
  47205. case ValueCondition.IsGreater:
  47206. return this._effectiveTarget[this._property] > this.value;
  47207. case ValueCondition.IsLesser:
  47208. return this._effectiveTarget[this._property] < this.value;
  47209. case ValueCondition.IsEqual:
  47210. case ValueCondition.IsDifferent:
  47211. var check;
  47212. if (this.value.equals) {
  47213. check = this.value.equals(this._effectiveTarget[this._property]);
  47214. }
  47215. else {
  47216. check = this.value === this._effectiveTarget[this._property];
  47217. }
  47218. return this.operator === ValueCondition.IsEqual ? check : !check;
  47219. }
  47220. return false;
  47221. };
  47222. ValueCondition.prototype.serialize = function () {
  47223. return this._serialize({
  47224. name: "ValueCondition",
  47225. properties: [
  47226. BABYLON.Action._GetTargetProperty(this._target),
  47227. { name: "propertyPath", value: this.propertyPath },
  47228. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47229. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47230. ]
  47231. });
  47232. };
  47233. ValueCondition.GetOperatorName = function (operator) {
  47234. switch (operator) {
  47235. case ValueCondition._IsEqual: return "IsEqual";
  47236. case ValueCondition._IsDifferent: return "IsDifferent";
  47237. case ValueCondition._IsGreater: return "IsGreater";
  47238. case ValueCondition._IsLesser: return "IsLesser";
  47239. default: return "";
  47240. }
  47241. };
  47242. // Statics
  47243. ValueCondition._IsEqual = 0;
  47244. ValueCondition._IsDifferent = 1;
  47245. ValueCondition._IsGreater = 2;
  47246. ValueCondition._IsLesser = 3;
  47247. return ValueCondition;
  47248. }(Condition));
  47249. BABYLON.ValueCondition = ValueCondition;
  47250. var PredicateCondition = /** @class */ (function (_super) {
  47251. __extends(PredicateCondition, _super);
  47252. function PredicateCondition(actionManager, predicate) {
  47253. var _this = _super.call(this, actionManager) || this;
  47254. _this.predicate = predicate;
  47255. return _this;
  47256. }
  47257. PredicateCondition.prototype.isValid = function () {
  47258. return this.predicate();
  47259. };
  47260. return PredicateCondition;
  47261. }(Condition));
  47262. BABYLON.PredicateCondition = PredicateCondition;
  47263. var StateCondition = /** @class */ (function (_super) {
  47264. __extends(StateCondition, _super);
  47265. function StateCondition(actionManager, target, value) {
  47266. var _this = _super.call(this, actionManager) || this;
  47267. _this.value = value;
  47268. _this._target = target;
  47269. return _this;
  47270. }
  47271. // Methods
  47272. StateCondition.prototype.isValid = function () {
  47273. return this._target.state === this.value;
  47274. };
  47275. StateCondition.prototype.serialize = function () {
  47276. return this._serialize({
  47277. name: "StateCondition",
  47278. properties: [
  47279. BABYLON.Action._GetTargetProperty(this._target),
  47280. { name: "value", value: this.value }
  47281. ]
  47282. });
  47283. };
  47284. return StateCondition;
  47285. }(Condition));
  47286. BABYLON.StateCondition = StateCondition;
  47287. })(BABYLON || (BABYLON = {}));
  47288. //# sourceMappingURL=babylon.condition.js.map
  47289. var BABYLON;
  47290. (function (BABYLON) {
  47291. var Action = /** @class */ (function () {
  47292. function Action(triggerOptions, condition) {
  47293. this.triggerOptions = triggerOptions;
  47294. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47295. if (triggerOptions.parameter) {
  47296. this.trigger = triggerOptions.trigger;
  47297. this._triggerParameter = triggerOptions.parameter;
  47298. }
  47299. else {
  47300. this.trigger = triggerOptions;
  47301. }
  47302. this._nextActiveAction = this;
  47303. this._condition = condition;
  47304. }
  47305. // Methods
  47306. Action.prototype._prepare = function () {
  47307. };
  47308. Action.prototype.getTriggerParameter = function () {
  47309. return this._triggerParameter;
  47310. };
  47311. Action.prototype._executeCurrent = function (evt) {
  47312. if (this._nextActiveAction._condition) {
  47313. var condition = this._nextActiveAction._condition;
  47314. var currentRenderId = this._actionManager.getScene().getRenderId();
  47315. // We cache the current evaluation for the current frame
  47316. if (condition._evaluationId === currentRenderId) {
  47317. if (!condition._currentResult) {
  47318. return;
  47319. }
  47320. }
  47321. else {
  47322. condition._evaluationId = currentRenderId;
  47323. if (!condition.isValid()) {
  47324. condition._currentResult = false;
  47325. return;
  47326. }
  47327. condition._currentResult = true;
  47328. }
  47329. }
  47330. this.onBeforeExecuteObservable.notifyObservers(this);
  47331. this._nextActiveAction.execute(evt);
  47332. this.skipToNextActiveAction();
  47333. };
  47334. Action.prototype.execute = function (evt) {
  47335. };
  47336. Action.prototype.skipToNextActiveAction = function () {
  47337. if (this._nextActiveAction._child) {
  47338. if (!this._nextActiveAction._child._actionManager) {
  47339. this._nextActiveAction._child._actionManager = this._actionManager;
  47340. }
  47341. this._nextActiveAction = this._nextActiveAction._child;
  47342. }
  47343. else {
  47344. this._nextActiveAction = this;
  47345. }
  47346. };
  47347. Action.prototype.then = function (action) {
  47348. this._child = action;
  47349. action._actionManager = this._actionManager;
  47350. action._prepare();
  47351. return action;
  47352. };
  47353. Action.prototype._getProperty = function (propertyPath) {
  47354. return this._actionManager._getProperty(propertyPath);
  47355. };
  47356. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47357. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47358. };
  47359. Action.prototype.serialize = function (parent) {
  47360. };
  47361. // Called by BABYLON.Action objects in serialize(...). Internal use
  47362. Action.prototype._serialize = function (serializedAction, parent) {
  47363. var serializationObject = {
  47364. type: 1,
  47365. children: [],
  47366. name: serializedAction.name,
  47367. properties: serializedAction.properties || []
  47368. };
  47369. // Serialize child
  47370. if (this._child) {
  47371. this._child.serialize(serializationObject);
  47372. }
  47373. // Check if "this" has a condition
  47374. if (this._condition) {
  47375. var serializedCondition = this._condition.serialize();
  47376. serializedCondition.children.push(serializationObject);
  47377. if (parent) {
  47378. parent.children.push(serializedCondition);
  47379. }
  47380. return serializedCondition;
  47381. }
  47382. if (parent) {
  47383. parent.children.push(serializationObject);
  47384. }
  47385. return serializationObject;
  47386. };
  47387. Action._SerializeValueAsString = function (value) {
  47388. if (typeof value === "number") {
  47389. return value.toString();
  47390. }
  47391. if (typeof value === "boolean") {
  47392. return value ? "true" : "false";
  47393. }
  47394. if (value instanceof BABYLON.Vector2) {
  47395. return value.x + ", " + value.y;
  47396. }
  47397. if (value instanceof BABYLON.Vector3) {
  47398. return value.x + ", " + value.y + ", " + value.z;
  47399. }
  47400. if (value instanceof BABYLON.Color3) {
  47401. return value.r + ", " + value.g + ", " + value.b;
  47402. }
  47403. if (value instanceof BABYLON.Color4) {
  47404. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47405. }
  47406. return value; // string
  47407. };
  47408. Action._GetTargetProperty = function (target) {
  47409. return {
  47410. name: "target",
  47411. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47412. : target instanceof BABYLON.Light ? "LightProperties"
  47413. : target instanceof BABYLON.Camera ? "CameraProperties"
  47414. : "SceneProperties",
  47415. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47416. };
  47417. };
  47418. return Action;
  47419. }());
  47420. BABYLON.Action = Action;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.action.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. /**
  47426. * ActionEvent is the event beint sent when an action is triggered.
  47427. */
  47428. var ActionEvent = /** @class */ (function () {
  47429. /**
  47430. * @param source The mesh or sprite that triggered the action.
  47431. * @param pointerX The X mouse cursor position at the time of the event
  47432. * @param pointerY The Y mouse cursor position at the time of the event
  47433. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47434. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47435. */
  47436. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47437. this.source = source;
  47438. this.pointerX = pointerX;
  47439. this.pointerY = pointerY;
  47440. this.meshUnderPointer = meshUnderPointer;
  47441. this.sourceEvent = sourceEvent;
  47442. this.additionalData = additionalData;
  47443. }
  47444. /**
  47445. * Helper function to auto-create an ActionEvent from a source mesh.
  47446. * @param source The source mesh that triggered the event
  47447. * @param evt {Event} The original (browser) event
  47448. */
  47449. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47450. var scene = source.getScene();
  47451. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47452. };
  47453. /**
  47454. * Helper function to auto-create an ActionEvent from a source mesh.
  47455. * @param source The source sprite that triggered the event
  47456. * @param scene Scene associated with the sprite
  47457. * @param evt {Event} The original (browser) event
  47458. */
  47459. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47460. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47461. };
  47462. /**
  47463. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47464. * @param scene the scene where the event occurred
  47465. * @param evt {Event} The original (browser) event
  47466. */
  47467. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47468. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47469. };
  47470. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47471. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47472. };
  47473. return ActionEvent;
  47474. }());
  47475. BABYLON.ActionEvent = ActionEvent;
  47476. /**
  47477. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47478. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47479. */
  47480. var ActionManager = /** @class */ (function () {
  47481. function ActionManager(scene) {
  47482. // Members
  47483. this.actions = new Array();
  47484. this.hoverCursor = '';
  47485. this._scene = scene;
  47486. scene._actionManagers.push(this);
  47487. }
  47488. Object.defineProperty(ActionManager, "NothingTrigger", {
  47489. get: function () {
  47490. return ActionManager._NothingTrigger;
  47491. },
  47492. enumerable: true,
  47493. configurable: true
  47494. });
  47495. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47496. get: function () {
  47497. return ActionManager._OnPickTrigger;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47503. get: function () {
  47504. return ActionManager._OnLeftPickTrigger;
  47505. },
  47506. enumerable: true,
  47507. configurable: true
  47508. });
  47509. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47510. get: function () {
  47511. return ActionManager._OnRightPickTrigger;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47517. get: function () {
  47518. return ActionManager._OnCenterPickTrigger;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47524. get: function () {
  47525. return ActionManager._OnPickDownTrigger;
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47531. get: function () {
  47532. return ActionManager._OnDoublePickTrigger;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47538. get: function () {
  47539. return ActionManager._OnPickUpTrigger;
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47545. /// This trigger will only be raised if you also declared a OnPickDown
  47546. get: function () {
  47547. return ActionManager._OnPickOutTrigger;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47553. get: function () {
  47554. return ActionManager._OnLongPressTrigger;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47560. get: function () {
  47561. return ActionManager._OnPointerOverTrigger;
  47562. },
  47563. enumerable: true,
  47564. configurable: true
  47565. });
  47566. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47567. get: function () {
  47568. return ActionManager._OnPointerOutTrigger;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47574. get: function () {
  47575. return ActionManager._OnEveryFrameTrigger;
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47581. get: function () {
  47582. return ActionManager._OnIntersectionEnterTrigger;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47588. get: function () {
  47589. return ActionManager._OnIntersectionExitTrigger;
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47595. get: function () {
  47596. return ActionManager._OnKeyDownTrigger;
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47602. get: function () {
  47603. return ActionManager._OnKeyUpTrigger;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. // Methods
  47609. ActionManager.prototype.dispose = function () {
  47610. var index = this._scene._actionManagers.indexOf(this);
  47611. for (var i = 0; i < this.actions.length; i++) {
  47612. var action = this.actions[i];
  47613. ActionManager.Triggers[action.trigger]--;
  47614. if (ActionManager.Triggers[action.trigger] === 0) {
  47615. delete ActionManager.Triggers[action.trigger];
  47616. }
  47617. }
  47618. if (index > -1) {
  47619. this._scene._actionManagers.splice(index, 1);
  47620. }
  47621. };
  47622. ActionManager.prototype.getScene = function () {
  47623. return this._scene;
  47624. };
  47625. /**
  47626. * Does this action manager handles actions of any of the given triggers
  47627. * @param {number[]} triggers - the triggers to be tested
  47628. * @return {boolean} whether one (or more) of the triggers is handeled
  47629. */
  47630. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47631. for (var index = 0; index < this.actions.length; index++) {
  47632. var action = this.actions[index];
  47633. if (triggers.indexOf(action.trigger) > -1) {
  47634. return true;
  47635. }
  47636. }
  47637. return false;
  47638. };
  47639. /**
  47640. * Does this action manager handles actions of a given trigger
  47641. * @param {number} trigger - the trigger to be tested
  47642. * @return {boolean} whether the trigger is handeled
  47643. */
  47644. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47645. for (var index = 0; index < this.actions.length; index++) {
  47646. var action = this.actions[index];
  47647. if (action.trigger === trigger) {
  47648. return true;
  47649. }
  47650. }
  47651. return false;
  47652. };
  47653. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47654. /**
  47655. * Does this action manager has pointer triggers
  47656. * @return {boolean} whether or not it has pointer triggers
  47657. */
  47658. get: function () {
  47659. for (var index = 0; index < this.actions.length; index++) {
  47660. var action = this.actions[index];
  47661. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47662. return true;
  47663. }
  47664. }
  47665. return false;
  47666. },
  47667. enumerable: true,
  47668. configurable: true
  47669. });
  47670. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47671. /**
  47672. * Does this action manager has pick triggers
  47673. * @return {boolean} whether or not it has pick triggers
  47674. */
  47675. get: function () {
  47676. for (var index = 0; index < this.actions.length; index++) {
  47677. var action = this.actions[index];
  47678. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47679. return true;
  47680. }
  47681. }
  47682. return false;
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ActionManager, "HasTriggers", {
  47688. /**
  47689. * Does exist one action manager with at least one trigger
  47690. * @return {boolean} whether or not it exists one action manager with one trigger
  47691. **/
  47692. get: function () {
  47693. for (var t in ActionManager.Triggers) {
  47694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47695. return true;
  47696. }
  47697. }
  47698. return false;
  47699. },
  47700. enumerable: true,
  47701. configurable: true
  47702. });
  47703. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47704. /**
  47705. * Does exist one action manager with at least one pick trigger
  47706. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47707. **/
  47708. get: function () {
  47709. for (var t in ActionManager.Triggers) {
  47710. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47711. var t_int = parseInt(t);
  47712. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47713. return true;
  47714. }
  47715. }
  47716. }
  47717. return false;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. /**
  47723. * Does exist one action manager that handles actions of a given trigger
  47724. * @param {number} trigger - the trigger to be tested
  47725. * @return {boolean} whether the trigger is handeled by at least one action manager
  47726. **/
  47727. ActionManager.HasSpecificTrigger = function (trigger) {
  47728. for (var t in ActionManager.Triggers) {
  47729. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47730. var t_int = parseInt(t);
  47731. if (t_int === trigger) {
  47732. return true;
  47733. }
  47734. }
  47735. }
  47736. return false;
  47737. };
  47738. /**
  47739. * Registers an action to this action manager
  47740. * @param {BABYLON.Action} action - the action to be registered
  47741. * @return {BABYLON.Action} the action amended (prepared) after registration
  47742. */
  47743. ActionManager.prototype.registerAction = function (action) {
  47744. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47745. if (this.getScene().actionManager !== this) {
  47746. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47747. return null;
  47748. }
  47749. }
  47750. this.actions.push(action);
  47751. if (ActionManager.Triggers[action.trigger]) {
  47752. ActionManager.Triggers[action.trigger]++;
  47753. }
  47754. else {
  47755. ActionManager.Triggers[action.trigger] = 1;
  47756. }
  47757. action._actionManager = this;
  47758. action._prepare();
  47759. return action;
  47760. };
  47761. /**
  47762. * Unregisters an action to this action manager
  47763. * @param action The action to be unregistered
  47764. * @return whether the action has been unregistered
  47765. */
  47766. ActionManager.prototype.unregisterAction = function (action) {
  47767. var index = this.actions.indexOf(action);
  47768. if (index !== -1) {
  47769. this.actions.splice(index, 1);
  47770. ActionManager.Triggers[action.trigger] -= 1;
  47771. if (ActionManager.Triggers[action.trigger] === 0) {
  47772. delete ActionManager.Triggers[action.trigger];
  47773. }
  47774. delete action._actionManager;
  47775. return true;
  47776. }
  47777. return false;
  47778. };
  47779. /**
  47780. * Process a specific trigger
  47781. * @param {number} trigger - the trigger to process
  47782. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47783. */
  47784. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47785. for (var index = 0; index < this.actions.length; index++) {
  47786. var action = this.actions[index];
  47787. if (action.trigger === trigger) {
  47788. if (evt) {
  47789. if (trigger === ActionManager.OnKeyUpTrigger
  47790. || trigger === ActionManager.OnKeyDownTrigger) {
  47791. var parameter = action.getTriggerParameter();
  47792. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47793. if (!parameter.toLowerCase) {
  47794. continue;
  47795. }
  47796. var lowerCase = parameter.toLowerCase();
  47797. if (lowerCase !== evt.sourceEvent.key) {
  47798. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47799. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47800. if (actualkey !== lowerCase) {
  47801. continue;
  47802. }
  47803. }
  47804. }
  47805. }
  47806. }
  47807. action._executeCurrent(evt);
  47808. }
  47809. }
  47810. };
  47811. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47812. var properties = propertyPath.split(".");
  47813. for (var index = 0; index < properties.length - 1; index++) {
  47814. target = target[properties[index]];
  47815. }
  47816. return target;
  47817. };
  47818. ActionManager.prototype._getProperty = function (propertyPath) {
  47819. var properties = propertyPath.split(".");
  47820. return properties[properties.length - 1];
  47821. };
  47822. ActionManager.prototype.serialize = function (name) {
  47823. var root = {
  47824. children: new Array(),
  47825. name: name,
  47826. type: 3,
  47827. properties: new Array() // Empty for root but required
  47828. };
  47829. for (var i = 0; i < this.actions.length; i++) {
  47830. var triggerObject = {
  47831. type: 0,
  47832. children: new Array(),
  47833. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47834. properties: new Array()
  47835. };
  47836. var triggerOptions = this.actions[i].triggerOptions;
  47837. if (triggerOptions && typeof triggerOptions !== "number") {
  47838. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47839. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47840. }
  47841. else {
  47842. var parameter = {};
  47843. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47844. if (triggerOptions.parameter.mesh) {
  47845. parameter._meshId = triggerOptions.parameter.mesh.id;
  47846. }
  47847. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47848. }
  47849. }
  47850. // Serialize child action, recursively
  47851. this.actions[i].serialize(triggerObject);
  47852. // Add serialized trigger
  47853. root.children.push(triggerObject);
  47854. }
  47855. return root;
  47856. };
  47857. ActionManager.Parse = function (parsedActions, object, scene) {
  47858. var actionManager = new ActionManager(scene);
  47859. if (object === null)
  47860. scene.actionManager = actionManager;
  47861. else
  47862. object.actionManager = actionManager;
  47863. // instanciate a new object
  47864. var instanciate = function (name, params) {
  47865. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47866. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47867. newInstance.constructor.apply(newInstance, params);
  47868. return newInstance;
  47869. };
  47870. var parseParameter = function (name, value, target, propertyPath) {
  47871. if (propertyPath === null) {
  47872. // String, boolean or float
  47873. var floatValue = parseFloat(value);
  47874. if (value === "true" || value === "false")
  47875. return value === "true";
  47876. else
  47877. return isNaN(floatValue) ? value : floatValue;
  47878. }
  47879. var effectiveTarget = propertyPath.split(".");
  47880. var values = value.split(",");
  47881. // Get effective Target
  47882. for (var i = 0; i < effectiveTarget.length; i++) {
  47883. target = target[effectiveTarget[i]];
  47884. }
  47885. // Return appropriate value with its type
  47886. if (typeof (target) === "boolean")
  47887. return values[0] === "true";
  47888. if (typeof (target) === "string")
  47889. return values[0];
  47890. // Parameters with multiple values such as Vector3 etc.
  47891. var split = new Array();
  47892. for (var i = 0; i < values.length; i++)
  47893. split.push(parseFloat(values[i]));
  47894. if (target instanceof BABYLON.Vector3)
  47895. return BABYLON.Vector3.FromArray(split);
  47896. if (target instanceof BABYLON.Vector4)
  47897. return BABYLON.Vector4.FromArray(split);
  47898. if (target instanceof BABYLON.Color3)
  47899. return BABYLON.Color3.FromArray(split);
  47900. if (target instanceof BABYLON.Color4)
  47901. return BABYLON.Color4.FromArray(split);
  47902. return parseFloat(values[0]);
  47903. };
  47904. // traverse graph per trigger
  47905. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47906. if (combineArray === void 0) { combineArray = null; }
  47907. if (parsedAction.detached)
  47908. return;
  47909. var parameters = new Array();
  47910. var target = null;
  47911. var propertyPath = null;
  47912. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47913. // Parameters
  47914. if (parsedAction.type === 2)
  47915. parameters.push(actionManager);
  47916. else
  47917. parameters.push(trigger);
  47918. if (combine) {
  47919. var actions = new Array();
  47920. for (var j = 0; j < parsedAction.combine.length; j++) {
  47921. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47922. }
  47923. parameters.push(actions);
  47924. }
  47925. else {
  47926. for (var i = 0; i < parsedAction.properties.length; i++) {
  47927. var value = parsedAction.properties[i].value;
  47928. var name = parsedAction.properties[i].name;
  47929. var targetType = parsedAction.properties[i].targetType;
  47930. if (name === "target")
  47931. if (targetType !== null && targetType === "SceneProperties")
  47932. value = target = scene;
  47933. else
  47934. value = target = scene.getNodeByName(value);
  47935. else if (name === "parent")
  47936. value = scene.getNodeByName(value);
  47937. else if (name === "sound")
  47938. value = scene.getSoundByName(value);
  47939. else if (name !== "propertyPath") {
  47940. if (parsedAction.type === 2 && name === "operator")
  47941. value = BABYLON.ValueCondition[value];
  47942. else
  47943. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47944. }
  47945. else {
  47946. propertyPath = value;
  47947. }
  47948. parameters.push(value);
  47949. }
  47950. }
  47951. if (combineArray === null) {
  47952. parameters.push(condition);
  47953. }
  47954. else {
  47955. parameters.push(null);
  47956. }
  47957. // If interpolate value action
  47958. if (parsedAction.name === "InterpolateValueAction") {
  47959. var param = parameters[parameters.length - 2];
  47960. parameters[parameters.length - 1] = param;
  47961. parameters[parameters.length - 2] = condition;
  47962. }
  47963. // Action or condition(s) and not CombineAction
  47964. var newAction = instanciate(parsedAction.name, parameters);
  47965. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47966. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47967. if (action)
  47968. action.then(nothing);
  47969. else
  47970. actionManager.registerAction(nothing);
  47971. action = nothing;
  47972. }
  47973. if (combineArray === null) {
  47974. if (newAction instanceof BABYLON.Condition) {
  47975. condition = newAction;
  47976. newAction = action;
  47977. }
  47978. else {
  47979. condition = null;
  47980. if (action)
  47981. action.then(newAction);
  47982. else
  47983. actionManager.registerAction(newAction);
  47984. }
  47985. }
  47986. else {
  47987. combineArray.push(newAction);
  47988. }
  47989. for (var i = 0; i < parsedAction.children.length; i++)
  47990. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47991. };
  47992. // triggers
  47993. for (var i = 0; i < parsedActions.children.length; i++) {
  47994. var triggerParams;
  47995. var trigger = parsedActions.children[i];
  47996. if (trigger.properties.length > 0) {
  47997. var param = trigger.properties[0].value;
  47998. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47999. if (value._meshId) {
  48000. value.mesh = scene.getMeshByID(value._meshId);
  48001. }
  48002. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48003. }
  48004. else
  48005. triggerParams = ActionManager[trigger.name];
  48006. for (var j = 0; j < trigger.children.length; j++) {
  48007. if (!trigger.detached)
  48008. traverse(trigger.children[j], triggerParams, null, null);
  48009. }
  48010. }
  48011. };
  48012. ActionManager.GetTriggerName = function (trigger) {
  48013. switch (trigger) {
  48014. case 0: return "NothingTrigger";
  48015. case 1: return "OnPickTrigger";
  48016. case 2: return "OnLeftPickTrigger";
  48017. case 3: return "OnRightPickTrigger";
  48018. case 4: return "OnCenterPickTrigger";
  48019. case 5: return "OnPickDownTrigger";
  48020. case 6: return "OnPickUpTrigger";
  48021. case 7: return "OnLongPressTrigger";
  48022. case 8: return "OnPointerOverTrigger";
  48023. case 9: return "OnPointerOutTrigger";
  48024. case 10: return "OnEveryFrameTrigger";
  48025. case 11: return "OnIntersectionEnterTrigger";
  48026. case 12: return "OnIntersectionExitTrigger";
  48027. case 13: return "OnKeyDownTrigger";
  48028. case 14: return "OnKeyUpTrigger";
  48029. case 15: return "OnPickOutTrigger";
  48030. default: return "";
  48031. }
  48032. };
  48033. // Statics
  48034. ActionManager._NothingTrigger = 0;
  48035. ActionManager._OnPickTrigger = 1;
  48036. ActionManager._OnLeftPickTrigger = 2;
  48037. ActionManager._OnRightPickTrigger = 3;
  48038. ActionManager._OnCenterPickTrigger = 4;
  48039. ActionManager._OnPickDownTrigger = 5;
  48040. ActionManager._OnDoublePickTrigger = 6;
  48041. ActionManager._OnPickUpTrigger = 7;
  48042. ActionManager._OnLongPressTrigger = 8;
  48043. ActionManager._OnPointerOverTrigger = 9;
  48044. ActionManager._OnPointerOutTrigger = 10;
  48045. ActionManager._OnEveryFrameTrigger = 11;
  48046. ActionManager._OnIntersectionEnterTrigger = 12;
  48047. ActionManager._OnIntersectionExitTrigger = 13;
  48048. ActionManager._OnKeyDownTrigger = 14;
  48049. ActionManager._OnKeyUpTrigger = 15;
  48050. ActionManager._OnPickOutTrigger = 16;
  48051. ActionManager.Triggers = {};
  48052. return ActionManager;
  48053. }());
  48054. BABYLON.ActionManager = ActionManager;
  48055. })(BABYLON || (BABYLON = {}));
  48056. //# sourceMappingURL=babylon.actionManager.js.map
  48057. var BABYLON;
  48058. (function (BABYLON) {
  48059. var InterpolateValueAction = /** @class */ (function (_super) {
  48060. __extends(InterpolateValueAction, _super);
  48061. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48062. if (duration === void 0) { duration = 1000; }
  48063. var _this = _super.call(this, triggerOptions, condition) || this;
  48064. _this.propertyPath = propertyPath;
  48065. _this.value = value;
  48066. _this.duration = duration;
  48067. _this.stopOtherAnimations = stopOtherAnimations;
  48068. _this.onInterpolationDone = onInterpolationDone;
  48069. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48070. _this._target = _this._effectiveTarget = target;
  48071. return _this;
  48072. }
  48073. InterpolateValueAction.prototype._prepare = function () {
  48074. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48075. this._property = this._getProperty(this.propertyPath);
  48076. };
  48077. InterpolateValueAction.prototype.execute = function () {
  48078. var _this = this;
  48079. var scene = this._actionManager.getScene();
  48080. var keys = [
  48081. {
  48082. frame: 0,
  48083. value: this._effectiveTarget[this._property]
  48084. }, {
  48085. frame: 100,
  48086. value: this.value
  48087. }
  48088. ];
  48089. var dataType;
  48090. if (typeof this.value === "number") {
  48091. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48092. }
  48093. else if (this.value instanceof BABYLON.Color3) {
  48094. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48095. }
  48096. else if (this.value instanceof BABYLON.Vector3) {
  48097. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48098. }
  48099. else if (this.value instanceof BABYLON.Matrix) {
  48100. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48101. }
  48102. else if (this.value instanceof BABYLON.Quaternion) {
  48103. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48104. }
  48105. else {
  48106. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48107. return;
  48108. }
  48109. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48110. animation.setKeys(keys);
  48111. if (this.stopOtherAnimations) {
  48112. scene.stopAnimation(this._effectiveTarget);
  48113. }
  48114. var wrapper = function () {
  48115. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48116. if (_this.onInterpolationDone) {
  48117. _this.onInterpolationDone();
  48118. }
  48119. };
  48120. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48121. };
  48122. InterpolateValueAction.prototype.serialize = function (parent) {
  48123. return _super.prototype._serialize.call(this, {
  48124. name: "InterpolateValueAction",
  48125. properties: [
  48126. BABYLON.Action._GetTargetProperty(this._target),
  48127. { name: "propertyPath", value: this.propertyPath },
  48128. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48129. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48130. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48131. ]
  48132. }, parent);
  48133. };
  48134. return InterpolateValueAction;
  48135. }(BABYLON.Action));
  48136. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48137. })(BABYLON || (BABYLON = {}));
  48138. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48139. var BABYLON;
  48140. (function (BABYLON) {
  48141. var SwitchBooleanAction = /** @class */ (function (_super) {
  48142. __extends(SwitchBooleanAction, _super);
  48143. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48144. var _this = _super.call(this, triggerOptions, condition) || this;
  48145. _this.propertyPath = propertyPath;
  48146. _this._target = _this._effectiveTarget = target;
  48147. return _this;
  48148. }
  48149. SwitchBooleanAction.prototype._prepare = function () {
  48150. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48151. this._property = this._getProperty(this.propertyPath);
  48152. };
  48153. SwitchBooleanAction.prototype.execute = function () {
  48154. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48155. };
  48156. SwitchBooleanAction.prototype.serialize = function (parent) {
  48157. return _super.prototype._serialize.call(this, {
  48158. name: "SwitchBooleanAction",
  48159. properties: [
  48160. BABYLON.Action._GetTargetProperty(this._target),
  48161. { name: "propertyPath", value: this.propertyPath }
  48162. ]
  48163. }, parent);
  48164. };
  48165. return SwitchBooleanAction;
  48166. }(BABYLON.Action));
  48167. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48168. var SetStateAction = /** @class */ (function (_super) {
  48169. __extends(SetStateAction, _super);
  48170. function SetStateAction(triggerOptions, target, value, condition) {
  48171. var _this = _super.call(this, triggerOptions, condition) || this;
  48172. _this.value = value;
  48173. _this._target = target;
  48174. return _this;
  48175. }
  48176. SetStateAction.prototype.execute = function () {
  48177. this._target.state = this.value;
  48178. };
  48179. SetStateAction.prototype.serialize = function (parent) {
  48180. return _super.prototype._serialize.call(this, {
  48181. name: "SetStateAction",
  48182. properties: [
  48183. BABYLON.Action._GetTargetProperty(this._target),
  48184. { name: "value", value: this.value }
  48185. ]
  48186. }, parent);
  48187. };
  48188. return SetStateAction;
  48189. }(BABYLON.Action));
  48190. BABYLON.SetStateAction = SetStateAction;
  48191. var SetValueAction = /** @class */ (function (_super) {
  48192. __extends(SetValueAction, _super);
  48193. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48194. var _this = _super.call(this, triggerOptions, condition) || this;
  48195. _this.propertyPath = propertyPath;
  48196. _this.value = value;
  48197. _this._target = _this._effectiveTarget = target;
  48198. return _this;
  48199. }
  48200. SetValueAction.prototype._prepare = function () {
  48201. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48202. this._property = this._getProperty(this.propertyPath);
  48203. };
  48204. SetValueAction.prototype.execute = function () {
  48205. this._effectiveTarget[this._property] = this.value;
  48206. if (this._target.markAsDirty) {
  48207. this._target.markAsDirty(this._property);
  48208. }
  48209. };
  48210. SetValueAction.prototype.serialize = function (parent) {
  48211. return _super.prototype._serialize.call(this, {
  48212. name: "SetValueAction",
  48213. properties: [
  48214. BABYLON.Action._GetTargetProperty(this._target),
  48215. { name: "propertyPath", value: this.propertyPath },
  48216. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48217. ]
  48218. }, parent);
  48219. };
  48220. return SetValueAction;
  48221. }(BABYLON.Action));
  48222. BABYLON.SetValueAction = SetValueAction;
  48223. var IncrementValueAction = /** @class */ (function (_super) {
  48224. __extends(IncrementValueAction, _super);
  48225. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48226. var _this = _super.call(this, triggerOptions, condition) || this;
  48227. _this.propertyPath = propertyPath;
  48228. _this.value = value;
  48229. _this._target = _this._effectiveTarget = target;
  48230. return _this;
  48231. }
  48232. IncrementValueAction.prototype._prepare = function () {
  48233. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48234. this._property = this._getProperty(this.propertyPath);
  48235. if (typeof this._effectiveTarget[this._property] !== "number") {
  48236. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48237. }
  48238. };
  48239. IncrementValueAction.prototype.execute = function () {
  48240. this._effectiveTarget[this._property] += this.value;
  48241. if (this._target.markAsDirty) {
  48242. this._target.markAsDirty(this._property);
  48243. }
  48244. };
  48245. IncrementValueAction.prototype.serialize = function (parent) {
  48246. return _super.prototype._serialize.call(this, {
  48247. name: "IncrementValueAction",
  48248. properties: [
  48249. BABYLON.Action._GetTargetProperty(this._target),
  48250. { name: "propertyPath", value: this.propertyPath },
  48251. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48252. ]
  48253. }, parent);
  48254. };
  48255. return IncrementValueAction;
  48256. }(BABYLON.Action));
  48257. BABYLON.IncrementValueAction = IncrementValueAction;
  48258. var PlayAnimationAction = /** @class */ (function (_super) {
  48259. __extends(PlayAnimationAction, _super);
  48260. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48261. var _this = _super.call(this, triggerOptions, condition) || this;
  48262. _this.from = from;
  48263. _this.to = to;
  48264. _this.loop = loop;
  48265. _this._target = target;
  48266. return _this;
  48267. }
  48268. PlayAnimationAction.prototype._prepare = function () {
  48269. };
  48270. PlayAnimationAction.prototype.execute = function () {
  48271. var scene = this._actionManager.getScene();
  48272. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48273. };
  48274. PlayAnimationAction.prototype.serialize = function (parent) {
  48275. return _super.prototype._serialize.call(this, {
  48276. name: "PlayAnimationAction",
  48277. properties: [
  48278. BABYLON.Action._GetTargetProperty(this._target),
  48279. { name: "from", value: String(this.from) },
  48280. { name: "to", value: String(this.to) },
  48281. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48282. ]
  48283. }, parent);
  48284. };
  48285. return PlayAnimationAction;
  48286. }(BABYLON.Action));
  48287. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48288. var StopAnimationAction = /** @class */ (function (_super) {
  48289. __extends(StopAnimationAction, _super);
  48290. function StopAnimationAction(triggerOptions, target, condition) {
  48291. var _this = _super.call(this, triggerOptions, condition) || this;
  48292. _this._target = target;
  48293. return _this;
  48294. }
  48295. StopAnimationAction.prototype._prepare = function () {
  48296. };
  48297. StopAnimationAction.prototype.execute = function () {
  48298. var scene = this._actionManager.getScene();
  48299. scene.stopAnimation(this._target);
  48300. };
  48301. StopAnimationAction.prototype.serialize = function (parent) {
  48302. return _super.prototype._serialize.call(this, {
  48303. name: "StopAnimationAction",
  48304. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48305. }, parent);
  48306. };
  48307. return StopAnimationAction;
  48308. }(BABYLON.Action));
  48309. BABYLON.StopAnimationAction = StopAnimationAction;
  48310. var DoNothingAction = /** @class */ (function (_super) {
  48311. __extends(DoNothingAction, _super);
  48312. function DoNothingAction(triggerOptions, condition) {
  48313. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48314. return _super.call(this, triggerOptions, condition) || this;
  48315. }
  48316. DoNothingAction.prototype.execute = function () {
  48317. };
  48318. DoNothingAction.prototype.serialize = function (parent) {
  48319. return _super.prototype._serialize.call(this, {
  48320. name: "DoNothingAction",
  48321. properties: []
  48322. }, parent);
  48323. };
  48324. return DoNothingAction;
  48325. }(BABYLON.Action));
  48326. BABYLON.DoNothingAction = DoNothingAction;
  48327. var CombineAction = /** @class */ (function (_super) {
  48328. __extends(CombineAction, _super);
  48329. function CombineAction(triggerOptions, children, condition) {
  48330. var _this = _super.call(this, triggerOptions, condition) || this;
  48331. _this.children = children;
  48332. return _this;
  48333. }
  48334. CombineAction.prototype._prepare = function () {
  48335. for (var index = 0; index < this.children.length; index++) {
  48336. this.children[index]._actionManager = this._actionManager;
  48337. this.children[index]._prepare();
  48338. }
  48339. };
  48340. CombineAction.prototype.execute = function (evt) {
  48341. for (var index = 0; index < this.children.length; index++) {
  48342. this.children[index].execute(evt);
  48343. }
  48344. };
  48345. CombineAction.prototype.serialize = function (parent) {
  48346. var serializationObject = _super.prototype._serialize.call(this, {
  48347. name: "CombineAction",
  48348. properties: [],
  48349. combine: []
  48350. }, parent);
  48351. for (var i = 0; i < this.children.length; i++) {
  48352. serializationObject.combine.push(this.children[i].serialize(null));
  48353. }
  48354. return serializationObject;
  48355. };
  48356. return CombineAction;
  48357. }(BABYLON.Action));
  48358. BABYLON.CombineAction = CombineAction;
  48359. var ExecuteCodeAction = /** @class */ (function (_super) {
  48360. __extends(ExecuteCodeAction, _super);
  48361. function ExecuteCodeAction(triggerOptions, func, condition) {
  48362. var _this = _super.call(this, triggerOptions, condition) || this;
  48363. _this.func = func;
  48364. return _this;
  48365. }
  48366. ExecuteCodeAction.prototype.execute = function (evt) {
  48367. this.func(evt);
  48368. };
  48369. return ExecuteCodeAction;
  48370. }(BABYLON.Action));
  48371. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48372. var SetParentAction = /** @class */ (function (_super) {
  48373. __extends(SetParentAction, _super);
  48374. function SetParentAction(triggerOptions, target, parent, condition) {
  48375. var _this = _super.call(this, triggerOptions, condition) || this;
  48376. _this._target = target;
  48377. _this._parent = parent;
  48378. return _this;
  48379. }
  48380. SetParentAction.prototype._prepare = function () {
  48381. };
  48382. SetParentAction.prototype.execute = function () {
  48383. if (this._target.parent === this._parent) {
  48384. return;
  48385. }
  48386. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48387. invertParentWorldMatrix.invert();
  48388. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48389. this._target.parent = this._parent;
  48390. };
  48391. SetParentAction.prototype.serialize = function (parent) {
  48392. return _super.prototype._serialize.call(this, {
  48393. name: "SetParentAction",
  48394. properties: [
  48395. BABYLON.Action._GetTargetProperty(this._target),
  48396. BABYLON.Action._GetTargetProperty(this._parent),
  48397. ]
  48398. }, parent);
  48399. };
  48400. return SetParentAction;
  48401. }(BABYLON.Action));
  48402. BABYLON.SetParentAction = SetParentAction;
  48403. var PlaySoundAction = /** @class */ (function (_super) {
  48404. __extends(PlaySoundAction, _super);
  48405. function PlaySoundAction(triggerOptions, sound, condition) {
  48406. var _this = _super.call(this, triggerOptions, condition) || this;
  48407. _this._sound = sound;
  48408. return _this;
  48409. }
  48410. PlaySoundAction.prototype._prepare = function () {
  48411. };
  48412. PlaySoundAction.prototype.execute = function () {
  48413. if (this._sound !== undefined)
  48414. this._sound.play();
  48415. };
  48416. PlaySoundAction.prototype.serialize = function (parent) {
  48417. return _super.prototype._serialize.call(this, {
  48418. name: "PlaySoundAction",
  48419. properties: [{ name: "sound", value: this._sound.name }]
  48420. }, parent);
  48421. };
  48422. return PlaySoundAction;
  48423. }(BABYLON.Action));
  48424. BABYLON.PlaySoundAction = PlaySoundAction;
  48425. var StopSoundAction = /** @class */ (function (_super) {
  48426. __extends(StopSoundAction, _super);
  48427. function StopSoundAction(triggerOptions, sound, condition) {
  48428. var _this = _super.call(this, triggerOptions, condition) || this;
  48429. _this._sound = sound;
  48430. return _this;
  48431. }
  48432. StopSoundAction.prototype._prepare = function () {
  48433. };
  48434. StopSoundAction.prototype.execute = function () {
  48435. if (this._sound !== undefined)
  48436. this._sound.stop();
  48437. };
  48438. StopSoundAction.prototype.serialize = function (parent) {
  48439. return _super.prototype._serialize.call(this, {
  48440. name: "StopSoundAction",
  48441. properties: [{ name: "sound", value: this._sound.name }]
  48442. }, parent);
  48443. };
  48444. return StopSoundAction;
  48445. }(BABYLON.Action));
  48446. BABYLON.StopSoundAction = StopSoundAction;
  48447. })(BABYLON || (BABYLON = {}));
  48448. //# sourceMappingURL=babylon.directActions.js.map
  48449. var BABYLON;
  48450. (function (BABYLON) {
  48451. var SpriteManager = /** @class */ (function () {
  48452. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48453. if (epsilon === void 0) { epsilon = 0.01; }
  48454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48455. this.name = name;
  48456. this.sprites = new Array();
  48457. this.renderingGroupId = 0;
  48458. this.layerMask = 0x0FFFFFFF;
  48459. this.fogEnabled = true;
  48460. this.isPickable = false;
  48461. /**
  48462. * An event triggered when the manager is disposed.
  48463. * @type {BABYLON.Observable}
  48464. */
  48465. this.onDisposeObservable = new BABYLON.Observable();
  48466. this._vertexBuffers = {};
  48467. this._capacity = capacity;
  48468. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48469. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48470. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48471. if (cellSize.width && cellSize.height) {
  48472. this.cellWidth = cellSize.width;
  48473. this.cellHeight = cellSize.height;
  48474. }
  48475. else if (cellSize !== undefined) {
  48476. this.cellWidth = cellSize;
  48477. this.cellHeight = cellSize;
  48478. }
  48479. else {
  48480. return;
  48481. }
  48482. this._epsilon = epsilon;
  48483. this._scene = scene;
  48484. this._scene.spriteManagers.push(this);
  48485. var indices = [];
  48486. var index = 0;
  48487. for (var count = 0; count < capacity; count++) {
  48488. indices.push(index);
  48489. indices.push(index + 1);
  48490. indices.push(index + 2);
  48491. indices.push(index);
  48492. indices.push(index + 2);
  48493. indices.push(index + 3);
  48494. index += 4;
  48495. }
  48496. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48497. // VBO
  48498. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48499. this._vertexData = new Float32Array(capacity * 16 * 4);
  48500. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48501. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48502. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48503. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48504. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48506. this._vertexBuffers["options"] = options;
  48507. this._vertexBuffers["cellInfo"] = cellInfo;
  48508. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48509. // Effects
  48510. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48511. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48512. }
  48513. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48514. set: function (callback) {
  48515. if (this._onDisposeObserver) {
  48516. this.onDisposeObservable.remove(this._onDisposeObserver);
  48517. }
  48518. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48519. },
  48520. enumerable: true,
  48521. configurable: true
  48522. });
  48523. Object.defineProperty(SpriteManager.prototype, "texture", {
  48524. get: function () {
  48525. return this._spriteTexture;
  48526. },
  48527. set: function (value) {
  48528. this._spriteTexture = value;
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48534. var arrayOffset = index * 16;
  48535. if (offsetX === 0)
  48536. offsetX = this._epsilon;
  48537. else if (offsetX === 1)
  48538. offsetX = 1 - this._epsilon;
  48539. if (offsetY === 0)
  48540. offsetY = this._epsilon;
  48541. else if (offsetY === 1)
  48542. offsetY = 1 - this._epsilon;
  48543. this._vertexData[arrayOffset] = sprite.position.x;
  48544. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48545. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48546. this._vertexData[arrayOffset + 3] = sprite.angle;
  48547. this._vertexData[arrayOffset + 4] = sprite.width;
  48548. this._vertexData[arrayOffset + 5] = sprite.height;
  48549. this._vertexData[arrayOffset + 6] = offsetX;
  48550. this._vertexData[arrayOffset + 7] = offsetY;
  48551. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48552. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48553. var offset = (sprite.cellIndex / rowSize) >> 0;
  48554. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48555. this._vertexData[arrayOffset + 11] = offset;
  48556. // Color
  48557. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48558. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48559. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48560. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48561. };
  48562. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48563. var count = Math.min(this._capacity, this.sprites.length);
  48564. var min = BABYLON.Vector3.Zero();
  48565. var max = BABYLON.Vector3.Zero();
  48566. var distance = Number.MAX_VALUE;
  48567. var currentSprite = null;
  48568. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48569. var cameraView = camera.getViewMatrix();
  48570. for (var index = 0; index < count; index++) {
  48571. var sprite = this.sprites[index];
  48572. if (!sprite) {
  48573. continue;
  48574. }
  48575. if (predicate) {
  48576. if (!predicate(sprite)) {
  48577. continue;
  48578. }
  48579. }
  48580. else if (!sprite.isPickable) {
  48581. continue;
  48582. }
  48583. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48584. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48585. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48586. if (ray.intersectsBoxMinMax(min, max)) {
  48587. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48588. if (distance > currentDistance) {
  48589. distance = currentDistance;
  48590. currentSprite = sprite;
  48591. if (fastCheck) {
  48592. break;
  48593. }
  48594. }
  48595. }
  48596. }
  48597. if (currentSprite) {
  48598. var result = new BABYLON.PickingInfo();
  48599. result.hit = true;
  48600. result.pickedSprite = currentSprite;
  48601. result.distance = distance;
  48602. return result;
  48603. }
  48604. return null;
  48605. };
  48606. SpriteManager.prototype.render = function () {
  48607. // Check
  48608. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48609. return;
  48610. var engine = this._scene.getEngine();
  48611. var baseSize = this._spriteTexture.getBaseSize();
  48612. // Sprites
  48613. var deltaTime = engine.getDeltaTime();
  48614. var max = Math.min(this._capacity, this.sprites.length);
  48615. var rowSize = baseSize.width / this.cellWidth;
  48616. var offset = 0;
  48617. for (var index = 0; index < max; index++) {
  48618. var sprite = this.sprites[index];
  48619. if (!sprite) {
  48620. continue;
  48621. }
  48622. sprite._animate(deltaTime);
  48623. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48624. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48625. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48626. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48627. }
  48628. this._buffer.update(this._vertexData);
  48629. // Render
  48630. var effect = this._effectBase;
  48631. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48632. effect = this._effectFog;
  48633. }
  48634. engine.enableEffect(effect);
  48635. var viewMatrix = this._scene.getViewMatrix();
  48636. effect.setTexture("diffuseSampler", this._spriteTexture);
  48637. effect.setMatrix("view", viewMatrix);
  48638. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48639. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48640. // Fog
  48641. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48642. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48643. effect.setColor3("vFogColor", this._scene.fogColor);
  48644. }
  48645. // VBOs
  48646. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48647. // Draw order
  48648. engine.setDepthFunctionToLessOrEqual();
  48649. effect.setBool("alphaTest", true);
  48650. engine.setColorWrite(false);
  48651. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48652. engine.setColorWrite(true);
  48653. effect.setBool("alphaTest", false);
  48654. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48656. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48657. };
  48658. SpriteManager.prototype.dispose = function () {
  48659. if (this._buffer) {
  48660. this._buffer.dispose();
  48661. this._buffer = null;
  48662. }
  48663. if (this._indexBuffer) {
  48664. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48665. this._indexBuffer = null;
  48666. }
  48667. if (this._spriteTexture) {
  48668. this._spriteTexture.dispose();
  48669. this._spriteTexture = null;
  48670. }
  48671. // Remove from scene
  48672. var index = this._scene.spriteManagers.indexOf(this);
  48673. this._scene.spriteManagers.splice(index, 1);
  48674. // Callback
  48675. this.onDisposeObservable.notifyObservers(this);
  48676. this.onDisposeObservable.clear();
  48677. };
  48678. return SpriteManager;
  48679. }());
  48680. BABYLON.SpriteManager = SpriteManager;
  48681. })(BABYLON || (BABYLON = {}));
  48682. //# sourceMappingURL=babylon.spriteManager.js.map
  48683. var BABYLON;
  48684. (function (BABYLON) {
  48685. var Sprite = /** @class */ (function () {
  48686. function Sprite(name, manager) {
  48687. this.name = name;
  48688. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48689. this.width = 1.0;
  48690. this.height = 1.0;
  48691. this.angle = 0;
  48692. this.cellIndex = 0;
  48693. this.invertU = 0;
  48694. this.invertV = 0;
  48695. this.animations = new Array();
  48696. this.isPickable = false;
  48697. this._animationStarted = false;
  48698. this._loopAnimation = false;
  48699. this._fromIndex = 0;
  48700. this._toIndex = 0;
  48701. this._delay = 0;
  48702. this._direction = 1;
  48703. this._time = 0;
  48704. this._manager = manager;
  48705. this._manager.sprites.push(this);
  48706. this.position = BABYLON.Vector3.Zero();
  48707. }
  48708. Object.defineProperty(Sprite.prototype, "size", {
  48709. get: function () {
  48710. return this.width;
  48711. },
  48712. set: function (value) {
  48713. this.width = value;
  48714. this.height = value;
  48715. },
  48716. enumerable: true,
  48717. configurable: true
  48718. });
  48719. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48720. this._fromIndex = from;
  48721. this._toIndex = to;
  48722. this._loopAnimation = loop;
  48723. this._delay = delay;
  48724. this._animationStarted = true;
  48725. this._direction = from < to ? 1 : -1;
  48726. this.cellIndex = from;
  48727. this._time = 0;
  48728. this._onAnimationEnd = onAnimationEnd;
  48729. };
  48730. Sprite.prototype.stopAnimation = function () {
  48731. this._animationStarted = false;
  48732. };
  48733. Sprite.prototype._animate = function (deltaTime) {
  48734. if (!this._animationStarted)
  48735. return;
  48736. this._time += deltaTime;
  48737. if (this._time > this._delay) {
  48738. this._time = this._time % this._delay;
  48739. this.cellIndex += this._direction;
  48740. if (this.cellIndex > this._toIndex) {
  48741. if (this._loopAnimation) {
  48742. this.cellIndex = this._fromIndex;
  48743. }
  48744. else {
  48745. this.cellIndex = this._toIndex;
  48746. this._animationStarted = false;
  48747. if (this._onAnimationEnd) {
  48748. this._onAnimationEnd();
  48749. }
  48750. if (this.disposeWhenFinishedAnimating) {
  48751. this.dispose();
  48752. }
  48753. }
  48754. }
  48755. }
  48756. };
  48757. Sprite.prototype.dispose = function () {
  48758. for (var i = 0; i < this._manager.sprites.length; i++) {
  48759. if (this._manager.sprites[i] == this) {
  48760. this._manager.sprites.splice(i, 1);
  48761. }
  48762. }
  48763. };
  48764. return Sprite;
  48765. }());
  48766. BABYLON.Sprite = Sprite;
  48767. })(BABYLON || (BABYLON = {}));
  48768. //# sourceMappingURL=babylon.sprite.js.map
  48769. var BABYLON;
  48770. (function (BABYLON) {
  48771. var IntersectionInfo = /** @class */ (function () {
  48772. function IntersectionInfo(bu, bv, distance) {
  48773. this.bu = bu;
  48774. this.bv = bv;
  48775. this.distance = distance;
  48776. this.faceId = 0;
  48777. this.subMeshId = 0;
  48778. }
  48779. return IntersectionInfo;
  48780. }());
  48781. BABYLON.IntersectionInfo = IntersectionInfo;
  48782. var PickingInfo = /** @class */ (function () {
  48783. function PickingInfo() {
  48784. this.hit = false;
  48785. this.distance = 0;
  48786. this.pickedPoint = null;
  48787. this.pickedMesh = null;
  48788. this.bu = 0;
  48789. this.bv = 0;
  48790. this.faceId = -1;
  48791. this.subMeshId = 0;
  48792. this.pickedSprite = null;
  48793. }
  48794. // Methods
  48795. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48796. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48797. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48798. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48799. return null;
  48800. }
  48801. var indices = this.pickedMesh.getIndices();
  48802. if (!indices) {
  48803. return null;
  48804. }
  48805. var result;
  48806. if (useVerticesNormals) {
  48807. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48808. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48809. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48810. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48811. normal0 = normal0.scale(this.bu);
  48812. normal1 = normal1.scale(this.bv);
  48813. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48814. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48815. }
  48816. else {
  48817. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48818. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48819. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48820. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48821. var p1p2 = vertex1.subtract(vertex2);
  48822. var p3p2 = vertex3.subtract(vertex2);
  48823. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48824. }
  48825. if (useWorldCoordinates) {
  48826. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48827. }
  48828. return BABYLON.Vector3.Normalize(result);
  48829. };
  48830. PickingInfo.prototype.getTextureCoordinates = function () {
  48831. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48832. return null;
  48833. }
  48834. var indices = this.pickedMesh.getIndices();
  48835. if (!indices) {
  48836. return null;
  48837. }
  48838. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48839. if (!uvs) {
  48840. return null;
  48841. }
  48842. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48843. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48844. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48845. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48846. uv1 = uv1.scale(this.bu);
  48847. uv2 = uv2.scale(this.bv);
  48848. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48849. };
  48850. return PickingInfo;
  48851. }());
  48852. BABYLON.PickingInfo = PickingInfo;
  48853. })(BABYLON || (BABYLON = {}));
  48854. //# sourceMappingURL=babylon.pickingInfo.js.map
  48855. var BABYLON;
  48856. (function (BABYLON) {
  48857. var Ray = /** @class */ (function () {
  48858. function Ray(origin, direction, length) {
  48859. if (length === void 0) { length = Number.MAX_VALUE; }
  48860. this.origin = origin;
  48861. this.direction = direction;
  48862. this.length = length;
  48863. }
  48864. // Methods
  48865. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48866. var d = 0.0;
  48867. var maxValue = Number.MAX_VALUE;
  48868. var inv;
  48869. var min;
  48870. var max;
  48871. var temp;
  48872. if (Math.abs(this.direction.x) < 0.0000001) {
  48873. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48874. return false;
  48875. }
  48876. }
  48877. else {
  48878. inv = 1.0 / this.direction.x;
  48879. min = (minimum.x - this.origin.x) * inv;
  48880. max = (maximum.x - this.origin.x) * inv;
  48881. if (max === -Infinity) {
  48882. max = Infinity;
  48883. }
  48884. if (min > max) {
  48885. temp = min;
  48886. min = max;
  48887. max = temp;
  48888. }
  48889. d = Math.max(min, d);
  48890. maxValue = Math.min(max, maxValue);
  48891. if (d > maxValue) {
  48892. return false;
  48893. }
  48894. }
  48895. if (Math.abs(this.direction.y) < 0.0000001) {
  48896. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48897. return false;
  48898. }
  48899. }
  48900. else {
  48901. inv = 1.0 / this.direction.y;
  48902. min = (minimum.y - this.origin.y) * inv;
  48903. max = (maximum.y - this.origin.y) * inv;
  48904. if (max === -Infinity) {
  48905. max = Infinity;
  48906. }
  48907. if (min > max) {
  48908. temp = min;
  48909. min = max;
  48910. max = temp;
  48911. }
  48912. d = Math.max(min, d);
  48913. maxValue = Math.min(max, maxValue);
  48914. if (d > maxValue) {
  48915. return false;
  48916. }
  48917. }
  48918. if (Math.abs(this.direction.z) < 0.0000001) {
  48919. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48920. return false;
  48921. }
  48922. }
  48923. else {
  48924. inv = 1.0 / this.direction.z;
  48925. min = (minimum.z - this.origin.z) * inv;
  48926. max = (maximum.z - this.origin.z) * inv;
  48927. if (max === -Infinity) {
  48928. max = Infinity;
  48929. }
  48930. if (min > max) {
  48931. temp = min;
  48932. min = max;
  48933. max = temp;
  48934. }
  48935. d = Math.max(min, d);
  48936. maxValue = Math.min(max, maxValue);
  48937. if (d > maxValue) {
  48938. return false;
  48939. }
  48940. }
  48941. return true;
  48942. };
  48943. Ray.prototype.intersectsBox = function (box) {
  48944. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48945. };
  48946. Ray.prototype.intersectsSphere = function (sphere) {
  48947. var x = sphere.center.x - this.origin.x;
  48948. var y = sphere.center.y - this.origin.y;
  48949. var z = sphere.center.z - this.origin.z;
  48950. var pyth = (x * x) + (y * y) + (z * z);
  48951. var rr = sphere.radius * sphere.radius;
  48952. if (pyth <= rr) {
  48953. return true;
  48954. }
  48955. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48956. if (dot < 0.0) {
  48957. return false;
  48958. }
  48959. var temp = pyth - (dot * dot);
  48960. return temp <= rr;
  48961. };
  48962. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48963. if (!this._edge1) {
  48964. this._edge1 = BABYLON.Vector3.Zero();
  48965. this._edge2 = BABYLON.Vector3.Zero();
  48966. this._pvec = BABYLON.Vector3.Zero();
  48967. this._tvec = BABYLON.Vector3.Zero();
  48968. this._qvec = BABYLON.Vector3.Zero();
  48969. }
  48970. vertex1.subtractToRef(vertex0, this._edge1);
  48971. vertex2.subtractToRef(vertex0, this._edge2);
  48972. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48973. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48974. if (det === 0) {
  48975. return null;
  48976. }
  48977. var invdet = 1 / det;
  48978. this.origin.subtractToRef(vertex0, this._tvec);
  48979. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48980. if (bu < 0 || bu > 1.0) {
  48981. return null;
  48982. }
  48983. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48984. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48985. if (bv < 0 || bu + bv > 1.0) {
  48986. return null;
  48987. }
  48988. //check if the distance is longer than the predefined length.
  48989. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48990. if (distance > this.length) {
  48991. return null;
  48992. }
  48993. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48994. };
  48995. Ray.prototype.intersectsPlane = function (plane) {
  48996. var distance;
  48997. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48998. if (Math.abs(result1) < 9.99999997475243E-07) {
  48999. return null;
  49000. }
  49001. else {
  49002. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49003. distance = (-plane.d - result2) / result1;
  49004. if (distance < 0.0) {
  49005. if (distance < -9.99999997475243E-07) {
  49006. return null;
  49007. }
  49008. else {
  49009. return 0;
  49010. }
  49011. }
  49012. return distance;
  49013. }
  49014. };
  49015. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49016. var tm = BABYLON.Tmp.Matrix[0];
  49017. mesh.getWorldMatrix().invertToRef(tm);
  49018. if (this._tmpRay) {
  49019. Ray.TransformToRef(this, tm, this._tmpRay);
  49020. }
  49021. else {
  49022. this._tmpRay = Ray.Transform(this, tm);
  49023. }
  49024. return mesh.intersects(this._tmpRay, fastCheck);
  49025. };
  49026. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49027. if (results) {
  49028. results.length = 0;
  49029. }
  49030. else {
  49031. results = [];
  49032. }
  49033. for (var i = 0; i < meshes.length; i++) {
  49034. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49035. if (pickInfo.hit) {
  49036. results.push(pickInfo);
  49037. }
  49038. }
  49039. results.sort(this._comparePickingInfo);
  49040. return results;
  49041. };
  49042. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49043. if (pickingInfoA.distance < pickingInfoB.distance) {
  49044. return -1;
  49045. }
  49046. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49047. return 1;
  49048. }
  49049. else {
  49050. return 0;
  49051. }
  49052. };
  49053. /**
  49054. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49055. * @param sega the first point of the segment to test the intersection against
  49056. * @param segb the second point of the segment to test the intersection against
  49057. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49058. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49059. */
  49060. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49061. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49062. var u = segb.subtract(sega);
  49063. var v = rsegb.subtract(this.origin);
  49064. var w = sega.subtract(this.origin);
  49065. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49066. var b = BABYLON.Vector3.Dot(u, v);
  49067. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49068. var d = BABYLON.Vector3.Dot(u, w);
  49069. var e = BABYLON.Vector3.Dot(v, w);
  49070. var D = a * c - b * b; // always >= 0
  49071. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49072. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49073. // compute the line parameters of the two closest points
  49074. if (D < Ray.smallnum) {
  49075. sN = 0.0; // force using point P0 on segment S1
  49076. sD = 1.0; // to prevent possible division by 0.0 later
  49077. tN = e;
  49078. tD = c;
  49079. }
  49080. else {
  49081. sN = (b * e - c * d);
  49082. tN = (a * e - b * d);
  49083. if (sN < 0.0) {
  49084. sN = 0.0;
  49085. tN = e;
  49086. tD = c;
  49087. }
  49088. else if (sN > sD) {
  49089. sN = sD;
  49090. tN = e + b;
  49091. tD = c;
  49092. }
  49093. }
  49094. if (tN < 0.0) {
  49095. tN = 0.0;
  49096. // recompute sc for this edge
  49097. if (-d < 0.0) {
  49098. sN = 0.0;
  49099. }
  49100. else if (-d > a)
  49101. sN = sD;
  49102. else {
  49103. sN = -d;
  49104. sD = a;
  49105. }
  49106. }
  49107. else if (tN > tD) {
  49108. tN = tD;
  49109. // recompute sc for this edge
  49110. if ((-d + b) < 0.0) {
  49111. sN = 0;
  49112. }
  49113. else if ((-d + b) > a) {
  49114. sN = sD;
  49115. }
  49116. else {
  49117. sN = (-d + b);
  49118. sD = a;
  49119. }
  49120. }
  49121. // finally do the division to get sc and tc
  49122. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49123. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49124. // get the difference of the two closest points
  49125. var qtc = v.multiplyByFloats(tc, tc, tc);
  49126. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49127. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49128. if (isIntersected) {
  49129. return qtc.length();
  49130. }
  49131. return -1;
  49132. };
  49133. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49134. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49135. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49136. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49137. this.direction.normalize();
  49138. return this;
  49139. };
  49140. // Statics
  49141. Ray.Zero = function () {
  49142. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49143. };
  49144. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49145. var result = Ray.Zero();
  49146. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49147. };
  49148. /**
  49149. * 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
  49150. * transformed to the given world matrix.
  49151. * @param origin The origin point
  49152. * @param end The end point
  49153. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49154. */
  49155. Ray.CreateNewFromTo = function (origin, end, world) {
  49156. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49157. var direction = end.subtract(origin);
  49158. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49159. direction.normalize();
  49160. return Ray.Transform(new Ray(origin, direction, length), world);
  49161. };
  49162. Ray.Transform = function (ray, matrix) {
  49163. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49164. Ray.TransformToRef(ray, matrix, result);
  49165. return result;
  49166. };
  49167. Ray.TransformToRef = function (ray, matrix, result) {
  49168. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49169. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49170. result.length = ray.length;
  49171. var dir = result.direction;
  49172. var len = dir.length();
  49173. if (!(len === 0 || len === 1)) {
  49174. var num = 1.0 / len;
  49175. dir.x *= num;
  49176. dir.y *= num;
  49177. dir.z *= num;
  49178. result.length *= len;
  49179. }
  49180. };
  49181. Ray.smallnum = 0.00000001;
  49182. Ray.rayl = 10e8;
  49183. return Ray;
  49184. }());
  49185. BABYLON.Ray = Ray;
  49186. })(BABYLON || (BABYLON = {}));
  49187. //# sourceMappingURL=babylon.ray.js.map
  49188. var BABYLON;
  49189. (function (BABYLON) {
  49190. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49191. if (boxMin.x > sphereCenter.x + sphereRadius)
  49192. return false;
  49193. if (sphereCenter.x - sphereRadius > boxMax.x)
  49194. return false;
  49195. if (boxMin.y > sphereCenter.y + sphereRadius)
  49196. return false;
  49197. if (sphereCenter.y - sphereRadius > boxMax.y)
  49198. return false;
  49199. if (boxMin.z > sphereCenter.z + sphereRadius)
  49200. return false;
  49201. if (sphereCenter.z - sphereRadius > boxMax.z)
  49202. return false;
  49203. return true;
  49204. };
  49205. var getLowestRoot = (function () {
  49206. var result = { root: 0, found: false };
  49207. return function (a, b, c, maxR) {
  49208. result.root = 0;
  49209. result.found = false;
  49210. var determinant = b * b - 4.0 * a * c;
  49211. if (determinant < 0)
  49212. return result;
  49213. var sqrtD = Math.sqrt(determinant);
  49214. var r1 = (-b - sqrtD) / (2.0 * a);
  49215. var r2 = (-b + sqrtD) / (2.0 * a);
  49216. if (r1 > r2) {
  49217. var temp = r2;
  49218. r2 = r1;
  49219. r1 = temp;
  49220. }
  49221. if (r1 > 0 && r1 < maxR) {
  49222. result.root = r1;
  49223. result.found = true;
  49224. return result;
  49225. }
  49226. if (r2 > 0 && r2 < maxR) {
  49227. result.root = r2;
  49228. result.found = true;
  49229. return result;
  49230. }
  49231. return result;
  49232. };
  49233. })();
  49234. var Collider = /** @class */ (function () {
  49235. function Collider() {
  49236. this._collisionPoint = BABYLON.Vector3.Zero();
  49237. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49238. this._tempVector = BABYLON.Vector3.Zero();
  49239. this._tempVector2 = BABYLON.Vector3.Zero();
  49240. this._tempVector3 = BABYLON.Vector3.Zero();
  49241. this._tempVector4 = BABYLON.Vector3.Zero();
  49242. this._edge = BABYLON.Vector3.Zero();
  49243. this._baseToVertex = BABYLON.Vector3.Zero();
  49244. this._destinationPoint = BABYLON.Vector3.Zero();
  49245. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49246. this._displacementVector = BABYLON.Vector3.Zero();
  49247. this._radius = BABYLON.Vector3.One();
  49248. this._retry = 0;
  49249. this._basePointWorld = BABYLON.Vector3.Zero();
  49250. this._velocityWorld = BABYLON.Vector3.Zero();
  49251. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49252. this._collisionMask = -1;
  49253. }
  49254. Object.defineProperty(Collider.prototype, "collisionMask", {
  49255. get: function () {
  49256. return this._collisionMask;
  49257. },
  49258. set: function (mask) {
  49259. this._collisionMask = !isNaN(mask) ? mask : -1;
  49260. },
  49261. enumerable: true,
  49262. configurable: true
  49263. });
  49264. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49265. /**
  49266. * Gets the plane normal used to compute the sliding response (in local space)
  49267. */
  49268. get: function () {
  49269. return this._slidePlaneNormal;
  49270. },
  49271. enumerable: true,
  49272. configurable: true
  49273. });
  49274. // Methods
  49275. Collider.prototype._initialize = function (source, dir, e) {
  49276. this._velocity = dir;
  49277. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49278. this._basePoint = source;
  49279. source.multiplyToRef(this._radius, this._basePointWorld);
  49280. dir.multiplyToRef(this._radius, this._velocityWorld);
  49281. this._velocityWorldLength = this._velocityWorld.length();
  49282. this._epsilon = e;
  49283. this.collisionFound = false;
  49284. };
  49285. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49286. pa.subtractToRef(point, this._tempVector);
  49287. pb.subtractToRef(point, this._tempVector2);
  49288. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49289. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49290. if (d < 0)
  49291. return false;
  49292. pc.subtractToRef(point, this._tempVector3);
  49293. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49294. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49295. if (d < 0)
  49296. return false;
  49297. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49298. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49299. return d >= 0;
  49300. };
  49301. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49302. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49303. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49304. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49305. return false;
  49306. }
  49307. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49308. return false;
  49309. return true;
  49310. };
  49311. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49312. var t0;
  49313. var embeddedInPlane = false;
  49314. //defensive programming, actually not needed.
  49315. if (!trianglePlaneArray) {
  49316. trianglePlaneArray = [];
  49317. }
  49318. if (!trianglePlaneArray[faceIndex]) {
  49319. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49320. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49321. }
  49322. var trianglePlane = trianglePlaneArray[faceIndex];
  49323. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49324. return;
  49325. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49326. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49327. if (normalDotVelocity == 0) {
  49328. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49329. return;
  49330. embeddedInPlane = true;
  49331. t0 = 0;
  49332. }
  49333. else {
  49334. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49335. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49336. if (t0 > t1) {
  49337. var temp = t1;
  49338. t1 = t0;
  49339. t0 = temp;
  49340. }
  49341. if (t0 > 1.0 || t1 < 0.0)
  49342. return;
  49343. if (t0 < 0)
  49344. t0 = 0;
  49345. if (t0 > 1.0)
  49346. t0 = 1.0;
  49347. }
  49348. this._collisionPoint.copyFromFloats(0, 0, 0);
  49349. var found = false;
  49350. var t = 1.0;
  49351. if (!embeddedInPlane) {
  49352. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49353. this._velocity.scaleToRef(t0, this._tempVector);
  49354. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49355. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49356. found = true;
  49357. t = t0;
  49358. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49359. }
  49360. }
  49361. if (!found) {
  49362. var velocitySquaredLength = this._velocity.lengthSquared();
  49363. var a = velocitySquaredLength;
  49364. this._basePoint.subtractToRef(p1, this._tempVector);
  49365. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49366. var c = this._tempVector.lengthSquared() - 1.0;
  49367. var lowestRoot = getLowestRoot(a, b, c, t);
  49368. if (lowestRoot.found) {
  49369. t = lowestRoot.root;
  49370. found = true;
  49371. this._collisionPoint.copyFrom(p1);
  49372. }
  49373. this._basePoint.subtractToRef(p2, this._tempVector);
  49374. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49375. c = this._tempVector.lengthSquared() - 1.0;
  49376. lowestRoot = getLowestRoot(a, b, c, t);
  49377. if (lowestRoot.found) {
  49378. t = lowestRoot.root;
  49379. found = true;
  49380. this._collisionPoint.copyFrom(p2);
  49381. }
  49382. this._basePoint.subtractToRef(p3, this._tempVector);
  49383. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49384. c = this._tempVector.lengthSquared() - 1.0;
  49385. lowestRoot = getLowestRoot(a, b, c, t);
  49386. if (lowestRoot.found) {
  49387. t = lowestRoot.root;
  49388. found = true;
  49389. this._collisionPoint.copyFrom(p3);
  49390. }
  49391. p2.subtractToRef(p1, this._edge);
  49392. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49393. var edgeSquaredLength = this._edge.lengthSquared();
  49394. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49395. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49396. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49397. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49398. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49399. lowestRoot = getLowestRoot(a, b, c, t);
  49400. if (lowestRoot.found) {
  49401. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49402. if (f >= 0.0 && f <= 1.0) {
  49403. t = lowestRoot.root;
  49404. found = true;
  49405. this._edge.scaleInPlace(f);
  49406. p1.addToRef(this._edge, this._collisionPoint);
  49407. }
  49408. }
  49409. p3.subtractToRef(p2, this._edge);
  49410. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49411. edgeSquaredLength = this._edge.lengthSquared();
  49412. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49413. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49414. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49415. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49416. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49417. lowestRoot = getLowestRoot(a, b, c, t);
  49418. if (lowestRoot.found) {
  49419. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49420. if (f >= 0.0 && f <= 1.0) {
  49421. t = lowestRoot.root;
  49422. found = true;
  49423. this._edge.scaleInPlace(f);
  49424. p2.addToRef(this._edge, this._collisionPoint);
  49425. }
  49426. }
  49427. p1.subtractToRef(p3, this._edge);
  49428. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49429. edgeSquaredLength = this._edge.lengthSquared();
  49430. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49431. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49432. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49433. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49434. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49435. lowestRoot = getLowestRoot(a, b, c, t);
  49436. if (lowestRoot.found) {
  49437. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49438. if (f >= 0.0 && f <= 1.0) {
  49439. t = lowestRoot.root;
  49440. found = true;
  49441. this._edge.scaleInPlace(f);
  49442. p3.addToRef(this._edge, this._collisionPoint);
  49443. }
  49444. }
  49445. }
  49446. if (found) {
  49447. var distToCollision = t * this._velocity.length();
  49448. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49449. if (!this.intersectionPoint) {
  49450. this.intersectionPoint = this._collisionPoint.clone();
  49451. }
  49452. else {
  49453. this.intersectionPoint.copyFrom(this._collisionPoint);
  49454. }
  49455. this._nearestDistance = distToCollision;
  49456. this.collisionFound = true;
  49457. }
  49458. }
  49459. };
  49460. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49461. for (var i = indexStart; i < indexEnd; i += 3) {
  49462. var p1 = pts[indices[i] - decal];
  49463. var p2 = pts[indices[i + 1] - decal];
  49464. var p3 = pts[indices[i + 2] - decal];
  49465. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49466. }
  49467. };
  49468. Collider.prototype._getResponse = function (pos, vel) {
  49469. pos.addToRef(vel, this._destinationPoint);
  49470. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49471. this._basePoint.addToRef(vel, pos);
  49472. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49473. this._slidePlaneNormal.normalize();
  49474. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49475. pos.addInPlace(this._displacementVector);
  49476. this.intersectionPoint.addInPlace(this._displacementVector);
  49477. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49478. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49479. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49480. };
  49481. return Collider;
  49482. }());
  49483. BABYLON.Collider = Collider;
  49484. })(BABYLON || (BABYLON = {}));
  49485. //# sourceMappingURL=babylon.collider.js.map
  49486. var BABYLON;
  49487. (function (BABYLON) {
  49488. //WebWorker code will be inserted to this variable.
  49489. BABYLON.CollisionWorker = "";
  49490. var WorkerTaskType;
  49491. (function (WorkerTaskType) {
  49492. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49493. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49494. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49495. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49496. var WorkerReplyType;
  49497. (function (WorkerReplyType) {
  49498. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49499. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49500. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49501. var CollisionCoordinatorWorker = /** @class */ (function () {
  49502. function CollisionCoordinatorWorker() {
  49503. var _this = this;
  49504. this._scaledPosition = BABYLON.Vector3.Zero();
  49505. this._scaledVelocity = BABYLON.Vector3.Zero();
  49506. this.onMeshUpdated = function (transformNode) {
  49507. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49508. };
  49509. this.onGeometryUpdated = function (geometry) {
  49510. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49511. };
  49512. this._afterRender = function () {
  49513. if (!_this._init)
  49514. return;
  49515. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49516. return;
  49517. }
  49518. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49519. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49520. if (_this._runningUpdated > 4) {
  49521. return;
  49522. }
  49523. ++_this._runningUpdated;
  49524. var payload = {
  49525. updatedMeshes: _this._addUpdateMeshesList,
  49526. updatedGeometries: _this._addUpdateGeometriesList,
  49527. removedGeometries: _this._toRemoveGeometryArray,
  49528. removedMeshes: _this._toRemoveMeshesArray
  49529. };
  49530. var message = {
  49531. payload: payload,
  49532. taskType: WorkerTaskType.UPDATE
  49533. };
  49534. var serializable = [];
  49535. for (var id in payload.updatedGeometries) {
  49536. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49537. //prepare transferables
  49538. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49539. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49540. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49541. }
  49542. }
  49543. _this._worker.postMessage(message, serializable);
  49544. _this._addUpdateMeshesList = {};
  49545. _this._addUpdateGeometriesList = {};
  49546. _this._toRemoveGeometryArray = [];
  49547. _this._toRemoveMeshesArray = [];
  49548. };
  49549. this._onMessageFromWorker = function (e) {
  49550. var returnData = e.data;
  49551. if (returnData.error != WorkerReplyType.SUCCESS) {
  49552. //TODO what errors can be returned from the worker?
  49553. BABYLON.Tools.Warn("error returned from worker!");
  49554. return;
  49555. }
  49556. switch (returnData.taskType) {
  49557. case WorkerTaskType.INIT:
  49558. _this._init = true;
  49559. //Update the worked with ALL of the scene's current state
  49560. _this._scene.meshes.forEach(function (mesh) {
  49561. _this.onMeshAdded(mesh);
  49562. });
  49563. _this._scene.getGeometries().forEach(function (geometry) {
  49564. _this.onGeometryAdded(geometry);
  49565. });
  49566. break;
  49567. case WorkerTaskType.UPDATE:
  49568. _this._runningUpdated--;
  49569. break;
  49570. case WorkerTaskType.COLLIDE:
  49571. var returnPayload = returnData.payload;
  49572. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49573. return;
  49574. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49575. if (callback) {
  49576. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49577. if (mesh) {
  49578. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49579. }
  49580. }
  49581. //cleanup
  49582. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49583. break;
  49584. }
  49585. };
  49586. this._collisionsCallbackArray = [];
  49587. this._init = false;
  49588. this._runningUpdated = 0;
  49589. this._addUpdateMeshesList = {};
  49590. this._addUpdateGeometriesList = {};
  49591. this._toRemoveGeometryArray = [];
  49592. this._toRemoveMeshesArray = [];
  49593. }
  49594. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49595. if (!this._init)
  49596. return;
  49597. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49598. return;
  49599. position.divideToRef(collider._radius, this._scaledPosition);
  49600. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49601. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49602. var payload = {
  49603. collider: {
  49604. position: this._scaledPosition.asArray(),
  49605. velocity: this._scaledVelocity.asArray(),
  49606. radius: collider._radius.asArray()
  49607. },
  49608. collisionId: collisionIndex,
  49609. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49610. maximumRetry: maximumRetry
  49611. };
  49612. var message = {
  49613. payload: payload,
  49614. taskType: WorkerTaskType.COLLIDE
  49615. };
  49616. this._worker.postMessage(message);
  49617. };
  49618. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49619. this._scene = scene;
  49620. this._scene.registerAfterRender(this._afterRender);
  49621. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49622. this._worker = new Worker(workerUrl);
  49623. this._worker.onmessage = this._onMessageFromWorker;
  49624. var message = {
  49625. payload: {},
  49626. taskType: WorkerTaskType.INIT
  49627. };
  49628. this._worker.postMessage(message);
  49629. };
  49630. CollisionCoordinatorWorker.prototype.destroy = function () {
  49631. this._scene.unregisterAfterRender(this._afterRender);
  49632. this._worker.terminate();
  49633. };
  49634. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49635. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49636. this.onMeshUpdated(mesh);
  49637. };
  49638. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49639. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49640. };
  49641. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49642. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49643. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49644. this.onGeometryUpdated(geometry);
  49645. };
  49646. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49647. this._toRemoveGeometryArray.push(geometry.id);
  49648. };
  49649. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49650. var submeshes = [];
  49651. if (mesh.subMeshes) {
  49652. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49653. var boundingInfo = sm.getBoundingInfo();
  49654. return {
  49655. position: idx,
  49656. verticesStart: sm.verticesStart,
  49657. verticesCount: sm.verticesCount,
  49658. indexStart: sm.indexStart,
  49659. indexCount: sm.indexCount,
  49660. hasMaterial: !!sm.getMaterial(),
  49661. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49662. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49663. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49664. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49665. };
  49666. });
  49667. }
  49668. var geometryId = null;
  49669. if (mesh instanceof BABYLON.Mesh) {
  49670. var geometry = mesh.geometry;
  49671. geometryId = geometry ? geometry.id : null;
  49672. }
  49673. else if (mesh instanceof BABYLON.InstancedMesh) {
  49674. var geometry = mesh.sourceMesh.geometry;
  49675. geometryId = geometry ? geometry.id : null;
  49676. }
  49677. var boundingInfo = mesh.getBoundingInfo();
  49678. return {
  49679. uniqueId: mesh.uniqueId,
  49680. id: mesh.id,
  49681. name: mesh.name,
  49682. geometryId: geometryId,
  49683. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49684. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49685. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49686. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49687. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49688. subMeshes: submeshes,
  49689. checkCollisions: mesh.checkCollisions
  49690. };
  49691. };
  49692. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49693. return {
  49694. id: geometry.id,
  49695. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49696. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49697. indices: new Uint32Array(geometry.getIndices() || []),
  49698. };
  49699. };
  49700. return CollisionCoordinatorWorker;
  49701. }());
  49702. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49703. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49704. function CollisionCoordinatorLegacy() {
  49705. this._scaledPosition = BABYLON.Vector3.Zero();
  49706. this._scaledVelocity = BABYLON.Vector3.Zero();
  49707. this._finalPosition = BABYLON.Vector3.Zero();
  49708. }
  49709. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49710. position.divideToRef(collider._radius, this._scaledPosition);
  49711. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49712. collider.collidedMesh = null;
  49713. collider._retry = 0;
  49714. collider._initialVelocity = this._scaledVelocity;
  49715. collider._initialPosition = this._scaledPosition;
  49716. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49717. this._finalPosition.multiplyInPlace(collider._radius);
  49718. //run the callback
  49719. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49720. };
  49721. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49722. this._scene = scene;
  49723. };
  49724. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49725. //Legacy need no destruction method.
  49726. };
  49727. //No update in legacy mode
  49728. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49729. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49730. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49731. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49732. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49733. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49734. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49735. if (excludedMesh === void 0) { excludedMesh = null; }
  49736. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49737. if (collider._retry >= maximumRetry) {
  49738. finalPosition.copyFrom(position);
  49739. return;
  49740. }
  49741. // Check if this is a mesh else camera or -1
  49742. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49743. collider._initialize(position, velocity, closeDistance);
  49744. // Check all meshes
  49745. for (var index = 0; index < this._scene.meshes.length; index++) {
  49746. var mesh = this._scene.meshes[index];
  49747. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49748. mesh._checkCollision(collider);
  49749. }
  49750. }
  49751. if (!collider.collisionFound) {
  49752. position.addToRef(velocity, finalPosition);
  49753. return;
  49754. }
  49755. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49756. collider._getResponse(position, velocity);
  49757. }
  49758. if (velocity.length() <= closeDistance) {
  49759. finalPosition.copyFrom(position);
  49760. return;
  49761. }
  49762. collider._retry++;
  49763. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49764. };
  49765. return CollisionCoordinatorLegacy;
  49766. }());
  49767. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49768. })(BABYLON || (BABYLON = {}));
  49769. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49770. var BABYLON;
  49771. (function (BABYLON) {
  49772. /**
  49773. * A particle represents one of the element emitted by a particle system.
  49774. * This is mainly define by its coordinates, direction, velocity and age.
  49775. */
  49776. var Particle = /** @class */ (function () {
  49777. /**
  49778. * Creates a new instance of @see Particle
  49779. * @param particleSystem the particle system the particle belongs to
  49780. */
  49781. function Particle(particleSystem) {
  49782. this.particleSystem = particleSystem;
  49783. /**
  49784. * The world position of the particle in the scene.
  49785. */
  49786. this.position = BABYLON.Vector3.Zero();
  49787. /**
  49788. * The world direction of the particle in the scene.
  49789. */
  49790. this.direction = BABYLON.Vector3.Zero();
  49791. /**
  49792. * The color of the particle.
  49793. */
  49794. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49795. /**
  49796. * The color change of the particle per step.
  49797. */
  49798. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49799. /**
  49800. * Defines how long will the life of the particle be.
  49801. */
  49802. this.lifeTime = 1.0;
  49803. /**
  49804. * The current age of the particle.
  49805. */
  49806. this.age = 0;
  49807. /**
  49808. * The current size of the particle.
  49809. */
  49810. this.size = 0;
  49811. /**
  49812. * The current angle of the particle.
  49813. */
  49814. this.angle = 0;
  49815. /**
  49816. * Defines how fast is the angle changing.
  49817. */
  49818. this.angularSpeed = 0;
  49819. /**
  49820. * Defines the cell index used by the particle to be rendered from a sprite.
  49821. */
  49822. this.cellIndex = 0;
  49823. this._currentFrameCounter = 0;
  49824. if (!this.particleSystem.isAnimationSheetEnabled) {
  49825. return;
  49826. }
  49827. this.cellIndex = this.particleSystem.startSpriteCellID;
  49828. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49829. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49830. }
  49831. else {
  49832. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49833. }
  49834. }
  49835. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49836. // (ageOffset / scaledUpdateSpeed) / available cells
  49837. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49838. this._currentFrameCounter += scaledUpdateSpeed;
  49839. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49840. this._currentFrameCounter = 0;
  49841. this.cellIndex++;
  49842. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49843. this.cellIndex = this.particleSystem.endSpriteCellID;
  49844. }
  49845. }
  49846. };
  49847. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49848. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49849. this.cellIndex++;
  49850. this._currentFrameCounter = 0;
  49851. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49852. if (this.particleSystem.spriteCellLoop) {
  49853. this.cellIndex = this.particleSystem.startSpriteCellID;
  49854. }
  49855. else {
  49856. this.cellIndex = this.particleSystem.endSpriteCellID;
  49857. }
  49858. }
  49859. }
  49860. else {
  49861. this._currentFrameCounter++;
  49862. }
  49863. };
  49864. /**
  49865. * Copy the properties of particle to another one.
  49866. * @param other the particle to copy the information to.
  49867. */
  49868. Particle.prototype.copyTo = function (other) {
  49869. other.position.copyFrom(this.position);
  49870. other.direction.copyFrom(this.direction);
  49871. other.color.copyFrom(this.color);
  49872. other.colorStep.copyFrom(this.colorStep);
  49873. other.lifeTime = this.lifeTime;
  49874. other.age = this.age;
  49875. other.size = this.size;
  49876. other.angle = this.angle;
  49877. other.angularSpeed = this.angularSpeed;
  49878. other.particleSystem = this.particleSystem;
  49879. other.cellIndex = this.cellIndex;
  49880. };
  49881. return Particle;
  49882. }());
  49883. BABYLON.Particle = Particle;
  49884. })(BABYLON || (BABYLON = {}));
  49885. //# sourceMappingURL=babylon.particle.js.map
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. /**
  49889. * This represents a particle system in Babylon.
  49890. * 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.
  49891. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49892. * @example https://doc.babylonjs.com/babylon101/particles
  49893. */
  49894. var ParticleSystem = /** @class */ (function () {
  49895. /**
  49896. * Instantiates a particle system.
  49897. * 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.
  49898. * @param name The name of the particle system
  49899. * @param capacity The max number of particles alive at the same time
  49900. * @param scene The scene the particle system belongs to
  49901. * @param customEffect a custom effect used to change the way particles are rendered by default
  49902. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49903. * @param epsilon Offset used to render the particles
  49904. */
  49905. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49906. if (customEffect === void 0) { customEffect = null; }
  49907. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49908. if (epsilon === void 0) { epsilon = 0.01; }
  49909. var _this = this;
  49910. /**
  49911. * List of animations used by the particle system.
  49912. */
  49913. this.animations = [];
  49914. /**
  49915. * The rendering group used by the Particle system to chose when to render.
  49916. */
  49917. this.renderingGroupId = 0;
  49918. /**
  49919. * The emitter represents the Mesh or position we are attaching the particle system to.
  49920. */
  49921. this.emitter = null;
  49922. /**
  49923. * The density of particles, the rate of particle flow
  49924. */
  49925. this.emitRate = 10;
  49926. /**
  49927. * If you want to launch only a few particles at once, that can be done, as well.
  49928. */
  49929. this.manualEmitCount = -1;
  49930. /**
  49931. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49932. */
  49933. this.updateSpeed = 0.01;
  49934. /**
  49935. * The amount of time the particle system is running (depends of the overall speed above).
  49936. */
  49937. this.targetStopDuration = 0;
  49938. /**
  49939. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49940. */
  49941. this.disposeOnStop = false;
  49942. /**
  49943. * Minimum power of emitting particles.
  49944. */
  49945. this.minEmitPower = 1;
  49946. /**
  49947. * Maximum power of emitting particles.
  49948. */
  49949. this.maxEmitPower = 1;
  49950. /**
  49951. * Minimum life time of emitting particles.
  49952. */
  49953. this.minLifeTime = 1;
  49954. /**
  49955. * Maximum life time of emitting particles.
  49956. */
  49957. this.maxLifeTime = 1;
  49958. /**
  49959. * Minimum Size of emitting particles.
  49960. */
  49961. this.minSize = 1;
  49962. /**
  49963. * Maximum Size of emitting particles.
  49964. */
  49965. this.maxSize = 1;
  49966. /**
  49967. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49968. */
  49969. this.minAngularSpeed = 0;
  49970. /**
  49971. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49972. */
  49973. this.maxAngularSpeed = 0;
  49974. /**
  49975. * The layer mask we are rendering the particles through.
  49976. */
  49977. this.layerMask = 0x0FFFFFFF;
  49978. /**
  49979. * This can help using your own shader to render the particle system.
  49980. * The according effect will be created
  49981. */
  49982. this.customShader = null;
  49983. /**
  49984. * By default particle system starts as soon as they are created. This prevents the
  49985. * automatic start to happen and let you decide when to start emitting particles.
  49986. */
  49987. this.preventAutoStart = false;
  49988. /**
  49989. * Callback triggered when the particle animation is ending.
  49990. */
  49991. this.onAnimationEnd = null;
  49992. /**
  49993. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49994. */
  49995. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49996. /**
  49997. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49998. * to override the particles.
  49999. */
  50000. this.forceDepthWrite = false;
  50001. /**
  50002. * You can use gravity if you want to give an orientation to your particles.
  50003. */
  50004. this.gravity = BABYLON.Vector3.Zero();
  50005. /**
  50006. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50007. */
  50008. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50009. /**
  50010. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50011. */
  50012. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50013. /**
  50014. * 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.
  50015. */
  50016. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50017. /**
  50018. * 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.
  50019. */
  50020. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50021. /**
  50022. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50023. */
  50024. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50025. /**
  50026. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50027. */
  50028. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50029. /**
  50030. * Color the particle will have at the end of its lifetime.
  50031. */
  50032. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50033. /**
  50034. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50035. */
  50036. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50037. /**
  50038. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50039. */
  50040. this.spriteCellLoop = true;
  50041. /**
  50042. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50043. */
  50044. this.spriteCellChangeSpeed = 0;
  50045. /**
  50046. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50047. */
  50048. this.startSpriteCellID = 0;
  50049. /**
  50050. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50051. */
  50052. this.endSpriteCellID = 0;
  50053. /**
  50054. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50055. */
  50056. this.spriteCellWidth = 0;
  50057. /**
  50058. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50059. */
  50060. this.spriteCellHeight = 0;
  50061. /**
  50062. * An event triggered when the system is disposed.
  50063. */
  50064. this.onDisposeObservable = new BABYLON.Observable();
  50065. this._particles = new Array();
  50066. this._stockParticles = new Array();
  50067. this._newPartsExcess = 0;
  50068. this._vertexBuffers = {};
  50069. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50070. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50071. this._scaledDirection = BABYLON.Vector3.Zero();
  50072. this._scaledGravity = BABYLON.Vector3.Zero();
  50073. this._currentRenderId = -1;
  50074. this._started = false;
  50075. this._stopped = false;
  50076. this._actualFrame = 0;
  50077. this._vertexBufferSize = 11;
  50078. this._appendParticleVertexes = null;
  50079. this.id = name;
  50080. this.name = name;
  50081. this._capacity = capacity;
  50082. this._epsilon = epsilon;
  50083. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50084. if (isAnimationSheetEnabled) {
  50085. this._vertexBufferSize = 12;
  50086. }
  50087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50088. this._customEffect = customEffect;
  50089. scene.particleSystems.push(this);
  50090. this._createIndexBuffer();
  50091. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50092. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50093. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50094. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50095. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50096. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50097. if (this._isAnimationSheetEnabled) {
  50098. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50099. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50100. }
  50101. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50102. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50103. this._vertexBuffers["options"] = options;
  50104. // Default behaviors
  50105. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50106. this.updateFunction = function (particles) {
  50107. for (var index = 0; index < particles.length; index++) {
  50108. var particle = particles[index];
  50109. particle.age += _this._scaledUpdateSpeed;
  50110. if (particle.age >= particle.lifeTime) {
  50111. _this.recycleParticle(particle);
  50112. index--;
  50113. continue;
  50114. }
  50115. else {
  50116. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50117. particle.color.addInPlace(_this._scaledColorStep);
  50118. if (particle.color.a < 0)
  50119. particle.color.a = 0;
  50120. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50121. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50122. particle.position.addInPlace(_this._scaledDirection);
  50123. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50124. particle.direction.addInPlace(_this._scaledGravity);
  50125. if (_this._isAnimationSheetEnabled) {
  50126. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50127. }
  50128. }
  50129. }
  50130. };
  50131. }
  50132. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50133. /**
  50134. * Sets a callback that will be triggered when the system is disposed.
  50135. */
  50136. set: function (callback) {
  50137. if (this._onDisposeObserver) {
  50138. this.onDisposeObservable.remove(this._onDisposeObserver);
  50139. }
  50140. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50146. /**
  50147. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50148. */
  50149. get: function () {
  50150. return this._isAnimationSheetEnabled;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. ParticleSystem.prototype._createIndexBuffer = function () {
  50156. var indices = [];
  50157. var index = 0;
  50158. for (var count = 0; count < this._capacity; count++) {
  50159. indices.push(index);
  50160. indices.push(index + 1);
  50161. indices.push(index + 2);
  50162. indices.push(index);
  50163. indices.push(index + 2);
  50164. indices.push(index + 3);
  50165. index += 4;
  50166. }
  50167. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50168. };
  50169. /**
  50170. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50171. * Its lifetime will start back at 0.
  50172. * @param particle The particle to recycle
  50173. */
  50174. ParticleSystem.prototype.recycleParticle = function (particle) {
  50175. var lastParticle = this._particles.pop();
  50176. if (lastParticle !== particle) {
  50177. lastParticle.copyTo(particle);
  50178. this._stockParticles.push(lastParticle);
  50179. }
  50180. };
  50181. /**
  50182. * Gets the maximum number of particles active at the same time.
  50183. * @returns The max number of active particles.
  50184. */
  50185. ParticleSystem.prototype.getCapacity = function () {
  50186. return this._capacity;
  50187. };
  50188. /**
  50189. * Gets Wether there are still active particles in the system.
  50190. * @returns True if it is alive, otherwise false.
  50191. */
  50192. ParticleSystem.prototype.isAlive = function () {
  50193. return this._alive;
  50194. };
  50195. /**
  50196. * Gets Wether the system has been started.
  50197. * @returns True if it has been started, otherwise false.
  50198. */
  50199. ParticleSystem.prototype.isStarted = function () {
  50200. return this._started;
  50201. };
  50202. /**
  50203. * Starts the particle system and begins to emit.
  50204. */
  50205. ParticleSystem.prototype.start = function () {
  50206. this._started = true;
  50207. this._stopped = false;
  50208. this._actualFrame = 0;
  50209. };
  50210. /**
  50211. * Stops the particle system.
  50212. */
  50213. ParticleSystem.prototype.stop = function () {
  50214. this._stopped = true;
  50215. };
  50216. /**
  50217. * @ignore (for internal use only)
  50218. */
  50219. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50220. var offset = index * this._vertexBufferSize;
  50221. this._vertexData[offset] = particle.position.x;
  50222. this._vertexData[offset + 1] = particle.position.y;
  50223. this._vertexData[offset + 2] = particle.position.z;
  50224. this._vertexData[offset + 3] = particle.color.r;
  50225. this._vertexData[offset + 4] = particle.color.g;
  50226. this._vertexData[offset + 5] = particle.color.b;
  50227. this._vertexData[offset + 6] = particle.color.a;
  50228. this._vertexData[offset + 7] = particle.angle;
  50229. this._vertexData[offset + 8] = particle.size;
  50230. this._vertexData[offset + 9] = offsetX;
  50231. this._vertexData[offset + 10] = offsetY;
  50232. };
  50233. /**
  50234. * @ignore (for internal use only)
  50235. */
  50236. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50237. if (offsetX === 0)
  50238. offsetX = this._epsilon;
  50239. else if (offsetX === 1)
  50240. offsetX = 1 - this._epsilon;
  50241. if (offsetY === 0)
  50242. offsetY = this._epsilon;
  50243. else if (offsetY === 1)
  50244. offsetY = 1 - this._epsilon;
  50245. var offset = index * this._vertexBufferSize;
  50246. this._vertexData[offset] = particle.position.x;
  50247. this._vertexData[offset + 1] = particle.position.y;
  50248. this._vertexData[offset + 2] = particle.position.z;
  50249. this._vertexData[offset + 3] = particle.color.r;
  50250. this._vertexData[offset + 4] = particle.color.g;
  50251. this._vertexData[offset + 5] = particle.color.b;
  50252. this._vertexData[offset + 6] = particle.color.a;
  50253. this._vertexData[offset + 7] = particle.angle;
  50254. this._vertexData[offset + 8] = particle.size;
  50255. this._vertexData[offset + 9] = offsetX;
  50256. this._vertexData[offset + 10] = offsetY;
  50257. this._vertexData[offset + 11] = particle.cellIndex;
  50258. };
  50259. ParticleSystem.prototype._update = function (newParticles) {
  50260. // Update current
  50261. this._alive = this._particles.length > 0;
  50262. this.updateFunction(this._particles);
  50263. // Add new ones
  50264. var worldMatrix;
  50265. if (this.emitter.position) {
  50266. var emitterMesh = this.emitter;
  50267. worldMatrix = emitterMesh.getWorldMatrix();
  50268. }
  50269. else {
  50270. var emitterPosition = this.emitter;
  50271. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50272. }
  50273. var particle;
  50274. for (var index = 0; index < newParticles; index++) {
  50275. if (this._particles.length === this._capacity) {
  50276. break;
  50277. }
  50278. if (this._stockParticles.length !== 0) {
  50279. particle = this._stockParticles.pop();
  50280. particle.age = 0;
  50281. particle.cellIndex = this.startSpriteCellID;
  50282. }
  50283. else {
  50284. particle = new BABYLON.Particle(this);
  50285. }
  50286. this._particles.push(particle);
  50287. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50288. if (this.startPositionFunction) {
  50289. this.startPositionFunction(worldMatrix, particle.position, particle);
  50290. }
  50291. else {
  50292. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50293. }
  50294. if (this.startDirectionFunction) {
  50295. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50296. }
  50297. else {
  50298. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50299. }
  50300. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50301. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50302. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50303. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50304. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50305. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50306. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50307. }
  50308. };
  50309. ParticleSystem.prototype._getEffect = function () {
  50310. if (this._customEffect) {
  50311. return this._customEffect;
  50312. }
  50313. ;
  50314. var defines = [];
  50315. if (this._scene.clipPlane) {
  50316. defines.push("#define CLIPPLANE");
  50317. }
  50318. if (this._isAnimationSheetEnabled) {
  50319. defines.push("#define ANIMATESHEET");
  50320. }
  50321. // Effect
  50322. var join = defines.join("\n");
  50323. if (this._cachedDefines !== join) {
  50324. this._cachedDefines = join;
  50325. var attributesNamesOrOptions;
  50326. var effectCreationOption;
  50327. if (this._isAnimationSheetEnabled) {
  50328. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50329. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50330. }
  50331. else {
  50332. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50333. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50334. }
  50335. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50336. }
  50337. return this._effect;
  50338. };
  50339. /**
  50340. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50341. */
  50342. ParticleSystem.prototype.animate = function () {
  50343. if (!this._started)
  50344. return;
  50345. var effect = this._getEffect();
  50346. // Check
  50347. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50348. return;
  50349. if (this._currentRenderId === this._scene.getRenderId()) {
  50350. return;
  50351. }
  50352. this._currentRenderId = this._scene.getRenderId();
  50353. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50354. // determine the number of particles we need to create
  50355. var newParticles;
  50356. if (this.manualEmitCount > -1) {
  50357. newParticles = this.manualEmitCount;
  50358. this._newPartsExcess = 0;
  50359. this.manualEmitCount = 0;
  50360. }
  50361. else {
  50362. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50363. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50364. }
  50365. if (this._newPartsExcess > 1.0) {
  50366. newParticles += this._newPartsExcess >> 0;
  50367. this._newPartsExcess -= this._newPartsExcess >> 0;
  50368. }
  50369. this._alive = false;
  50370. if (!this._stopped) {
  50371. this._actualFrame += this._scaledUpdateSpeed;
  50372. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50373. this.stop();
  50374. }
  50375. else {
  50376. newParticles = 0;
  50377. }
  50378. this._update(newParticles);
  50379. // Stopped?
  50380. if (this._stopped) {
  50381. if (!this._alive) {
  50382. this._started = false;
  50383. if (this.onAnimationEnd) {
  50384. this.onAnimationEnd();
  50385. }
  50386. if (this.disposeOnStop) {
  50387. this._scene._toBeDisposed.push(this);
  50388. }
  50389. }
  50390. }
  50391. // Animation sheet
  50392. if (this._isAnimationSheetEnabled) {
  50393. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50394. }
  50395. else {
  50396. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50397. }
  50398. // Update VBO
  50399. var offset = 0;
  50400. for (var index = 0; index < this._particles.length; index++) {
  50401. var particle = this._particles[index];
  50402. this._appendParticleVertexes(offset, particle);
  50403. offset += 4;
  50404. }
  50405. if (this._vertexBuffer) {
  50406. this._vertexBuffer.update(this._vertexData);
  50407. }
  50408. };
  50409. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50410. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50411. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50412. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50413. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50414. };
  50415. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50416. this._appendParticleVertex(offset++, particle, 0, 0);
  50417. this._appendParticleVertex(offset++, particle, 1, 0);
  50418. this._appendParticleVertex(offset++, particle, 1, 1);
  50419. this._appendParticleVertex(offset++, particle, 0, 1);
  50420. };
  50421. /**
  50422. * Rebuilds the particle system.
  50423. */
  50424. ParticleSystem.prototype.rebuild = function () {
  50425. this._createIndexBuffer();
  50426. if (this._vertexBuffer) {
  50427. this._vertexBuffer._rebuild();
  50428. }
  50429. };
  50430. /**
  50431. * Renders the particle system in its current state.
  50432. * @returns the current number of particles.
  50433. */
  50434. ParticleSystem.prototype.render = function () {
  50435. var effect = this._getEffect();
  50436. // Check
  50437. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50438. return 0;
  50439. var engine = this._scene.getEngine();
  50440. // Render
  50441. engine.enableEffect(effect);
  50442. engine.setState(false);
  50443. var viewMatrix = this._scene.getViewMatrix();
  50444. effect.setTexture("diffuseSampler", this.particleTexture);
  50445. effect.setMatrix("view", viewMatrix);
  50446. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50447. if (this._isAnimationSheetEnabled) {
  50448. var baseSize = this.particleTexture.getBaseSize();
  50449. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50450. }
  50451. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50452. if (this._scene.clipPlane) {
  50453. var clipPlane = this._scene.clipPlane;
  50454. var invView = viewMatrix.clone();
  50455. invView.invert();
  50456. effect.setMatrix("invView", invView);
  50457. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50458. }
  50459. // VBOs
  50460. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50461. // Draw order
  50462. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50463. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50464. }
  50465. else {
  50466. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50467. }
  50468. if (this.forceDepthWrite) {
  50469. engine.setDepthWrite(true);
  50470. }
  50471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50472. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50473. return this._particles.length;
  50474. };
  50475. /**
  50476. * Disposes the particle system and free the associated resources.
  50477. */
  50478. ParticleSystem.prototype.dispose = function () {
  50479. if (this._vertexBuffer) {
  50480. this._vertexBuffer.dispose();
  50481. this._vertexBuffer = null;
  50482. }
  50483. if (this._indexBuffer) {
  50484. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50485. this._indexBuffer = null;
  50486. }
  50487. if (this.particleTexture) {
  50488. this.particleTexture.dispose();
  50489. this.particleTexture = null;
  50490. }
  50491. // Remove from scene
  50492. var index = this._scene.particleSystems.indexOf(this);
  50493. if (index > -1) {
  50494. this._scene.particleSystems.splice(index, 1);
  50495. }
  50496. // Callback
  50497. this.onDisposeObservable.notifyObservers(this);
  50498. this.onDisposeObservable.clear();
  50499. };
  50500. /**
  50501. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50502. * @param radius The radius of the sphere to emit from
  50503. * @returns the emitter
  50504. */
  50505. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50506. if (radius === void 0) { radius = 1; }
  50507. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50508. this.particleEmitterType = particleEmitter;
  50509. return particleEmitter;
  50510. };
  50511. /**
  50512. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50513. * @param radius The radius of the sphere to emit from
  50514. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50515. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50516. * @returns the emitter
  50517. */
  50518. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50519. if (radius === void 0) { radius = 1; }
  50520. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50521. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50522. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50523. this.particleEmitterType = particleEmitter;
  50524. return particleEmitter;
  50525. };
  50526. /**
  50527. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50528. * @param radius The radius of the cone to emit from
  50529. * @param angle The base angle of the cone
  50530. * @returns the emitter
  50531. */
  50532. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50533. if (radius === void 0) { radius = 1; }
  50534. if (angle === void 0) { angle = Math.PI / 4; }
  50535. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50536. this.particleEmitterType = particleEmitter;
  50537. return particleEmitter;
  50538. };
  50539. // 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.
  50540. /**
  50541. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50542. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50543. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50544. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50545. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50546. * @returns the emitter
  50547. */
  50548. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50549. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50550. this.direction1 = direction1;
  50551. this.direction2 = direction2;
  50552. this.minEmitBox = minEmitBox;
  50553. this.maxEmitBox = maxEmitBox;
  50554. this.particleEmitterType = particleEmitter;
  50555. return particleEmitter;
  50556. };
  50557. /**
  50558. * Clones the particle system.
  50559. * @param name The name of the cloned object
  50560. * @param newEmitter The new emitter to use
  50561. * @returns the cloned particle system
  50562. */
  50563. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50564. var custom = null;
  50565. var program = null;
  50566. if (this.customShader != null) {
  50567. program = this.customShader;
  50568. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50569. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50570. }
  50571. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50572. result.customShader = program;
  50573. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50574. if (newEmitter === undefined) {
  50575. newEmitter = this.emitter;
  50576. }
  50577. result.emitter = newEmitter;
  50578. if (this.particleTexture) {
  50579. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50580. }
  50581. if (!this.preventAutoStart) {
  50582. result.start();
  50583. }
  50584. return result;
  50585. };
  50586. /**
  50587. * Serializes the particle system to a JSON object.
  50588. * @returns the JSON object
  50589. */
  50590. ParticleSystem.prototype.serialize = function () {
  50591. var serializationObject = {};
  50592. serializationObject.name = this.name;
  50593. serializationObject.id = this.id;
  50594. // Emitter
  50595. if (this.emitter.position) {
  50596. var emitterMesh = this.emitter;
  50597. serializationObject.emitterId = emitterMesh.id;
  50598. }
  50599. else {
  50600. var emitterPosition = this.emitter;
  50601. serializationObject.emitter = emitterPosition.asArray();
  50602. }
  50603. serializationObject.capacity = this.getCapacity();
  50604. if (this.particleTexture) {
  50605. serializationObject.textureName = this.particleTexture.name;
  50606. }
  50607. // Animations
  50608. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50609. // Particle system
  50610. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50611. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50612. serializationObject.minSize = this.minSize;
  50613. serializationObject.maxSize = this.maxSize;
  50614. serializationObject.minEmitPower = this.minEmitPower;
  50615. serializationObject.maxEmitPower = this.maxEmitPower;
  50616. serializationObject.minLifeTime = this.minLifeTime;
  50617. serializationObject.maxLifeTime = this.maxLifeTime;
  50618. serializationObject.emitRate = this.emitRate;
  50619. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50620. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50621. serializationObject.gravity = this.gravity.asArray();
  50622. serializationObject.direction1 = this.direction1.asArray();
  50623. serializationObject.direction2 = this.direction2.asArray();
  50624. serializationObject.color1 = this.color1.asArray();
  50625. serializationObject.color2 = this.color2.asArray();
  50626. serializationObject.colorDead = this.colorDead.asArray();
  50627. serializationObject.updateSpeed = this.updateSpeed;
  50628. serializationObject.targetStopDuration = this.targetStopDuration;
  50629. serializationObject.textureMask = this.textureMask.asArray();
  50630. serializationObject.blendMode = this.blendMode;
  50631. serializationObject.customShader = this.customShader;
  50632. serializationObject.preventAutoStart = this.preventAutoStart;
  50633. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50634. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50635. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50636. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50637. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50638. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50639. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50640. return serializationObject;
  50641. };
  50642. /**
  50643. * Parses a JSON object to create a particle system.
  50644. * @param parsedParticleSystem The JSON object to parse
  50645. * @param scene The scene to create the particle system in
  50646. * @param rootUrl The root url to use to load external dependencies like texture
  50647. * @returns the Parsed particle system
  50648. */
  50649. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50650. var name = parsedParticleSystem.name;
  50651. var custom = null;
  50652. var program = null;
  50653. if (parsedParticleSystem.customShader) {
  50654. program = parsedParticleSystem.customShader;
  50655. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50656. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50657. }
  50658. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50659. particleSystem.customShader = program;
  50660. if (parsedParticleSystem.id) {
  50661. particleSystem.id = parsedParticleSystem.id;
  50662. }
  50663. // Auto start
  50664. if (parsedParticleSystem.preventAutoStart) {
  50665. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50666. }
  50667. // Texture
  50668. if (parsedParticleSystem.textureName) {
  50669. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50670. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50671. }
  50672. // Emitter
  50673. if (parsedParticleSystem.emitterId) {
  50674. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50675. }
  50676. else {
  50677. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50678. }
  50679. // Animations
  50680. if (parsedParticleSystem.animations) {
  50681. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50682. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50683. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50684. }
  50685. }
  50686. if (parsedParticleSystem.autoAnimate) {
  50687. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50688. }
  50689. // Particle system
  50690. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50691. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50692. particleSystem.minSize = parsedParticleSystem.minSize;
  50693. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50694. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50695. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50696. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50697. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50698. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50699. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50700. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50701. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50702. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50703. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50704. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50705. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50706. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50707. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50708. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50709. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50710. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50711. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50712. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50713. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50714. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50715. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50716. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50717. if (!particleSystem.preventAutoStart) {
  50718. particleSystem.start();
  50719. }
  50720. return particleSystem;
  50721. };
  50722. /**
  50723. * Source color is added to the destination color without alpha affecting the result.
  50724. */
  50725. ParticleSystem.BLENDMODE_ONEONE = 0;
  50726. /**
  50727. * Blend current color and particle color using particle’s alpha.
  50728. */
  50729. ParticleSystem.BLENDMODE_STANDARD = 1;
  50730. return ParticleSystem;
  50731. }());
  50732. BABYLON.ParticleSystem = ParticleSystem;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.particleSystem.js.map
  50735. var BABYLON;
  50736. (function (BABYLON) {
  50737. /**
  50738. * Particle emitter emitting particles from the inside of a box.
  50739. * It emits the particles randomly between 2 given directions.
  50740. */
  50741. var BoxParticleEmitter = /** @class */ (function () {
  50742. // to be updated like the rest of emitters when breaking changes.
  50743. // all property should be come public variables and passed through constructor.
  50744. /**
  50745. * Creates a new instance of @see BoxParticleEmitter
  50746. * @param _particleSystem the particle system associated with the emitter
  50747. */
  50748. function BoxParticleEmitter(_particleSystem) {
  50749. this._particleSystem = _particleSystem;
  50750. }
  50751. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50752. /**
  50753. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50754. */
  50755. get: function () {
  50756. return this._particleSystem.direction1;
  50757. },
  50758. /**
  50759. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50760. */
  50761. set: function (value) {
  50762. this._particleSystem.direction1 = value;
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50768. /**
  50769. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50770. */
  50771. get: function () {
  50772. return this._particleSystem.direction2;
  50773. },
  50774. /**
  50775. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50776. */
  50777. set: function (value) {
  50778. this._particleSystem.direction2 = value;
  50779. },
  50780. enumerable: true,
  50781. configurable: true
  50782. });
  50783. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50784. /**
  50785. * 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.
  50786. */
  50787. get: function () {
  50788. return this._particleSystem.minEmitBox;
  50789. },
  50790. /**
  50791. * 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.
  50792. */
  50793. set: function (value) {
  50794. this._particleSystem.minEmitBox = value;
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50800. /**
  50801. * 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.
  50802. */
  50803. get: function () {
  50804. return this._particleSystem.maxEmitBox;
  50805. },
  50806. /**
  50807. * 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.
  50808. */
  50809. set: function (value) {
  50810. this._particleSystem.maxEmitBox = value;
  50811. },
  50812. enumerable: true,
  50813. configurable: true
  50814. });
  50815. /**
  50816. * Called by the particle System when the direction is computed for the created particle.
  50817. * @param emitPower is the power of the particle (speed)
  50818. * @param worldMatrix is the world matrix of the particle system
  50819. * @param directionToUpdate is the direction vector to update with the result
  50820. * @param particle is the particle we are computed the direction for
  50821. */
  50822. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50823. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50824. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50825. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50826. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50827. };
  50828. /**
  50829. * Called by the particle System when the position is computed for the created particle.
  50830. * @param worldMatrix is the world matrix of the particle system
  50831. * @param positionToUpdate is the position vector to update with the result
  50832. * @param particle is the particle we are computed the position for
  50833. */
  50834. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50835. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50836. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50837. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50839. };
  50840. /**
  50841. * Clones the current emitter and returns a copy of it
  50842. * @returns the new emitter
  50843. */
  50844. BoxParticleEmitter.prototype.clone = function () {
  50845. var newOne = new BoxParticleEmitter(this._particleSystem);
  50846. BABYLON.Tools.DeepCopy(this, newOne);
  50847. return newOne;
  50848. };
  50849. return BoxParticleEmitter;
  50850. }());
  50851. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50852. })(BABYLON || (BABYLON = {}));
  50853. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50854. var BABYLON;
  50855. (function (BABYLON) {
  50856. /**
  50857. * Particle emitter emitting particles from the inside of a cone.
  50858. * It emits the particles alongside the cone volume from the base to the particle.
  50859. * The emission direction might be randomized.
  50860. */
  50861. var ConeParticleEmitter = /** @class */ (function () {
  50862. /**
  50863. * Creates a new instance of @see ConeParticleEmitter
  50864. * @param radius the radius of the emission cone
  50865. * @param angles the cone base angle
  50866. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50867. */
  50868. function ConeParticleEmitter(radius,
  50869. /**
  50870. * The radius of the emission cone.
  50871. */
  50872. angle,
  50873. /**
  50874. * The cone base angle.
  50875. */
  50876. directionRandomizer) {
  50877. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50878. this.angle = angle;
  50879. this.directionRandomizer = directionRandomizer;
  50880. this.radius = radius;
  50881. }
  50882. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50883. /**
  50884. * Gets the radius of the emission cone.
  50885. */
  50886. get: function () {
  50887. return this._radius;
  50888. },
  50889. /**
  50890. * Sets the radius of the emission cone.
  50891. */
  50892. set: function (value) {
  50893. this._radius = value;
  50894. if (this.angle !== 0) {
  50895. this._height = value / Math.tan(this.angle / 2);
  50896. }
  50897. else {
  50898. this._height = 1;
  50899. }
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. /**
  50905. * Called by the particle System when the direction is computed for the created particle.
  50906. * @param emitPower is the power of the particle (speed)
  50907. * @param worldMatrix is the world matrix of the particle system
  50908. * @param directionToUpdate is the direction vector to update with the result
  50909. * @param particle is the particle we are computed the direction for
  50910. */
  50911. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50912. if (this.angle === 0) {
  50913. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50914. }
  50915. else {
  50916. // measure the direction Vector from the emitter to the particle.
  50917. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50918. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50919. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50920. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50921. direction.x += randX;
  50922. direction.y += randY;
  50923. direction.z += randZ;
  50924. direction.normalize();
  50925. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50926. }
  50927. };
  50928. /**
  50929. * Called by the particle System when the position is computed for the created particle.
  50930. * @param worldMatrix is the world matrix of the particle system
  50931. * @param positionToUpdate is the position vector to update with the result
  50932. * @param particle is the particle we are computed the position for
  50933. */
  50934. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50935. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50936. var h = BABYLON.Scalar.RandomRange(0, 1);
  50937. // Better distribution in a cone at normal angles.
  50938. h = 1 - h * h;
  50939. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50940. radius = radius * h / this._height;
  50941. var randX = radius * Math.sin(s);
  50942. var randZ = radius * Math.cos(s);
  50943. var randY = h;
  50944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50945. };
  50946. /**
  50947. * Clones the current emitter and returns a copy of it
  50948. * @returns the new emitter
  50949. */
  50950. ConeParticleEmitter.prototype.clone = function () {
  50951. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50952. BABYLON.Tools.DeepCopy(this, newOne);
  50953. return newOne;
  50954. };
  50955. return ConeParticleEmitter;
  50956. }());
  50957. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50958. })(BABYLON || (BABYLON = {}));
  50959. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50960. var BABYLON;
  50961. (function (BABYLON) {
  50962. /**
  50963. * Particle emitter emitting particles from the inside of a sphere.
  50964. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50965. */
  50966. var SphereParticleEmitter = /** @class */ (function () {
  50967. /**
  50968. * Creates a new instance of @see SphereParticleEmitter
  50969. * @param radius the radius of the emission sphere
  50970. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50971. */
  50972. function SphereParticleEmitter(
  50973. /**
  50974. * The radius of the emission sphere.
  50975. */
  50976. radius,
  50977. /**
  50978. * How much to randomize the particle direction [0-1].
  50979. */
  50980. directionRandomizer) {
  50981. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50982. this.radius = radius;
  50983. this.directionRandomizer = directionRandomizer;
  50984. }
  50985. /**
  50986. * Called by the particle System when the direction is computed for the created particle.
  50987. * @param emitPower is the power of the particle (speed)
  50988. * @param worldMatrix is the world matrix of the particle system
  50989. * @param directionToUpdate is the direction vector to update with the result
  50990. * @param particle is the particle we are computed the direction for
  50991. */
  50992. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50993. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50994. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50995. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50996. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50997. direction.x += randX;
  50998. direction.y += randY;
  50999. direction.z += randZ;
  51000. direction.normalize();
  51001. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51002. };
  51003. /**
  51004. * Called by the particle System when the position is computed for the created particle.
  51005. * @param worldMatrix is the world matrix of the particle system
  51006. * @param positionToUpdate is the position vector to update with the result
  51007. * @param particle is the particle we are computed the position for
  51008. */
  51009. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51010. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51011. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51012. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51013. var randY = this.radius * Math.cos(theta);
  51014. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51015. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51016. };
  51017. /**
  51018. * Clones the current emitter and returns a copy of it
  51019. * @returns the new emitter
  51020. */
  51021. SphereParticleEmitter.prototype.clone = function () {
  51022. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51023. BABYLON.Tools.DeepCopy(this, newOne);
  51024. return newOne;
  51025. };
  51026. return SphereParticleEmitter;
  51027. }());
  51028. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51029. /**
  51030. * Particle emitter emitting particles from the inside of a sphere.
  51031. * It emits the particles randomly between two vectors.
  51032. */
  51033. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51034. __extends(SphereDirectedParticleEmitter, _super);
  51035. /**
  51036. * Creates a new instance of @see SphereDirectedParticleEmitter
  51037. * @param radius the radius of the emission sphere
  51038. * @param direction1 the min limit of the emission direction
  51039. * @param direction2 the max limit of the emission direction
  51040. */
  51041. function SphereDirectedParticleEmitter(radius,
  51042. /**
  51043. * The min limit of the emission direction.
  51044. */
  51045. direction1,
  51046. /**
  51047. * The max limit of the emission direction.
  51048. */
  51049. direction2) {
  51050. var _this = _super.call(this, radius) || this;
  51051. _this.direction1 = direction1;
  51052. _this.direction2 = direction2;
  51053. return _this;
  51054. }
  51055. /**
  51056. * Called by the particle System when the direction is computed for the created particle.
  51057. * @param emitPower is the power of the particle (speed)
  51058. * @param worldMatrix is the world matrix of the particle system
  51059. * @param directionToUpdate is the direction vector to update with the result
  51060. * @param particle is the particle we are computed the direction for
  51061. */
  51062. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51063. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51064. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51065. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51066. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51067. };
  51068. /**
  51069. * Clones the current emitter and returns a copy of it
  51070. * @returns the new emitter
  51071. */
  51072. SphereDirectedParticleEmitter.prototype.clone = function () {
  51073. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51074. BABYLON.Tools.DeepCopy(this, newOne);
  51075. return newOne;
  51076. };
  51077. return SphereDirectedParticleEmitter;
  51078. }(SphereParticleEmitter));
  51079. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51080. })(BABYLON || (BABYLON = {}));
  51081. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51082. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51083. var BABYLON;
  51084. (function (BABYLON) {
  51085. /**
  51086. * This represents a GPU particle system in Babylon.
  51087. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  51088. */
  51089. var GPUParticleSystem = /** @class */ (function () {
  51090. /**
  51091. * Instantiates a GPU particle system.
  51092. * 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.
  51093. * @param name The name of the particle system
  51094. * @param capacity The max number of particles alive at the same time
  51095. * @param scene The scene the particle system belongs to
  51096. */
  51097. function GPUParticleSystem(name, capacity, scene) {
  51098. /**
  51099. * The emitter represents the Mesh or position we are attaching the particle system to.
  51100. */
  51101. this.emitter = null;
  51102. /**
  51103. * The rendering group used by the Particle system to chose when to render.
  51104. */
  51105. this.renderingGroupId = 0;
  51106. /**
  51107. * The layer mask we are rendering the particles through.
  51108. */
  51109. this.layerMask = 0x0FFFFFFF; // TODO
  51110. this._updateVertexBuffers = {};
  51111. this._renderVertexBuffers = {};
  51112. this._currentRenderId = -1;
  51113. this._started = true;
  51114. /**
  51115. * An event triggered when the system is disposed.
  51116. */
  51117. this.onDisposeObservable = new BABYLON.Observable();
  51118. this.id = name;
  51119. this.name = name;
  51120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51121. this._capacity = capacity;
  51122. this._engine = this._scene.getEngine();
  51123. this._scene.particleSystems.push(this);
  51124. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  51125. var updateEffectOptions = {
  51126. attributes: ["position", "age", "life", "velocity"],
  51127. uniformsNames: [],
  51128. uniformBuffersNames: [],
  51129. samplers: [],
  51130. defines: "",
  51131. fallbacks: null,
  51132. onCompiled: null,
  51133. onError: null,
  51134. indexParameters: null,
  51135. maxSimultaneousLights: 0,
  51136. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  51137. };
  51138. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  51139. }
  51140. /**
  51141. * Gets Wether the system has been started.
  51142. * @returns True if it has been started, otherwise false.
  51143. */
  51144. GPUParticleSystem.prototype.isStarted = function () {
  51145. return this._started;
  51146. };
  51147. /**
  51148. * Starts the particle system and begins to emit.
  51149. */
  51150. GPUParticleSystem.prototype.start = function () {
  51151. this._started = true;
  51152. };
  51153. /**
  51154. * Stops the particle system.
  51155. */
  51156. GPUParticleSystem.prototype.stop = function () {
  51157. this._started = false;
  51158. };
  51159. /**
  51160. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51161. */
  51162. GPUParticleSystem.prototype.animate = function () {
  51163. // Do nothing
  51164. };
  51165. GPUParticleSystem.prototype._initialize = function () {
  51166. if (this._renderVAO) {
  51167. return;
  51168. }
  51169. var data = new Array();
  51170. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  51171. // position
  51172. data.push(0.0);
  51173. data.push(0.0);
  51174. data.push(0.0);
  51175. var life = 1 + Math.random() * 10; // TODO: var
  51176. data.push(life + 1); // create the particle as a dead one to create a new one at start
  51177. data.push(life);
  51178. // velocity
  51179. data.push(0.0);
  51180. data.push(0.0);
  51181. data.push(0.0);
  51182. }
  51183. // Update VAO
  51184. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  51185. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  51186. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  51187. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  51188. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  51189. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  51190. this._engine.bindArrayBuffer(null);
  51191. // Render VAO
  51192. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  51193. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  51194. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  51195. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  51196. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  51197. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  51198. this._engine.bindArrayBuffer(null);
  51199. // Links
  51200. this._sourceVAO = this._updateVAO;
  51201. this._targetVAO = this._renderVAO;
  51202. this._sourceBuffer = this._updateBuffer;
  51203. this._targetBuffer = this._renderBuffer;
  51204. };
  51205. /**
  51206. * Renders the particle system in its current state.
  51207. * @returns the current number of particles.
  51208. */
  51209. GPUParticleSystem.prototype.render = function () {
  51210. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  51211. return 0;
  51212. }
  51213. // Get everything ready to render
  51214. this._initialize();
  51215. if (this._currentRenderId === this._scene.getRenderId()) {
  51216. return 0;
  51217. }
  51218. this._currentRenderId = this._scene.getRenderId();
  51219. // Enable update effect
  51220. this._engine.enableEffect(this._updateEffect);
  51221. this._engine.setState(false);
  51222. // Bind source VAO
  51223. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  51224. // Update
  51225. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  51226. this._engine.setRasterizerState(false);
  51227. this._engine.beginTransformFeedback();
  51228. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  51229. this._engine.endTransformFeedback();
  51230. this._engine.setRasterizerState(true);
  51231. this._engine.bindTransformFeedbackBuffer(null);
  51232. // Enable render effect
  51233. this._engine.enableEffect(this._renderEffect);
  51234. // Bind source VAO
  51235. this._engine.bindVertexArrayObject(this._targetVAO, null);
  51236. // Render
  51237. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  51238. // Switch VAOs
  51239. var tmpVAO = this._sourceVAO;
  51240. this._sourceVAO = this._targetVAO;
  51241. this._targetVAO = tmpVAO;
  51242. // Switch buffers
  51243. var tmpBuffer = this._sourceBuffer;
  51244. this._sourceBuffer = this._targetBuffer;
  51245. this._targetBuffer = tmpBuffer;
  51246. return 0;
  51247. };
  51248. /**
  51249. * Rebuilds the particle system
  51250. */
  51251. GPUParticleSystem.prototype.rebuild = function () {
  51252. };
  51253. /**
  51254. * Disposes the particle system and free the associated resources.
  51255. */
  51256. GPUParticleSystem.prototype.dispose = function () {
  51257. var index = this._scene.particleSystems.indexOf(this);
  51258. if (index > -1) {
  51259. this._scene.particleSystems.splice(index, 1);
  51260. }
  51261. //TODO: this._dataBuffer.dispose();
  51262. // Callback
  51263. this.onDisposeObservable.notifyObservers(this);
  51264. this.onDisposeObservable.clear();
  51265. };
  51266. //TODO: Clone / Parse / serialize
  51267. /**
  51268. * Clones the particle system.
  51269. * @param name The name of the cloned object
  51270. * @param newEmitter The new emitter to use
  51271. * @returns the cloned particle system
  51272. */
  51273. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  51274. return null;
  51275. };
  51276. /**
  51277. * Serializes the particle system to a JSON object.
  51278. * @returns the JSON object
  51279. */
  51280. GPUParticleSystem.prototype.serialize = function () {
  51281. };
  51282. return GPUParticleSystem;
  51283. }());
  51284. BABYLON.GPUParticleSystem = GPUParticleSystem;
  51285. })(BABYLON || (BABYLON = {}));
  51286. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  51287. var BABYLON;
  51288. (function (BABYLON) {
  51289. /**
  51290. * Represents one particle of a solid particle system.
  51291. * @see SolidParticleSystem
  51292. */
  51293. var SolidParticle = /** @class */ (function () {
  51294. /**
  51295. * Creates a Solid Particle object.
  51296. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51297. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51298. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51299. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51300. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51301. * @param shapeId (integer) is the model shape identifier in the SPS.
  51302. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51303. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51304. */
  51305. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51306. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51307. /**
  51308. * particle global index
  51309. */
  51310. this.idx = 0;
  51311. /**
  51312. * The color of the particle
  51313. */
  51314. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51315. /**
  51316. * The world space position of the particle.
  51317. */
  51318. this.position = BABYLON.Vector3.Zero();
  51319. /**
  51320. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51321. */
  51322. this.rotation = BABYLON.Vector3.Zero();
  51323. /**
  51324. * The scaling of the particle.
  51325. */
  51326. this.scaling = BABYLON.Vector3.One();
  51327. /**
  51328. * The uvs of the particle.
  51329. */
  51330. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51331. /**
  51332. * The current speed of the particle.
  51333. */
  51334. this.velocity = BABYLON.Vector3.Zero();
  51335. /**
  51336. * The pivot point in the particle local space.
  51337. */
  51338. this.pivot = BABYLON.Vector3.Zero();
  51339. /**
  51340. * Must the particle be translated from its pivot point in its local space ?
  51341. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51342. * Default : false
  51343. */
  51344. this.translateFromPivot = false;
  51345. /**
  51346. * Is the particle active or not ?
  51347. */
  51348. this.alive = true;
  51349. /**
  51350. * Is the particle visible or not ?
  51351. */
  51352. this.isVisible = true;
  51353. /**
  51354. * Index of this particle in the global "positions" array (Internal use)
  51355. */
  51356. this._pos = 0;
  51357. /**
  51358. * Index of this particle in the global "indices" array (Internal use)
  51359. */
  51360. this._ind = 0;
  51361. /**
  51362. * ModelShape id of this particle
  51363. */
  51364. this.shapeId = 0;
  51365. /**
  51366. * Index of the particle in its shape id (Internal use)
  51367. */
  51368. this.idxInShape = 0;
  51369. /**
  51370. * Still set as invisible in order to skip useless computations (Internal use)
  51371. */
  51372. this._stillInvisible = false;
  51373. /**
  51374. * Last computed particle rotation matrix
  51375. */
  51376. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51377. this.idx = particleIndex;
  51378. this._pos = positionIndex;
  51379. this._ind = indiceIndex;
  51380. this._model = model;
  51381. this.shapeId = shapeId;
  51382. this.idxInShape = idxInShape;
  51383. this._sps = sps;
  51384. if (modelBoundingInfo) {
  51385. this._modelBoundingInfo = modelBoundingInfo;
  51386. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51387. }
  51388. }
  51389. Object.defineProperty(SolidParticle.prototype, "scale", {
  51390. /**
  51391. * Legacy support, changed scale to scaling
  51392. */
  51393. get: function () {
  51394. return this.scaling;
  51395. },
  51396. /**
  51397. * Legacy support, changed scale to scaling
  51398. */
  51399. set: function (scale) {
  51400. this.scaling = scale;
  51401. },
  51402. enumerable: true,
  51403. configurable: true
  51404. });
  51405. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51406. /**
  51407. * Legacy support, changed quaternion to rotationQuaternion
  51408. */
  51409. get: function () {
  51410. return this.rotationQuaternion;
  51411. },
  51412. /**
  51413. * Legacy support, changed quaternion to rotationQuaternion
  51414. */
  51415. set: function (q) {
  51416. this.rotationQuaternion = q;
  51417. },
  51418. enumerable: true,
  51419. configurable: true
  51420. });
  51421. /**
  51422. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51423. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51424. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51425. * @returns true if it intersects
  51426. */
  51427. SolidParticle.prototype.intersectsMesh = function (target) {
  51428. if (!this._boundingInfo || !target._boundingInfo) {
  51429. return false;
  51430. }
  51431. if (this._sps._bSphereOnly) {
  51432. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51433. }
  51434. return this._boundingInfo.intersects(target._boundingInfo, false);
  51435. };
  51436. return SolidParticle;
  51437. }());
  51438. BABYLON.SolidParticle = SolidParticle;
  51439. /**
  51440. * Represents the shape of the model used by one particle of a solid particle system.
  51441. * SPS internal tool, don't use it manually.
  51442. * @see SolidParticleSystem
  51443. */
  51444. var ModelShape = /** @class */ (function () {
  51445. /**
  51446. * 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.
  51447. * SPS internal tool, don't use it manually.
  51448. * @ignore
  51449. */
  51450. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51451. /**
  51452. * length of the shape in the model indices array (internal use)
  51453. */
  51454. this._indicesLength = 0;
  51455. this.shapeID = id;
  51456. this._shape = shape;
  51457. this._indicesLength = indicesLength;
  51458. this._shapeUV = shapeUV;
  51459. this._positionFunction = posFunction;
  51460. this._vertexFunction = vtxFunction;
  51461. }
  51462. return ModelShape;
  51463. }());
  51464. BABYLON.ModelShape = ModelShape;
  51465. /**
  51466. * Represents a Depth Sorted Particle in the solid particle system.
  51467. * @see SolidParticleSystem
  51468. */
  51469. var DepthSortedParticle = /** @class */ (function () {
  51470. function DepthSortedParticle() {
  51471. /**
  51472. * Index of the particle in the "indices" array
  51473. */
  51474. this.ind = 0;
  51475. /**
  51476. * Length of the particle shape in the "indices" array
  51477. */
  51478. this.indicesLength = 0;
  51479. /**
  51480. * Squared distance from the particle to the camera
  51481. */
  51482. this.sqDistance = 0.0;
  51483. }
  51484. return DepthSortedParticle;
  51485. }());
  51486. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51487. })(BABYLON || (BABYLON = {}));
  51488. //# sourceMappingURL=babylon.solidParticle.js.map
  51489. var BABYLON;
  51490. (function (BABYLON) {
  51491. /**
  51492. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51493. *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.
  51494. * The SPS is also a particle system. It provides some methods to manage the particles.
  51495. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51496. *
  51497. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51498. */
  51499. var SolidParticleSystem = /** @class */ (function () {
  51500. /**
  51501. * Creates a SPS (Solid Particle System) object.
  51502. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51503. * @param scene (Scene) is the scene in which the SPS is added.
  51504. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51505. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51506. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51507. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51508. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51509. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51510. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51511. */
  51512. function SolidParticleSystem(name, scene, options) {
  51513. /**
  51514. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51515. * Example : var p = SPS.particles[i];
  51516. */
  51517. this.particles = new Array();
  51518. /**
  51519. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51520. */
  51521. this.nbParticles = 0;
  51522. /**
  51523. * If the particles must ever face the camera (default false). Useful for planar particles.
  51524. */
  51525. this.billboard = false;
  51526. /**
  51527. * Recompute normals when adding a shape
  51528. */
  51529. this.recomputeNormals = true;
  51530. /**
  51531. * This a counter ofr your own usage. It's not set by any SPS functions.
  51532. */
  51533. this.counter = 0;
  51534. /**
  51535. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51536. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51537. */
  51538. this.vars = {};
  51539. /**
  51540. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51541. */
  51542. this._bSphereOnly = false;
  51543. /**
  51544. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51545. */
  51546. this._bSphereRadiusFactor = 1.0;
  51547. this._positions = new Array();
  51548. this._indices = new Array();
  51549. this._normals = new Array();
  51550. this._colors = new Array();
  51551. this._uvs = new Array();
  51552. this._index = 0; // indices index
  51553. this._updatable = true;
  51554. this._pickable = false;
  51555. this._isVisibilityBoxLocked = false;
  51556. this._alwaysVisible = false;
  51557. this._depthSort = false;
  51558. this._shapeCounter = 0;
  51559. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51560. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51561. this._computeParticleColor = true;
  51562. this._computeParticleTexture = true;
  51563. this._computeParticleRotation = true;
  51564. this._computeParticleVertex = false;
  51565. this._computeBoundingBox = false;
  51566. this._depthSortParticles = true;
  51567. this._cam_axisZ = BABYLON.Vector3.Zero();
  51568. this._cam_axisY = BABYLON.Vector3.Zero();
  51569. this._cam_axisX = BABYLON.Vector3.Zero();
  51570. this._axisZ = BABYLON.Axis.Z;
  51571. this._camDir = BABYLON.Vector3.Zero();
  51572. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51573. this._rotMatrix = new BABYLON.Matrix();
  51574. this._invertMatrix = new BABYLON.Matrix();
  51575. this._rotated = BABYLON.Vector3.Zero();
  51576. this._quaternion = new BABYLON.Quaternion();
  51577. this._vertex = BABYLON.Vector3.Zero();
  51578. this._normal = BABYLON.Vector3.Zero();
  51579. this._yaw = 0.0;
  51580. this._pitch = 0.0;
  51581. this._roll = 0.0;
  51582. this._halfroll = 0.0;
  51583. this._halfpitch = 0.0;
  51584. this._halfyaw = 0.0;
  51585. this._sinRoll = 0.0;
  51586. this._cosRoll = 0.0;
  51587. this._sinPitch = 0.0;
  51588. this._cosPitch = 0.0;
  51589. this._sinYaw = 0.0;
  51590. this._cosYaw = 0.0;
  51591. this._mustUnrotateFixedNormals = false;
  51592. this._minimum = BABYLON.Vector3.Zero();
  51593. this._maximum = BABYLON.Vector3.Zero();
  51594. this._minBbox = BABYLON.Vector3.Zero();
  51595. this._maxBbox = BABYLON.Vector3.Zero();
  51596. this._particlesIntersect = false;
  51597. this._depthSortFunction = function (p1, p2) {
  51598. return (p2.sqDistance - p1.sqDistance);
  51599. };
  51600. this._needs32Bits = false;
  51601. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51602. this.name = name;
  51603. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51604. this._camera = scene.activeCamera;
  51605. this._pickable = options ? options.isPickable : false;
  51606. this._depthSort = options ? options.enableDepthSort : false;
  51607. this._particlesIntersect = options ? options.particleIntersection : false;
  51608. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51609. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51610. if (options && options.updatable) {
  51611. this._updatable = options.updatable;
  51612. }
  51613. else {
  51614. this._updatable = true;
  51615. }
  51616. if (this._pickable) {
  51617. this.pickedParticles = [];
  51618. }
  51619. if (this._depthSort) {
  51620. this.depthSortedParticles = [];
  51621. }
  51622. }
  51623. /**
  51624. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51625. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51626. * @returns the created mesh
  51627. */
  51628. SolidParticleSystem.prototype.buildMesh = function () {
  51629. if (this.nbParticles === 0) {
  51630. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51631. this.addShape(triangle, 1);
  51632. triangle.dispose();
  51633. }
  51634. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51635. this._positions32 = new Float32Array(this._positions);
  51636. this._uvs32 = new Float32Array(this._uvs);
  51637. this._colors32 = new Float32Array(this._colors);
  51638. if (this.recomputeNormals) {
  51639. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51640. }
  51641. this._normals32 = new Float32Array(this._normals);
  51642. this._fixedNormal32 = new Float32Array(this._normals);
  51643. if (this._mustUnrotateFixedNormals) {
  51644. this._unrotateFixedNormals();
  51645. }
  51646. var vertexData = new BABYLON.VertexData();
  51647. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51648. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51649. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51650. if (this._uvs32) {
  51651. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51652. ;
  51653. }
  51654. if (this._colors32) {
  51655. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51656. }
  51657. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51658. vertexData.applyToMesh(mesh, this._updatable);
  51659. this.mesh = mesh;
  51660. this.mesh.isPickable = this._pickable;
  51661. // free memory
  51662. if (!this._depthSort) {
  51663. this._indices = null;
  51664. }
  51665. this._positions = null;
  51666. this._normals = null;
  51667. this._uvs = null;
  51668. this._colors = null;
  51669. if (!this._updatable) {
  51670. this.particles.length = 0;
  51671. }
  51672. return mesh;
  51673. };
  51674. /**
  51675. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51676. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51677. * Thus the particles generated from `digest()` have their property `position` set yet.
  51678. * @param mesh ( Mesh ) is the mesh to be digested
  51679. * @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
  51680. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51681. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51682. * @returns the current SPS
  51683. */
  51684. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51685. var size = (options && options.facetNb) || 1;
  51686. var number = (options && options.number) || 0;
  51687. var delta = (options && options.delta) || 0;
  51688. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51689. var meshInd = mesh.getIndices();
  51690. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51691. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51692. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51693. var f = 0; // facet counter
  51694. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51695. // compute size from number
  51696. if (number) {
  51697. number = (number > totalFacets) ? totalFacets : number;
  51698. size = Math.round(totalFacets / number);
  51699. delta = 0;
  51700. }
  51701. else {
  51702. size = (size > totalFacets) ? totalFacets : size;
  51703. }
  51704. var facetPos = []; // submesh positions
  51705. var facetInd = []; // submesh indices
  51706. var facetUV = []; // submesh UV
  51707. var facetCol = []; // submesh colors
  51708. var barycenter = BABYLON.Vector3.Zero();
  51709. var sizeO = size;
  51710. while (f < totalFacets) {
  51711. size = sizeO + Math.floor((1 + delta) * Math.random());
  51712. if (f > totalFacets - size) {
  51713. size = totalFacets - f;
  51714. }
  51715. // reset temp arrays
  51716. facetPos.length = 0;
  51717. facetInd.length = 0;
  51718. facetUV.length = 0;
  51719. facetCol.length = 0;
  51720. // iterate over "size" facets
  51721. var fi = 0;
  51722. for (var j = f * 3; j < (f + size) * 3; j++) {
  51723. facetInd.push(fi);
  51724. var i = meshInd[j];
  51725. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51726. if (meshUV) {
  51727. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51728. }
  51729. if (meshCol) {
  51730. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51731. }
  51732. fi++;
  51733. }
  51734. // create a model shape for each single particle
  51735. var idx = this.nbParticles;
  51736. var shape = this._posToShape(facetPos);
  51737. var shapeUV = this._uvsToShapeUV(facetUV);
  51738. // compute the barycenter of the shape
  51739. var v;
  51740. for (v = 0; v < shape.length; v++) {
  51741. barycenter.addInPlace(shape[v]);
  51742. }
  51743. barycenter.scaleInPlace(1 / shape.length);
  51744. // shift the shape from its barycenter to the origin
  51745. for (v = 0; v < shape.length; v++) {
  51746. shape[v].subtractInPlace(barycenter);
  51747. }
  51748. var bInfo;
  51749. if (this._particlesIntersect) {
  51750. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51751. }
  51752. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51753. // add the particle in the SPS
  51754. var currentPos = this._positions.length;
  51755. var currentInd = this._indices.length;
  51756. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51757. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51758. // initialize the particle position
  51759. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51760. this._index += shape.length;
  51761. idx++;
  51762. this.nbParticles++;
  51763. this._shapeCounter++;
  51764. f += size;
  51765. }
  51766. return this;
  51767. };
  51768. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51769. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51770. var index = 0;
  51771. var idx = 0;
  51772. for (var p = 0; p < this.particles.length; p++) {
  51773. this._particle = this.particles[p];
  51774. this._shape = this._particle._model._shape;
  51775. if (this._particle.rotationQuaternion) {
  51776. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51777. }
  51778. else {
  51779. this._yaw = this._particle.rotation.y;
  51780. this._pitch = this._particle.rotation.x;
  51781. this._roll = this._particle.rotation.z;
  51782. this._quaternionRotationYPR();
  51783. }
  51784. this._quaternionToRotationMatrix();
  51785. this._rotMatrix.invertToRef(this._invertMatrix);
  51786. for (var pt = 0; pt < this._shape.length; pt++) {
  51787. idx = index + pt * 3;
  51788. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51789. this._fixedNormal32[idx] = this._normal.x;
  51790. this._fixedNormal32[idx + 1] = this._normal.y;
  51791. this._fixedNormal32[idx + 2] = this._normal.z;
  51792. }
  51793. index = idx + 3;
  51794. }
  51795. };
  51796. //reset copy
  51797. SolidParticleSystem.prototype._resetCopy = function () {
  51798. this._copy.position.x = 0;
  51799. this._copy.position.y = 0;
  51800. this._copy.position.z = 0;
  51801. this._copy.rotation.x = 0;
  51802. this._copy.rotation.y = 0;
  51803. this._copy.rotation.z = 0;
  51804. this._copy.rotationQuaternion = null;
  51805. this._copy.scaling.x = 1.0;
  51806. this._copy.scaling.y = 1.0;
  51807. this._copy.scaling.z = 1.0;
  51808. this._copy.uvs.x = 0;
  51809. this._copy.uvs.y = 0;
  51810. this._copy.uvs.z = 1.0;
  51811. this._copy.uvs.w = 1.0;
  51812. this._copy.color = null;
  51813. this._copy.translateFromPivot = false;
  51814. };
  51815. // _meshBuilder : inserts the shape model in the global SPS mesh
  51816. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51817. var i;
  51818. var u = 0;
  51819. var c = 0;
  51820. var n = 0;
  51821. this._resetCopy();
  51822. if (options && options.positionFunction) {
  51823. options.positionFunction(this._copy, idx, idxInShape);
  51824. this._mustUnrotateFixedNormals = true;
  51825. }
  51826. if (this._copy.rotationQuaternion) {
  51827. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51828. }
  51829. else {
  51830. this._yaw = this._copy.rotation.y;
  51831. this._pitch = this._copy.rotation.x;
  51832. this._roll = this._copy.rotation.z;
  51833. this._quaternionRotationYPR();
  51834. }
  51835. this._quaternionToRotationMatrix();
  51836. if (this._copy.translateFromPivot) {
  51837. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51838. }
  51839. else {
  51840. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51841. }
  51842. for (i = 0; i < shape.length; i++) {
  51843. this._vertex.x = shape[i].x;
  51844. this._vertex.y = shape[i].y;
  51845. this._vertex.z = shape[i].z;
  51846. if (options && options.vertexFunction) {
  51847. options.vertexFunction(this._copy, this._vertex, i);
  51848. }
  51849. this._vertex.x *= this._copy.scaling.x;
  51850. this._vertex.y *= this._copy.scaling.y;
  51851. this._vertex.z *= this._copy.scaling.z;
  51852. this._vertex.x -= this._copy.pivot.x;
  51853. this._vertex.y -= this._copy.pivot.y;
  51854. this._vertex.z -= this._copy.pivot.z;
  51855. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51856. this._rotated.addInPlace(this._pivotBackTranslation);
  51857. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51858. if (meshUV) {
  51859. 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);
  51860. u += 2;
  51861. }
  51862. if (this._copy.color) {
  51863. this._color = this._copy.color;
  51864. }
  51865. else if (meshCol && meshCol[c] !== undefined) {
  51866. this._color.r = meshCol[c];
  51867. this._color.g = meshCol[c + 1];
  51868. this._color.b = meshCol[c + 2];
  51869. this._color.a = meshCol[c + 3];
  51870. }
  51871. else {
  51872. this._color.r = 1.0;
  51873. this._color.g = 1.0;
  51874. this._color.b = 1.0;
  51875. this._color.a = 1.0;
  51876. }
  51877. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51878. c += 4;
  51879. if (!this.recomputeNormals && meshNor) {
  51880. this._normal.x = meshNor[n];
  51881. this._normal.y = meshNor[n + 1];
  51882. this._normal.z = meshNor[n + 2];
  51883. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51884. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51885. n += 3;
  51886. }
  51887. }
  51888. for (i = 0; i < meshInd.length; i++) {
  51889. var current_ind = p + meshInd[i];
  51890. indices.push(current_ind);
  51891. if (current_ind > 65535) {
  51892. this._needs32Bits = true;
  51893. }
  51894. }
  51895. if (this._pickable) {
  51896. var nbfaces = meshInd.length / 3;
  51897. for (i = 0; i < nbfaces; i++) {
  51898. this.pickedParticles.push({ idx: idx, faceId: i });
  51899. }
  51900. }
  51901. if (this._depthSort) {
  51902. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51903. }
  51904. return this._copy;
  51905. };
  51906. // returns a shape array from positions array
  51907. SolidParticleSystem.prototype._posToShape = function (positions) {
  51908. var shape = [];
  51909. for (var i = 0; i < positions.length; i += 3) {
  51910. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51911. }
  51912. return shape;
  51913. };
  51914. // returns a shapeUV array from a Vector4 uvs
  51915. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51916. var shapeUV = [];
  51917. if (uvs) {
  51918. for (var i = 0; i < uvs.length; i++)
  51919. shapeUV.push(uvs[i]);
  51920. }
  51921. return shapeUV;
  51922. };
  51923. // adds a new particle object in the particles array
  51924. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51925. if (bInfo === void 0) { bInfo = null; }
  51926. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51927. this.particles.push(sp);
  51928. return sp;
  51929. };
  51930. /**
  51931. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51932. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51933. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51934. * @param nb (positive integer) the number of particles to be created from this model
  51935. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51936. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51937. * @returns the number of shapes in the system
  51938. */
  51939. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51940. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51941. var meshInd = mesh.getIndices();
  51942. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51943. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51944. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51945. var bbInfo;
  51946. if (this._particlesIntersect) {
  51947. bbInfo = mesh.getBoundingInfo();
  51948. }
  51949. var shape = this._posToShape(meshPos);
  51950. var shapeUV = this._uvsToShapeUV(meshUV);
  51951. var posfunc = options ? options.positionFunction : null;
  51952. var vtxfunc = options ? options.vertexFunction : null;
  51953. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51954. // particles
  51955. var sp;
  51956. var currentCopy;
  51957. var idx = this.nbParticles;
  51958. for (var i = 0; i < nb; i++) {
  51959. var currentPos = this._positions.length;
  51960. var currentInd = this._indices.length;
  51961. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51962. if (this._updatable) {
  51963. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51964. sp.position.copyFrom(currentCopy.position);
  51965. sp.rotation.copyFrom(currentCopy.rotation);
  51966. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51967. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51968. }
  51969. if (currentCopy.color && sp.color) {
  51970. sp.color.copyFrom(currentCopy.color);
  51971. }
  51972. sp.scaling.copyFrom(currentCopy.scaling);
  51973. sp.uvs.copyFrom(currentCopy.uvs);
  51974. }
  51975. this._index += shape.length;
  51976. idx++;
  51977. }
  51978. this.nbParticles += nb;
  51979. this._shapeCounter++;
  51980. return this._shapeCounter - 1;
  51981. };
  51982. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51983. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51984. this._resetCopy();
  51985. if (particle._model._positionFunction) {
  51986. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51987. }
  51988. if (this._copy.rotationQuaternion) {
  51989. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51990. }
  51991. else {
  51992. this._yaw = this._copy.rotation.y;
  51993. this._pitch = this._copy.rotation.x;
  51994. this._roll = this._copy.rotation.z;
  51995. this._quaternionRotationYPR();
  51996. }
  51997. this._quaternionToRotationMatrix();
  51998. if (this._copy.translateFromPivot) {
  51999. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52000. }
  52001. else {
  52002. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  52003. }
  52004. this._shape = particle._model._shape;
  52005. for (var pt = 0; pt < this._shape.length; pt++) {
  52006. this._vertex.x = this._shape[pt].x;
  52007. this._vertex.y = this._shape[pt].y;
  52008. this._vertex.z = this._shape[pt].z;
  52009. if (particle._model._vertexFunction) {
  52010. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52011. }
  52012. this._vertex.x *= this._copy.scaling.x;
  52013. this._vertex.y *= this._copy.scaling.y;
  52014. this._vertex.z *= this._copy.scaling.z;
  52015. this._vertex.x -= this._copy.pivot.x;
  52016. this._vertex.y -= this._copy.pivot.y;
  52017. this._vertex.z -= this._copy.pivot.z;
  52018. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52019. this._rotated.addInPlace(this._pivotBackTranslation);
  52020. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52021. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52022. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52023. }
  52024. particle.position.x = 0.0;
  52025. particle.position.y = 0.0;
  52026. particle.position.z = 0.0;
  52027. particle.rotation.x = 0.0;
  52028. particle.rotation.y = 0.0;
  52029. particle.rotation.z = 0.0;
  52030. particle.rotationQuaternion = null;
  52031. particle.scaling.x = 1.0;
  52032. particle.scaling.y = 1.0;
  52033. particle.scaling.z = 1.0;
  52034. };
  52035. /**
  52036. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52037. * @returns the SPS.
  52038. */
  52039. SolidParticleSystem.prototype.rebuildMesh = function () {
  52040. for (var p = 0; p < this.particles.length; p++) {
  52041. this._rebuildParticle(this.particles[p]);
  52042. }
  52043. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52044. return this;
  52045. };
  52046. /**
  52047. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52048. * This method calls `updateParticle()` for each particle of the SPS.
  52049. * For an animated SPS, it is usually called within the render loop.
  52050. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52051. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52052. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52053. * @returns the SPS.
  52054. */
  52055. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52056. if (start === void 0) { start = 0; }
  52057. if (end === void 0) { end = this.nbParticles - 1; }
  52058. if (update === void 0) { update = true; }
  52059. if (!this._updatable) {
  52060. return this;
  52061. }
  52062. // custom beforeUpdate
  52063. this.beforeUpdateParticles(start, end, update);
  52064. this._cam_axisX.x = 1.0;
  52065. this._cam_axisX.y = 0.0;
  52066. this._cam_axisX.z = 0.0;
  52067. this._cam_axisY.x = 0.0;
  52068. this._cam_axisY.y = 1.0;
  52069. this._cam_axisY.z = 0.0;
  52070. this._cam_axisZ.x = 0.0;
  52071. this._cam_axisZ.y = 0.0;
  52072. this._cam_axisZ.z = 1.0;
  52073. // cases when the World Matrix is to be computed first
  52074. if (this.billboard || this._depthSort) {
  52075. this.mesh.computeWorldMatrix(true);
  52076. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52077. }
  52078. // if the particles will always face the camera
  52079. if (this.billboard) {
  52080. // compute the camera position and un-rotate it by the current mesh rotation
  52081. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52082. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52083. this._cam_axisZ.normalize();
  52084. // same for camera up vector extracted from the cam view matrix
  52085. var view = this._camera.getViewMatrix(true);
  52086. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52087. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52088. this._cam_axisY.normalize();
  52089. this._cam_axisX.normalize();
  52090. }
  52091. // if depthSort, compute the camera global position in the mesh local system
  52092. if (this._depthSort) {
  52093. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52094. }
  52095. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52096. var idx = 0; // current position index in the global array positions32
  52097. var index = 0; // position start index in the global array positions32 of the current particle
  52098. var colidx = 0; // current color index in the global array colors32
  52099. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52100. var uvidx = 0; // current uv index in the global array uvs32
  52101. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52102. var pt = 0; // current index in the particle model shape
  52103. if (this.mesh.isFacetDataEnabled) {
  52104. this._computeBoundingBox = true;
  52105. }
  52106. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52107. if (this._computeBoundingBox) {
  52108. if (start == 0 && end == this.nbParticles - 1) {
  52109. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52110. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52111. }
  52112. else {
  52113. if (this.mesh._boundingInfo) {
  52114. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52115. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52116. }
  52117. }
  52118. }
  52119. // particle loop
  52120. index = this.particles[start]._pos;
  52121. var vpos = (index / 3) | 0;
  52122. colorIndex = vpos * 4;
  52123. uvIndex = vpos * 2;
  52124. for (var p = start; p <= end; p++) {
  52125. this._particle = this.particles[p];
  52126. this._shape = this._particle._model._shape;
  52127. this._shapeUV = this._particle._model._shapeUV;
  52128. // call to custom user function to update the particle properties
  52129. this.updateParticle(this._particle);
  52130. // camera-particle distance for depth sorting
  52131. if (this._depthSort && this._depthSortParticles) {
  52132. var dsp = this.depthSortedParticles[p];
  52133. dsp.ind = this._particle._ind;
  52134. dsp.indicesLength = this._particle._model._indicesLength;
  52135. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52136. }
  52137. // skip the computations for inactive or already invisible particles
  52138. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52139. // increment indexes for the next particle
  52140. pt = this._shape.length;
  52141. index += pt * 3;
  52142. colorIndex += pt * 4;
  52143. uvIndex += pt * 2;
  52144. continue;
  52145. }
  52146. if (this._particle.isVisible) {
  52147. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52148. // particle rotation matrix
  52149. if (this.billboard) {
  52150. this._particle.rotation.x = 0.0;
  52151. this._particle.rotation.y = 0.0;
  52152. }
  52153. if (this._computeParticleRotation || this.billboard) {
  52154. if (this._particle.rotationQuaternion) {
  52155. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52156. }
  52157. else {
  52158. this._yaw = this._particle.rotation.y;
  52159. this._pitch = this._particle.rotation.x;
  52160. this._roll = this._particle.rotation.z;
  52161. this._quaternionRotationYPR();
  52162. }
  52163. this._quaternionToRotationMatrix();
  52164. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52165. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52166. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52167. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52168. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52169. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52170. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52171. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52172. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52173. }
  52174. if (this._particle.translateFromPivot) {
  52175. this._pivotBackTranslation.x = 0.0;
  52176. this._pivotBackTranslation.y = 0.0;
  52177. this._pivotBackTranslation.z = 0.0;
  52178. }
  52179. else {
  52180. this._pivotBackTranslation.x = this._particle.pivot.x;
  52181. this._pivotBackTranslation.y = this._particle.pivot.y;
  52182. this._pivotBackTranslation.z = this._particle.pivot.z;
  52183. }
  52184. // particle vertex loop
  52185. for (pt = 0; pt < this._shape.length; pt++) {
  52186. idx = index + pt * 3;
  52187. colidx = colorIndex + pt * 4;
  52188. uvidx = uvIndex + pt * 2;
  52189. this._vertex.x = this._shape[pt].x;
  52190. this._vertex.y = this._shape[pt].y;
  52191. this._vertex.z = this._shape[pt].z;
  52192. if (this._computeParticleVertex) {
  52193. this.updateParticleVertex(this._particle, this._vertex, pt);
  52194. }
  52195. // positions
  52196. this._vertex.x *= this._particle.scaling.x;
  52197. this._vertex.y *= this._particle.scaling.y;
  52198. this._vertex.z *= this._particle.scaling.z;
  52199. this._vertex.x -= this._particle.pivot.x;
  52200. this._vertex.y -= this._particle.pivot.y;
  52201. this._vertex.z -= this._particle.pivot.z;
  52202. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52203. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52204. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52205. this._rotated.x += this._pivotBackTranslation.x;
  52206. this._rotated.y += this._pivotBackTranslation.y;
  52207. this._rotated.z += this._pivotBackTranslation.z;
  52208. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52209. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52210. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52211. if (this._computeBoundingBox) {
  52212. if (this._positions32[idx] < this._minimum.x) {
  52213. this._minimum.x = this._positions32[idx];
  52214. }
  52215. if (this._positions32[idx] > this._maximum.x) {
  52216. this._maximum.x = this._positions32[idx];
  52217. }
  52218. if (this._positions32[idx + 1] < this._minimum.y) {
  52219. this._minimum.y = this._positions32[idx + 1];
  52220. }
  52221. if (this._positions32[idx + 1] > this._maximum.y) {
  52222. this._maximum.y = this._positions32[idx + 1];
  52223. }
  52224. if (this._positions32[idx + 2] < this._minimum.z) {
  52225. this._minimum.z = this._positions32[idx + 2];
  52226. }
  52227. if (this._positions32[idx + 2] > this._maximum.z) {
  52228. this._maximum.z = this._positions32[idx + 2];
  52229. }
  52230. }
  52231. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52232. if (!this._computeParticleVertex) {
  52233. this._normal.x = this._fixedNormal32[idx];
  52234. this._normal.y = this._fixedNormal32[idx + 1];
  52235. this._normal.z = this._fixedNormal32[idx + 2];
  52236. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52237. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52238. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52239. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52240. 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;
  52241. 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;
  52242. }
  52243. if (this._computeParticleColor && this._particle.color) {
  52244. this._colors32[colidx] = this._particle.color.r;
  52245. this._colors32[colidx + 1] = this._particle.color.g;
  52246. this._colors32[colidx + 2] = this._particle.color.b;
  52247. this._colors32[colidx + 3] = this._particle.color.a;
  52248. }
  52249. if (this._computeParticleTexture) {
  52250. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52251. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52252. }
  52253. }
  52254. }
  52255. else {
  52256. this._particle._stillInvisible = true; // mark the particle as invisible
  52257. for (pt = 0; pt < this._shape.length; pt++) {
  52258. idx = index + pt * 3;
  52259. colidx = colorIndex + pt * 4;
  52260. uvidx = uvIndex + pt * 2;
  52261. this._positions32[idx] = 0.0;
  52262. this._positions32[idx + 1] = 0.0;
  52263. this._positions32[idx + 2] = 0.0;
  52264. this._normals32[idx] = 0.0;
  52265. this._normals32[idx + 1] = 0.0;
  52266. this._normals32[idx + 2] = 0.0;
  52267. if (this._computeParticleColor && this._particle.color) {
  52268. this._colors32[colidx] = this._particle.color.r;
  52269. this._colors32[colidx + 1] = this._particle.color.g;
  52270. this._colors32[colidx + 2] = this._particle.color.b;
  52271. this._colors32[colidx + 3] = this._particle.color.a;
  52272. }
  52273. if (this._computeParticleTexture) {
  52274. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52275. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52276. }
  52277. }
  52278. }
  52279. // if the particle intersections must be computed : update the bbInfo
  52280. if (this._particlesIntersect) {
  52281. var bInfo = this._particle._boundingInfo;
  52282. var bBox = bInfo.boundingBox;
  52283. var bSphere = bInfo.boundingSphere;
  52284. if (!this._bSphereOnly) {
  52285. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52286. for (var b = 0; b < bBox.vectors.length; b++) {
  52287. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52288. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52289. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52290. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52291. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52292. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52293. 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;
  52294. 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;
  52295. 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;
  52296. }
  52297. bBox._update(this.mesh._worldMatrix);
  52298. }
  52299. // place and scale the particle bouding sphere in the SPS local system, then update it
  52300. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52301. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52302. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52303. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52304. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52305. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52306. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52307. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52308. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52309. 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));
  52310. bSphere._update(this.mesh._worldMatrix);
  52311. }
  52312. // increment indexes for the next particle
  52313. index = idx + 3;
  52314. colorIndex = colidx + 4;
  52315. uvIndex = uvidx + 2;
  52316. }
  52317. // if the VBO must be updated
  52318. if (update) {
  52319. if (this._computeParticleColor) {
  52320. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52321. }
  52322. if (this._computeParticleTexture) {
  52323. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52324. }
  52325. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52326. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52327. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52328. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52329. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52330. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52331. for (var i = 0; i < this._normals32.length; i++) {
  52332. this._fixedNormal32[i] = this._normals32[i];
  52333. }
  52334. }
  52335. if (!this.mesh.areNormalsFrozen) {
  52336. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52337. }
  52338. }
  52339. if (this._depthSort && this._depthSortParticles) {
  52340. this.depthSortedParticles.sort(this._depthSortFunction);
  52341. var dspl = this.depthSortedParticles.length;
  52342. var sorted = 0;
  52343. var lind = 0;
  52344. var sind = 0;
  52345. var sid = 0;
  52346. for (sorted = 0; sorted < dspl; sorted++) {
  52347. lind = this.depthSortedParticles[sorted].indicesLength;
  52348. sind = this.depthSortedParticles[sorted].ind;
  52349. for (var i = 0; i < lind; i++) {
  52350. this._indices32[sid] = this._indices[sind + i];
  52351. sid++;
  52352. }
  52353. }
  52354. this.mesh.updateIndices(this._indices32);
  52355. }
  52356. }
  52357. if (this._computeBoundingBox) {
  52358. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52359. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52360. }
  52361. this.afterUpdateParticles(start, end, update);
  52362. return this;
  52363. };
  52364. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52365. this._halfroll = this._roll * 0.5;
  52366. this._halfpitch = this._pitch * 0.5;
  52367. this._halfyaw = this._yaw * 0.5;
  52368. this._sinRoll = Math.sin(this._halfroll);
  52369. this._cosRoll = Math.cos(this._halfroll);
  52370. this._sinPitch = Math.sin(this._halfpitch);
  52371. this._cosPitch = Math.cos(this._halfpitch);
  52372. this._sinYaw = Math.sin(this._halfyaw);
  52373. this._cosYaw = Math.cos(this._halfyaw);
  52374. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52375. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52376. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52377. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52378. };
  52379. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52380. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52381. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52382. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52383. this._rotMatrix.m[3] = 0;
  52384. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52385. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52386. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52387. this._rotMatrix.m[7] = 0;
  52388. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52389. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52390. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52391. this._rotMatrix.m[11] = 0;
  52392. this._rotMatrix.m[12] = 0;
  52393. this._rotMatrix.m[13] = 0;
  52394. this._rotMatrix.m[14] = 0;
  52395. this._rotMatrix.m[15] = 1.0;
  52396. };
  52397. /**
  52398. * Disposes the SPS.
  52399. */
  52400. SolidParticleSystem.prototype.dispose = function () {
  52401. this.mesh.dispose();
  52402. this.vars = null;
  52403. // drop references to internal big arrays for the GC
  52404. this._positions = null;
  52405. this._indices = null;
  52406. this._normals = null;
  52407. this._uvs = null;
  52408. this._colors = null;
  52409. this._indices32 = null;
  52410. this._positions32 = null;
  52411. this._normals32 = null;
  52412. this._fixedNormal32 = null;
  52413. this._uvs32 = null;
  52414. this._colors32 = null;
  52415. this.pickedParticles = null;
  52416. };
  52417. /**
  52418. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52419. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52420. * @returns the SPS.
  52421. */
  52422. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52423. if (!this._isVisibilityBoxLocked) {
  52424. this.mesh.refreshBoundingInfo();
  52425. }
  52426. return this;
  52427. };
  52428. /**
  52429. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52430. * @param size the size (float) of the visibility box
  52431. * note : this doesn't lock the SPS mesh bounding box.
  52432. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52433. */
  52434. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52435. var vis = size / 2;
  52436. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52437. };
  52438. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52439. /**
  52440. * Gets whether the SPS as always visible or not
  52441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52442. */
  52443. get: function () {
  52444. return this._alwaysVisible;
  52445. },
  52446. /**
  52447. * Sets the SPS as always visible or not
  52448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52449. */
  52450. set: function (val) {
  52451. this._alwaysVisible = val;
  52452. this.mesh.alwaysSelectAsActiveMesh = val;
  52453. },
  52454. enumerable: true,
  52455. configurable: true
  52456. });
  52457. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52458. /**
  52459. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52461. */
  52462. get: function () {
  52463. return this._isVisibilityBoxLocked;
  52464. },
  52465. /**
  52466. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52467. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52468. */
  52469. set: function (val) {
  52470. this._isVisibilityBoxLocked = val;
  52471. var boundingInfo = this.mesh.getBoundingInfo();
  52472. boundingInfo.isLocked = val;
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52478. /**
  52479. * Gets if `setParticles()` computes the particle rotations or not.
  52480. * Default value : true. The SPS is faster when it's set to false.
  52481. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52482. */
  52483. get: function () {
  52484. return this._computeParticleRotation;
  52485. },
  52486. /**
  52487. * Tells to `setParticles()` to compute the particle rotations or not.
  52488. * Default value : true. The SPS is faster when it's set to false.
  52489. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52490. */
  52491. set: function (val) {
  52492. this._computeParticleRotation = val;
  52493. },
  52494. enumerable: true,
  52495. configurable: true
  52496. });
  52497. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52498. /**
  52499. * Gets if `setParticles()` computes the particle colors or not.
  52500. * Default value : true. The SPS is faster when it's set to false.
  52501. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52502. */
  52503. get: function () {
  52504. return this._computeParticleColor;
  52505. },
  52506. /**
  52507. * Tells to `setParticles()` to compute the particle colors or not.
  52508. * Default value : true. The SPS is faster when it's set to false.
  52509. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52510. */
  52511. set: function (val) {
  52512. this._computeParticleColor = val;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52518. /**
  52519. * Gets if `setParticles()` computes the particle textures or not.
  52520. * Default value : true. The SPS is faster when it's set to false.
  52521. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52522. */
  52523. get: function () {
  52524. return this._computeParticleTexture;
  52525. },
  52526. set: function (val) {
  52527. this._computeParticleTexture = val;
  52528. },
  52529. enumerable: true,
  52530. configurable: true
  52531. });
  52532. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52533. /**
  52534. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52535. * Default value : false. The SPS is faster when it's set to false.
  52536. * Note : the particle custom vertex positions aren't stored values.
  52537. */
  52538. get: function () {
  52539. return this._computeParticleVertex;
  52540. },
  52541. /**
  52542. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52543. * Default value : false. The SPS is faster when it's set to false.
  52544. * Note : the particle custom vertex positions aren't stored values.
  52545. */
  52546. set: function (val) {
  52547. this._computeParticleVertex = val;
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52553. /**
  52554. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52555. */
  52556. get: function () {
  52557. return this._computeBoundingBox;
  52558. },
  52559. /**
  52560. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52561. */
  52562. set: function (val) {
  52563. this._computeBoundingBox = val;
  52564. },
  52565. enumerable: true,
  52566. configurable: true
  52567. });
  52568. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52569. /**
  52570. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52571. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52572. * Default : `true`
  52573. */
  52574. get: function () {
  52575. return this._depthSortParticles;
  52576. },
  52577. /**
  52578. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52579. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52580. * Default : `true`
  52581. */
  52582. set: function (val) {
  52583. this._depthSortParticles = val;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. // =======================================================================
  52589. // Particle behavior logic
  52590. // these following methods may be overwritten by the user to fit his needs
  52591. /**
  52592. * This function does nothing. It may be overwritten to set all the particle first values.
  52593. * The SPS doesn't call this function, you may have to call it by your own.
  52594. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52595. */
  52596. SolidParticleSystem.prototype.initParticles = function () {
  52597. };
  52598. /**
  52599. * This function does nothing. It may be overwritten to recycle a particle.
  52600. * The SPS doesn't call this function, you may have to call it by your own.
  52601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52602. * @param particle The particle to recycle
  52603. * @returns the recycled particle
  52604. */
  52605. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52606. return particle;
  52607. };
  52608. /**
  52609. * Updates a particle : this function should be overwritten by the user.
  52610. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52611. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52612. * @example : just set a particle position or velocity and recycle conditions
  52613. * @param particle The particle to update
  52614. * @returns the updated particle
  52615. */
  52616. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52617. return particle;
  52618. };
  52619. /**
  52620. * Updates a vertex of a particle : it can be overwritten by the user.
  52621. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52622. * @param particle the current particle
  52623. * @param vertex the current index of the current particle
  52624. * @param pt the index of the current vertex in the particle shape
  52625. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52626. * @example : just set a vertex particle position
  52627. * @returns the updated vertex
  52628. */
  52629. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52630. return vertex;
  52631. };
  52632. /**
  52633. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52634. * This does nothing and may be overwritten by the user.
  52635. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52636. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52637. * @param update the boolean update value actually passed to setParticles()
  52638. */
  52639. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52640. };
  52641. /**
  52642. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52643. * This will be passed three parameters.
  52644. * This does nothing and may be overwritten by the user.
  52645. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52646. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52647. * @param update the boolean update value actually passed to setParticles()
  52648. */
  52649. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52650. };
  52651. return SolidParticleSystem;
  52652. }());
  52653. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52654. })(BABYLON || (BABYLON = {}));
  52655. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52656. var BABYLON;
  52657. (function (BABYLON) {
  52658. var ShaderMaterial = /** @class */ (function (_super) {
  52659. __extends(ShaderMaterial, _super);
  52660. function ShaderMaterial(name, scene, shaderPath, options) {
  52661. var _this = _super.call(this, name, scene) || this;
  52662. _this._textures = {};
  52663. _this._textureArrays = {};
  52664. _this._floats = {};
  52665. _this._ints = {};
  52666. _this._floatsArrays = {};
  52667. _this._colors3 = {};
  52668. _this._colors3Arrays = {};
  52669. _this._colors4 = {};
  52670. _this._vectors2 = {};
  52671. _this._vectors3 = {};
  52672. _this._vectors4 = {};
  52673. _this._matrices = {};
  52674. _this._matrices3x3 = {};
  52675. _this._matrices2x2 = {};
  52676. _this._vectors2Arrays = {};
  52677. _this._vectors3Arrays = {};
  52678. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52679. _this._shaderPath = shaderPath;
  52680. options.needAlphaBlending = options.needAlphaBlending || false;
  52681. options.needAlphaTesting = options.needAlphaTesting || false;
  52682. options.attributes = options.attributes || ["position", "normal", "uv"];
  52683. options.uniforms = options.uniforms || ["worldViewProjection"];
  52684. options.uniformBuffers = options.uniformBuffers || [];
  52685. options.samplers = options.samplers || [];
  52686. options.defines = options.defines || [];
  52687. _this._options = options;
  52688. return _this;
  52689. }
  52690. ShaderMaterial.prototype.getClassName = function () {
  52691. return "ShaderMaterial";
  52692. };
  52693. ShaderMaterial.prototype.needAlphaBlending = function () {
  52694. return this._options.needAlphaBlending;
  52695. };
  52696. ShaderMaterial.prototype.needAlphaTesting = function () {
  52697. return this._options.needAlphaTesting;
  52698. };
  52699. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52700. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52701. this._options.uniforms.push(uniformName);
  52702. }
  52703. };
  52704. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52705. if (this._options.samplers.indexOf(name) === -1) {
  52706. this._options.samplers.push(name);
  52707. }
  52708. this._textures[name] = texture;
  52709. return this;
  52710. };
  52711. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52712. if (this._options.samplers.indexOf(name) === -1) {
  52713. this._options.samplers.push(name);
  52714. }
  52715. this._checkUniform(name);
  52716. this._textureArrays[name] = textures;
  52717. return this;
  52718. };
  52719. ShaderMaterial.prototype.setFloat = function (name, value) {
  52720. this._checkUniform(name);
  52721. this._floats[name] = value;
  52722. return this;
  52723. };
  52724. ShaderMaterial.prototype.setInt = function (name, value) {
  52725. this._checkUniform(name);
  52726. this._ints[name] = value;
  52727. return this;
  52728. };
  52729. ShaderMaterial.prototype.setFloats = function (name, value) {
  52730. this._checkUniform(name);
  52731. this._floatsArrays[name] = value;
  52732. return this;
  52733. };
  52734. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52735. this._checkUniform(name);
  52736. this._colors3[name] = value;
  52737. return this;
  52738. };
  52739. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52740. this._checkUniform(name);
  52741. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52742. color.toArray(arr, arr.length);
  52743. return arr;
  52744. }, []);
  52745. return this;
  52746. };
  52747. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52748. this._checkUniform(name);
  52749. this._colors4[name] = value;
  52750. return this;
  52751. };
  52752. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52753. this._checkUniform(name);
  52754. this._vectors2[name] = value;
  52755. return this;
  52756. };
  52757. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52758. this._checkUniform(name);
  52759. this._vectors3[name] = value;
  52760. return this;
  52761. };
  52762. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52763. this._checkUniform(name);
  52764. this._vectors4[name] = value;
  52765. return this;
  52766. };
  52767. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52768. this._checkUniform(name);
  52769. this._matrices[name] = value;
  52770. return this;
  52771. };
  52772. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52773. this._checkUniform(name);
  52774. this._matrices3x3[name] = value;
  52775. return this;
  52776. };
  52777. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52778. this._checkUniform(name);
  52779. this._matrices2x2[name] = value;
  52780. return this;
  52781. };
  52782. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52783. this._checkUniform(name);
  52784. this._vectors2Arrays[name] = value;
  52785. return this;
  52786. };
  52787. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52788. this._checkUniform(name);
  52789. this._vectors3Arrays[name] = value;
  52790. return this;
  52791. };
  52792. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52793. if (!mesh) {
  52794. return true;
  52795. }
  52796. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52797. return false;
  52798. }
  52799. return false;
  52800. };
  52801. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52802. var scene = this.getScene();
  52803. var engine = scene.getEngine();
  52804. if (!this.checkReadyOnEveryCall) {
  52805. if (this._renderId === scene.getRenderId()) {
  52806. if (this._checkCache(scene, mesh, useInstances)) {
  52807. return true;
  52808. }
  52809. }
  52810. }
  52811. // Instances
  52812. var defines = [];
  52813. var attribs = [];
  52814. var fallbacks = new BABYLON.EffectFallbacks();
  52815. if (useInstances) {
  52816. defines.push("#define INSTANCES");
  52817. }
  52818. for (var index = 0; index < this._options.defines.length; index++) {
  52819. defines.push(this._options.defines[index]);
  52820. }
  52821. for (var index = 0; index < this._options.attributes.length; index++) {
  52822. attribs.push(this._options.attributes[index]);
  52823. }
  52824. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52825. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52826. defines.push("#define VERTEXCOLOR");
  52827. }
  52828. // Bones
  52829. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52830. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52831. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52832. if (mesh.numBoneInfluencers > 4) {
  52833. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52834. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52835. }
  52836. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52837. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52838. fallbacks.addCPUSkinningFallback(0, mesh);
  52839. if (this._options.uniforms.indexOf("mBones") === -1) {
  52840. this._options.uniforms.push("mBones");
  52841. }
  52842. }
  52843. else {
  52844. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52845. }
  52846. // Textures
  52847. for (var name in this._textures) {
  52848. if (!this._textures[name].isReady()) {
  52849. return false;
  52850. }
  52851. }
  52852. // Alpha test
  52853. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52854. defines.push("#define ALPHATEST");
  52855. }
  52856. var previousEffect = this._effect;
  52857. var join = defines.join("\n");
  52858. this._effect = engine.createEffect(this._shaderPath, {
  52859. attributes: attribs,
  52860. uniformsNames: this._options.uniforms,
  52861. uniformBuffersNames: this._options.uniformBuffers,
  52862. samplers: this._options.samplers,
  52863. defines: join,
  52864. fallbacks: fallbacks,
  52865. onCompiled: this.onCompiled,
  52866. onError: this.onError
  52867. }, engine);
  52868. if (!this._effect.isReady()) {
  52869. return false;
  52870. }
  52871. if (previousEffect !== this._effect) {
  52872. scene.resetCachedMaterial();
  52873. }
  52874. this._renderId = scene.getRenderId();
  52875. return true;
  52876. };
  52877. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52878. var scene = this.getScene();
  52879. if (!this._effect) {
  52880. return;
  52881. }
  52882. if (this._options.uniforms.indexOf("world") !== -1) {
  52883. this._effect.setMatrix("world", world);
  52884. }
  52885. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52886. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52887. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52888. }
  52889. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52890. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52891. }
  52892. };
  52893. ShaderMaterial.prototype.bind = function (world, mesh) {
  52894. // Std values
  52895. this.bindOnlyWorldMatrix(world);
  52896. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52897. if (this._options.uniforms.indexOf("view") !== -1) {
  52898. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52899. }
  52900. if (this._options.uniforms.indexOf("projection") !== -1) {
  52901. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52902. }
  52903. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52904. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52905. }
  52906. // Bones
  52907. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52908. var name;
  52909. // Texture
  52910. for (name in this._textures) {
  52911. this._effect.setTexture(name, this._textures[name]);
  52912. }
  52913. // Texture arrays
  52914. for (name in this._textureArrays) {
  52915. this._effect.setTextureArray(name, this._textureArrays[name]);
  52916. }
  52917. // Int
  52918. for (name in this._ints) {
  52919. this._effect.setInt(name, this._ints[name]);
  52920. }
  52921. // Float
  52922. for (name in this._floats) {
  52923. this._effect.setFloat(name, this._floats[name]);
  52924. }
  52925. // Floats
  52926. for (name in this._floatsArrays) {
  52927. this._effect.setArray(name, this._floatsArrays[name]);
  52928. }
  52929. // Color3
  52930. for (name in this._colors3) {
  52931. this._effect.setColor3(name, this._colors3[name]);
  52932. }
  52933. for (name in this._colors3Arrays) {
  52934. this._effect.setArray3(name, this._colors3Arrays[name]);
  52935. }
  52936. // Color4
  52937. for (name in this._colors4) {
  52938. var color = this._colors4[name];
  52939. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52940. }
  52941. // Vector2
  52942. for (name in this._vectors2) {
  52943. this._effect.setVector2(name, this._vectors2[name]);
  52944. }
  52945. // Vector3
  52946. for (name in this._vectors3) {
  52947. this._effect.setVector3(name, this._vectors3[name]);
  52948. }
  52949. // Vector4
  52950. for (name in this._vectors4) {
  52951. this._effect.setVector4(name, this._vectors4[name]);
  52952. }
  52953. // Matrix
  52954. for (name in this._matrices) {
  52955. this._effect.setMatrix(name, this._matrices[name]);
  52956. }
  52957. // Matrix 3x3
  52958. for (name in this._matrices3x3) {
  52959. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52960. }
  52961. // Matrix 2x2
  52962. for (name in this._matrices2x2) {
  52963. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52964. }
  52965. // Vector2Array
  52966. for (name in this._vectors2Arrays) {
  52967. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52968. }
  52969. // Vector3Array
  52970. for (name in this._vectors3Arrays) {
  52971. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52972. }
  52973. }
  52974. this._afterBind(mesh);
  52975. };
  52976. ShaderMaterial.prototype.getActiveTextures = function () {
  52977. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52978. for (var name in this._textures) {
  52979. activeTextures.push(this._textures[name]);
  52980. }
  52981. for (var name in this._textureArrays) {
  52982. var array = this._textureArrays[name];
  52983. for (var index = 0; index < array.length; index++) {
  52984. activeTextures.push(array[index]);
  52985. }
  52986. }
  52987. return activeTextures;
  52988. };
  52989. ShaderMaterial.prototype.hasTexture = function (texture) {
  52990. if (_super.prototype.hasTexture.call(this, texture)) {
  52991. return true;
  52992. }
  52993. for (var name in this._textures) {
  52994. if (this._textures[name] === texture) {
  52995. return true;
  52996. }
  52997. }
  52998. for (var name in this._textureArrays) {
  52999. var array = this._textureArrays[name];
  53000. for (var index = 0; index < array.length; index++) {
  53001. if (array[index] === texture) {
  53002. return true;
  53003. }
  53004. }
  53005. }
  53006. return false;
  53007. };
  53008. ShaderMaterial.prototype.clone = function (name) {
  53009. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53010. return newShaderMaterial;
  53011. };
  53012. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53013. if (forceDisposeTextures) {
  53014. var name;
  53015. for (name in this._textures) {
  53016. this._textures[name].dispose();
  53017. }
  53018. for (name in this._textureArrays) {
  53019. var array = this._textureArrays[name];
  53020. for (var index = 0; index < array.length; index++) {
  53021. array[index].dispose();
  53022. }
  53023. }
  53024. }
  53025. this._textures = {};
  53026. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53027. };
  53028. ShaderMaterial.prototype.serialize = function () {
  53029. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53030. serializationObject.customType = "BABYLON.ShaderMaterial";
  53031. serializationObject.options = this._options;
  53032. serializationObject.shaderPath = this._shaderPath;
  53033. var name;
  53034. // Texture
  53035. serializationObject.textures = {};
  53036. for (name in this._textures) {
  53037. serializationObject.textures[name] = this._textures[name].serialize();
  53038. }
  53039. // Texture arrays
  53040. serializationObject.textureArrays = {};
  53041. for (name in this._textureArrays) {
  53042. serializationObject.textureArrays[name] = [];
  53043. var array = this._textureArrays[name];
  53044. for (var index = 0; index < array.length; index++) {
  53045. serializationObject.textureArrays[name].push(array[index].serialize());
  53046. }
  53047. }
  53048. // Float
  53049. serializationObject.floats = {};
  53050. for (name in this._floats) {
  53051. serializationObject.floats[name] = this._floats[name];
  53052. }
  53053. // Float s
  53054. serializationObject.FloatArrays = {};
  53055. for (name in this._floatsArrays) {
  53056. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53057. }
  53058. // Color3
  53059. serializationObject.colors3 = {};
  53060. for (name in this._colors3) {
  53061. serializationObject.colors3[name] = this._colors3[name].asArray();
  53062. }
  53063. // Color3 array
  53064. serializationObject.colors3Arrays = {};
  53065. for (name in this._colors3Arrays) {
  53066. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53067. }
  53068. // Color4
  53069. serializationObject.colors4 = {};
  53070. for (name in this._colors4) {
  53071. serializationObject.colors4[name] = this._colors4[name].asArray();
  53072. }
  53073. // Vector2
  53074. serializationObject.vectors2 = {};
  53075. for (name in this._vectors2) {
  53076. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53077. }
  53078. // Vector3
  53079. serializationObject.vectors3 = {};
  53080. for (name in this._vectors3) {
  53081. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53082. }
  53083. // Vector4
  53084. serializationObject.vectors4 = {};
  53085. for (name in this._vectors4) {
  53086. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53087. }
  53088. // Matrix
  53089. serializationObject.matrices = {};
  53090. for (name in this._matrices) {
  53091. serializationObject.matrices[name] = this._matrices[name].asArray();
  53092. }
  53093. // Matrix 3x3
  53094. serializationObject.matrices3x3 = {};
  53095. for (name in this._matrices3x3) {
  53096. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53097. }
  53098. // Matrix 2x2
  53099. serializationObject.matrices2x2 = {};
  53100. for (name in this._matrices2x2) {
  53101. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53102. }
  53103. // Vector2Array
  53104. serializationObject.vectors2Arrays = {};
  53105. for (name in this._vectors2Arrays) {
  53106. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53107. }
  53108. // Vector3Array
  53109. serializationObject.vectors3Arrays = {};
  53110. for (name in this._vectors3Arrays) {
  53111. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53112. }
  53113. return serializationObject;
  53114. };
  53115. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53116. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53117. var name;
  53118. // Texture
  53119. for (name in source.textures) {
  53120. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53121. }
  53122. // Texture arrays
  53123. for (name in source.textureArrays) {
  53124. var array = source.textureArrays[name];
  53125. var textureArray = new Array();
  53126. for (var index = 0; index < array.length; index++) {
  53127. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53128. }
  53129. material.setTextureArray(name, textureArray);
  53130. }
  53131. // Float
  53132. for (name in source.floats) {
  53133. material.setFloat(name, source.floats[name]);
  53134. }
  53135. // Float s
  53136. for (name in source.floatsArrays) {
  53137. material.setFloats(name, source.floatsArrays[name]);
  53138. }
  53139. // Color3
  53140. for (name in source.colors3) {
  53141. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53142. }
  53143. // Color3 arrays
  53144. for (name in source.colors3Arrays) {
  53145. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53146. if (i % 3 === 0) {
  53147. arr.push([num]);
  53148. }
  53149. else {
  53150. arr[arr.length - 1].push(num);
  53151. }
  53152. return arr;
  53153. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53154. material.setColor3Array(name, colors);
  53155. }
  53156. // Color4
  53157. for (name in source.colors4) {
  53158. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53159. }
  53160. // Vector2
  53161. for (name in source.vectors2) {
  53162. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53163. }
  53164. // Vector3
  53165. for (name in source.vectors3) {
  53166. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53167. }
  53168. // Vector4
  53169. for (name in source.vectors4) {
  53170. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53171. }
  53172. // Matrix
  53173. for (name in source.matrices) {
  53174. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53175. }
  53176. // Matrix 3x3
  53177. for (name in source.matrices3x3) {
  53178. material.setMatrix3x3(name, source.matrices3x3[name]);
  53179. }
  53180. // Matrix 2x2
  53181. for (name in source.matrices2x2) {
  53182. material.setMatrix2x2(name, source.matrices2x2[name]);
  53183. }
  53184. // Vector2Array
  53185. for (name in source.vectors2Arrays) {
  53186. material.setArray2(name, source.vectors2Arrays[name]);
  53187. }
  53188. // Vector3Array
  53189. for (name in source.vectors3Arrays) {
  53190. material.setArray3(name, source.vectors3Arrays[name]);
  53191. }
  53192. return material;
  53193. };
  53194. return ShaderMaterial;
  53195. }(BABYLON.Material));
  53196. BABYLON.ShaderMaterial = ShaderMaterial;
  53197. })(BABYLON || (BABYLON = {}));
  53198. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53199. var BABYLON;
  53200. (function (BABYLON) {
  53201. var GroundMesh = /** @class */ (function (_super) {
  53202. __extends(GroundMesh, _super);
  53203. function GroundMesh(name, scene) {
  53204. var _this = _super.call(this, name, scene) || this;
  53205. _this.generateOctree = false;
  53206. return _this;
  53207. }
  53208. GroundMesh.prototype.getClassName = function () {
  53209. return "GroundMesh";
  53210. };
  53211. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53212. get: function () {
  53213. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53214. },
  53215. enumerable: true,
  53216. configurable: true
  53217. });
  53218. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53219. get: function () {
  53220. return this._subdivisionsX;
  53221. },
  53222. enumerable: true,
  53223. configurable: true
  53224. });
  53225. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53226. get: function () {
  53227. return this._subdivisionsY;
  53228. },
  53229. enumerable: true,
  53230. configurable: true
  53231. });
  53232. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53233. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53234. this._subdivisionsX = chunksCount;
  53235. this._subdivisionsY = chunksCount;
  53236. this.subdivide(chunksCount);
  53237. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53238. };
  53239. /**
  53240. * Returns a height (y) value in the Worl system :
  53241. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53242. * Returns the ground y position if (x, z) are outside the ground surface.
  53243. */
  53244. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53245. var world = this.getWorldMatrix();
  53246. var invMat = BABYLON.Tmp.Matrix[5];
  53247. world.invertToRef(invMat);
  53248. var tmpVect = BABYLON.Tmp.Vector3[8];
  53249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53250. x = tmpVect.x;
  53251. z = tmpVect.z;
  53252. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53253. return this.position.y;
  53254. }
  53255. if (!this._heightQuads || this._heightQuads.length == 0) {
  53256. this._initHeightQuads();
  53257. this._computeHeightQuads();
  53258. }
  53259. var facet = this._getFacetAt(x, z);
  53260. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53261. // return y in the World system
  53262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53263. return tmpVect.y;
  53264. };
  53265. /**
  53266. * Returns a normalized vector (Vector3) orthogonal to the ground
  53267. * at the ground coordinates (x, z) expressed in the World system.
  53268. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53269. */
  53270. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53271. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53272. this.getNormalAtCoordinatesToRef(x, z, normal);
  53273. return normal;
  53274. };
  53275. /**
  53276. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53277. * at the ground coordinates (x, z) expressed in the World system.
  53278. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53279. * Returns the GroundMesh.
  53280. */
  53281. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53282. var world = this.getWorldMatrix();
  53283. var tmpMat = BABYLON.Tmp.Matrix[5];
  53284. world.invertToRef(tmpMat);
  53285. var tmpVect = BABYLON.Tmp.Vector3[8];
  53286. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53287. x = tmpVect.x;
  53288. z = tmpVect.z;
  53289. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53290. return this;
  53291. }
  53292. if (!this._heightQuads || this._heightQuads.length == 0) {
  53293. this._initHeightQuads();
  53294. this._computeHeightQuads();
  53295. }
  53296. var facet = this._getFacetAt(x, z);
  53297. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53298. return this;
  53299. };
  53300. /**
  53301. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53302. * if the ground has been updated.
  53303. * This can be used in the render loop.
  53304. * Returns the GroundMesh.
  53305. */
  53306. GroundMesh.prototype.updateCoordinateHeights = function () {
  53307. if (!this._heightQuads || this._heightQuads.length == 0) {
  53308. this._initHeightQuads();
  53309. }
  53310. this._computeHeightQuads();
  53311. return this;
  53312. };
  53313. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53314. GroundMesh.prototype._getFacetAt = function (x, z) {
  53315. // retrieve col and row from x, z coordinates in the ground local system
  53316. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53317. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53318. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53319. var facet;
  53320. if (z < quad.slope.x * x + quad.slope.y) {
  53321. facet = quad.facet1;
  53322. }
  53323. else {
  53324. facet = quad.facet2;
  53325. }
  53326. return facet;
  53327. };
  53328. // Creates and populates the heightMap array with "facet" elements :
  53329. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53330. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53331. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53332. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53333. // Returns the GroundMesh.
  53334. GroundMesh.prototype._initHeightQuads = function () {
  53335. var subdivisionsX = this._subdivisionsX;
  53336. var subdivisionsY = this._subdivisionsY;
  53337. this._heightQuads = new Array();
  53338. for (var row = 0; row < subdivisionsY; row++) {
  53339. for (var col = 0; col < subdivisionsX; col++) {
  53340. 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) };
  53341. this._heightQuads[row * subdivisionsX + col] = quad;
  53342. }
  53343. }
  53344. return this;
  53345. };
  53346. // Compute each quad element values and update the the heightMap array :
  53347. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53348. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53349. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53350. // Returns the GroundMesh.
  53351. GroundMesh.prototype._computeHeightQuads = function () {
  53352. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53353. if (!positions) {
  53354. return this;
  53355. }
  53356. var v1 = BABYLON.Tmp.Vector3[3];
  53357. var v2 = BABYLON.Tmp.Vector3[2];
  53358. var v3 = BABYLON.Tmp.Vector3[1];
  53359. var v4 = BABYLON.Tmp.Vector3[0];
  53360. var v1v2 = BABYLON.Tmp.Vector3[4];
  53361. var v1v3 = BABYLON.Tmp.Vector3[5];
  53362. var v1v4 = BABYLON.Tmp.Vector3[6];
  53363. var norm1 = BABYLON.Tmp.Vector3[7];
  53364. var norm2 = BABYLON.Tmp.Vector3[8];
  53365. var i = 0;
  53366. var j = 0;
  53367. var k = 0;
  53368. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53369. var h = 0;
  53370. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53371. var d2 = 0;
  53372. var subdivisionsX = this._subdivisionsX;
  53373. var subdivisionsY = this._subdivisionsY;
  53374. for (var row = 0; row < subdivisionsY; row++) {
  53375. for (var col = 0; col < subdivisionsX; col++) {
  53376. i = col * 3;
  53377. j = row * (subdivisionsX + 1) * 3;
  53378. k = (row + 1) * (subdivisionsX + 1) * 3;
  53379. v1.x = positions[j + i];
  53380. v1.y = positions[j + i + 1];
  53381. v1.z = positions[j + i + 2];
  53382. v2.x = positions[j + i + 3];
  53383. v2.y = positions[j + i + 4];
  53384. v2.z = positions[j + i + 5];
  53385. v3.x = positions[k + i];
  53386. v3.y = positions[k + i + 1];
  53387. v3.z = positions[k + i + 2];
  53388. v4.x = positions[k + i + 3];
  53389. v4.y = positions[k + i + 4];
  53390. v4.z = positions[k + i + 5];
  53391. // 2D slope V1V4
  53392. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53393. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53394. // facet equations :
  53395. // we compute each facet normal vector
  53396. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53397. // we compute the value d by applying the equation to v1 which belongs to the plane
  53398. // then we store the facet equation in a Vector4
  53399. v2.subtractToRef(v1, v1v2);
  53400. v3.subtractToRef(v1, v1v3);
  53401. v4.subtractToRef(v1, v1v4);
  53402. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53403. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53404. norm1.normalize();
  53405. norm2.normalize();
  53406. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53407. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53408. var quad = this._heightQuads[row * subdivisionsX + col];
  53409. quad.slope.copyFromFloats(cd, h);
  53410. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53411. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53412. }
  53413. }
  53414. return this;
  53415. };
  53416. GroundMesh.prototype.serialize = function (serializationObject) {
  53417. _super.prototype.serialize.call(this, serializationObject);
  53418. serializationObject.subdivisionsX = this._subdivisionsX;
  53419. serializationObject.subdivisionsY = this._subdivisionsY;
  53420. serializationObject.minX = this._minX;
  53421. serializationObject.maxX = this._maxX;
  53422. serializationObject.minZ = this._minZ;
  53423. serializationObject.maxZ = this._maxZ;
  53424. serializationObject.width = this._width;
  53425. serializationObject.height = this._height;
  53426. };
  53427. GroundMesh.Parse = function (parsedMesh, scene) {
  53428. var result = new GroundMesh(parsedMesh.name, scene);
  53429. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53430. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53431. result._minX = parsedMesh.minX;
  53432. result._maxX = parsedMesh.maxX;
  53433. result._minZ = parsedMesh.minZ;
  53434. result._maxZ = parsedMesh.maxZ;
  53435. result._width = parsedMesh.width;
  53436. result._height = parsedMesh.height;
  53437. return result;
  53438. };
  53439. return GroundMesh;
  53440. }(BABYLON.Mesh));
  53441. BABYLON.GroundMesh = GroundMesh;
  53442. })(BABYLON || (BABYLON = {}));
  53443. //# sourceMappingURL=babylon.groundMesh.js.map
  53444. var BABYLON;
  53445. (function (BABYLON) {
  53446. /**
  53447. * Creates an instance based on a source mesh.
  53448. */
  53449. var InstancedMesh = /** @class */ (function (_super) {
  53450. __extends(InstancedMesh, _super);
  53451. function InstancedMesh(name, source) {
  53452. var _this = _super.call(this, name, source.getScene()) || this;
  53453. source.instances.push(_this);
  53454. _this._sourceMesh = source;
  53455. _this.position.copyFrom(source.position);
  53456. _this.rotation.copyFrom(source.rotation);
  53457. _this.scaling.copyFrom(source.scaling);
  53458. if (source.rotationQuaternion) {
  53459. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53460. }
  53461. _this.infiniteDistance = source.infiniteDistance;
  53462. _this.setPivotMatrix(source.getPivotMatrix());
  53463. _this.refreshBoundingInfo();
  53464. _this._syncSubMeshes();
  53465. return _this;
  53466. }
  53467. /**
  53468. * Returns the string "InstancedMesh".
  53469. */
  53470. InstancedMesh.prototype.getClassName = function () {
  53471. return "InstancedMesh";
  53472. };
  53473. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53474. // Methods
  53475. get: function () {
  53476. return this._sourceMesh.receiveShadows;
  53477. },
  53478. enumerable: true,
  53479. configurable: true
  53480. });
  53481. Object.defineProperty(InstancedMesh.prototype, "material", {
  53482. get: function () {
  53483. return this._sourceMesh.material;
  53484. },
  53485. enumerable: true,
  53486. configurable: true
  53487. });
  53488. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53489. get: function () {
  53490. return this._sourceMesh.visibility;
  53491. },
  53492. enumerable: true,
  53493. configurable: true
  53494. });
  53495. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53496. get: function () {
  53497. return this._sourceMesh.skeleton;
  53498. },
  53499. enumerable: true,
  53500. configurable: true
  53501. });
  53502. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53503. get: function () {
  53504. return this._sourceMesh.renderingGroupId;
  53505. },
  53506. enumerable: true,
  53507. configurable: true
  53508. });
  53509. /**
  53510. * Returns the total number of vertices (integer).
  53511. */
  53512. InstancedMesh.prototype.getTotalVertices = function () {
  53513. return this._sourceMesh.getTotalVertices();
  53514. };
  53515. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53516. get: function () {
  53517. return this._sourceMesh;
  53518. },
  53519. enumerable: true,
  53520. configurable: true
  53521. });
  53522. /**
  53523. * Is this node ready to be used/rendered
  53524. * @return {boolean} is it ready
  53525. */
  53526. InstancedMesh.prototype.isReady = function () {
  53527. return this._sourceMesh.isReady(true);
  53528. };
  53529. /**
  53530. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53531. */
  53532. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53533. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53534. };
  53535. /**
  53536. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53537. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53538. * The `data` are either a numeric array either a Float32Array.
  53539. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53540. * 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).
  53541. * Note that a new underlying VertexBuffer object is created each call.
  53542. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53543. *
  53544. * Possible `kind` values :
  53545. * - BABYLON.VertexBuffer.PositionKind
  53546. * - BABYLON.VertexBuffer.UVKind
  53547. * - BABYLON.VertexBuffer.UV2Kind
  53548. * - BABYLON.VertexBuffer.UV3Kind
  53549. * - BABYLON.VertexBuffer.UV4Kind
  53550. * - BABYLON.VertexBuffer.UV5Kind
  53551. * - BABYLON.VertexBuffer.UV6Kind
  53552. * - BABYLON.VertexBuffer.ColorKind
  53553. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53554. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53555. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53556. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53557. *
  53558. * Returns the Mesh.
  53559. */
  53560. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53561. if (this.sourceMesh) {
  53562. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53563. }
  53564. return this.sourceMesh;
  53565. };
  53566. /**
  53567. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53568. * If the mesh has no geometry, it is simply returned as it is.
  53569. * The `data` are either a numeric array either a Float32Array.
  53570. * No new underlying VertexBuffer object is created.
  53571. * 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.
  53572. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53573. *
  53574. * Possible `kind` values :
  53575. * - BABYLON.VertexBuffer.PositionKind
  53576. * - BABYLON.VertexBuffer.UVKind
  53577. * - BABYLON.VertexBuffer.UV2Kind
  53578. * - BABYLON.VertexBuffer.UV3Kind
  53579. * - BABYLON.VertexBuffer.UV4Kind
  53580. * - BABYLON.VertexBuffer.UV5Kind
  53581. * - BABYLON.VertexBuffer.UV6Kind
  53582. * - BABYLON.VertexBuffer.ColorKind
  53583. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53584. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53585. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53586. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53587. *
  53588. * Returns the Mesh.
  53589. */
  53590. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53591. if (this.sourceMesh) {
  53592. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53593. }
  53594. return this.sourceMesh;
  53595. };
  53596. /**
  53597. * Sets the mesh indices.
  53598. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53599. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53600. * This method creates a new index buffer each call.
  53601. * Returns the Mesh.
  53602. */
  53603. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53604. if (totalVertices === void 0) { totalVertices = null; }
  53605. if (this.sourceMesh) {
  53606. this.sourceMesh.setIndices(indices, totalVertices);
  53607. }
  53608. return this.sourceMesh;
  53609. };
  53610. /**
  53611. * Boolean : True if the mesh owns the requested kind of data.
  53612. */
  53613. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53614. return this._sourceMesh.isVerticesDataPresent(kind);
  53615. };
  53616. /**
  53617. * Returns an array of indices (IndicesArray).
  53618. */
  53619. InstancedMesh.prototype.getIndices = function () {
  53620. return this._sourceMesh.getIndices();
  53621. };
  53622. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53623. get: function () {
  53624. return this._sourceMesh._positions;
  53625. },
  53626. enumerable: true,
  53627. configurable: true
  53628. });
  53629. /**
  53630. * Sets a new updated BoundingInfo to the mesh.
  53631. * Returns the mesh.
  53632. */
  53633. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53634. var meshBB = this._sourceMesh.getBoundingInfo();
  53635. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53636. this._updateBoundingInfo();
  53637. return this;
  53638. };
  53639. InstancedMesh.prototype._preActivate = function () {
  53640. if (this._currentLOD) {
  53641. this._currentLOD._preActivate();
  53642. }
  53643. return this;
  53644. };
  53645. InstancedMesh.prototype._activate = function (renderId) {
  53646. if (this._currentLOD) {
  53647. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53648. }
  53649. return this;
  53650. };
  53651. /**
  53652. * Returns the current associated LOD AbstractMesh.
  53653. */
  53654. InstancedMesh.prototype.getLOD = function (camera) {
  53655. if (!camera) {
  53656. return this;
  53657. }
  53658. var boundingInfo = this.getBoundingInfo();
  53659. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53660. if (this._currentLOD === this.sourceMesh) {
  53661. return this;
  53662. }
  53663. return this._currentLOD;
  53664. };
  53665. InstancedMesh.prototype._syncSubMeshes = function () {
  53666. this.releaseSubMeshes();
  53667. if (this._sourceMesh.subMeshes) {
  53668. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53669. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53670. }
  53671. }
  53672. return this;
  53673. };
  53674. InstancedMesh.prototype._generatePointsArray = function () {
  53675. return this._sourceMesh._generatePointsArray();
  53676. };
  53677. /**
  53678. * Creates a new InstancedMesh from the current mesh.
  53679. * - name (string) : the cloned mesh name
  53680. * - newParent (optional Node) : the optional Node to parent the clone to.
  53681. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53682. *
  53683. * Returns the clone.
  53684. */
  53685. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53686. var result = this._sourceMesh.createInstance(name);
  53687. // Deep copy
  53688. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53689. // Bounding info
  53690. this.refreshBoundingInfo();
  53691. // Parent
  53692. if (newParent) {
  53693. result.parent = newParent;
  53694. }
  53695. if (!doNotCloneChildren) {
  53696. // Children
  53697. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53698. var mesh = this.getScene().meshes[index];
  53699. if (mesh.parent === this) {
  53700. mesh.clone(mesh.name, result);
  53701. }
  53702. }
  53703. }
  53704. result.computeWorldMatrix(true);
  53705. return result;
  53706. };
  53707. /**
  53708. * Disposes the InstancedMesh.
  53709. * Returns nothing.
  53710. */
  53711. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53712. // Remove from mesh
  53713. var index = this._sourceMesh.instances.indexOf(this);
  53714. this._sourceMesh.instances.splice(index, 1);
  53715. _super.prototype.dispose.call(this, doNotRecurse);
  53716. };
  53717. return InstancedMesh;
  53718. }(BABYLON.AbstractMesh));
  53719. BABYLON.InstancedMesh = InstancedMesh;
  53720. })(BABYLON || (BABYLON = {}));
  53721. //# sourceMappingURL=babylon.instancedMesh.js.map
  53722. var BABYLON;
  53723. (function (BABYLON) {
  53724. var LinesMesh = /** @class */ (function (_super) {
  53725. __extends(LinesMesh, _super);
  53726. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53727. if (scene === void 0) { scene = null; }
  53728. if (parent === void 0) { parent = null; }
  53729. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53730. _this.useVertexColor = useVertexColor;
  53731. _this.useVertexAlpha = useVertexAlpha;
  53732. _this.color = new BABYLON.Color3(1, 1, 1);
  53733. _this.alpha = 1;
  53734. if (source) {
  53735. _this.color = source.color.clone();
  53736. _this.alpha = source.alpha;
  53737. _this.useVertexColor = source.useVertexColor;
  53738. _this.useVertexAlpha = source.useVertexAlpha;
  53739. }
  53740. _this._intersectionThreshold = 0.1;
  53741. var defines = [];
  53742. var options = {
  53743. attributes: [BABYLON.VertexBuffer.PositionKind],
  53744. uniforms: ["world", "viewProjection"],
  53745. needAlphaBlending: true,
  53746. defines: defines
  53747. };
  53748. if (useVertexAlpha === false) {
  53749. options.needAlphaBlending = false;
  53750. }
  53751. if (!useVertexColor) {
  53752. options.uniforms.push("color");
  53753. }
  53754. else {
  53755. options.defines.push("#define VERTEXCOLOR");
  53756. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53757. }
  53758. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53759. return _this;
  53760. }
  53761. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53762. /**
  53763. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53764. * This margin is expressed in world space coordinates, so its value may vary.
  53765. * Default value is 0.1
  53766. * @returns the intersection Threshold value.
  53767. */
  53768. get: function () {
  53769. return this._intersectionThreshold;
  53770. },
  53771. /**
  53772. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53773. * This margin is expressed in world space coordinates, so its value may vary.
  53774. * @param value the new threshold to apply
  53775. */
  53776. set: function (value) {
  53777. if (this._intersectionThreshold === value) {
  53778. return;
  53779. }
  53780. this._intersectionThreshold = value;
  53781. if (this.geometry) {
  53782. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53783. }
  53784. },
  53785. enumerable: true,
  53786. configurable: true
  53787. });
  53788. /**
  53789. * Returns the string "LineMesh"
  53790. */
  53791. LinesMesh.prototype.getClassName = function () {
  53792. return "LinesMesh";
  53793. };
  53794. Object.defineProperty(LinesMesh.prototype, "material", {
  53795. get: function () {
  53796. return this._colorShader;
  53797. },
  53798. set: function (value) {
  53799. // Do nothing
  53800. },
  53801. enumerable: true,
  53802. configurable: true
  53803. });
  53804. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53805. get: function () {
  53806. return false;
  53807. },
  53808. enumerable: true,
  53809. configurable: true
  53810. });
  53811. LinesMesh.prototype.createInstance = function (name) {
  53812. throw new Error("LinesMeshes do not support createInstance.");
  53813. };
  53814. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53815. if (!this._geometry) {
  53816. return this;
  53817. }
  53818. // VBOs
  53819. this._geometry._bind(this._colorShader.getEffect());
  53820. // Color
  53821. if (!this.useVertexColor) {
  53822. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53823. }
  53824. return this;
  53825. };
  53826. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53827. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53828. return this;
  53829. }
  53830. var engine = this.getScene().getEngine();
  53831. // Draw order
  53832. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53833. return this;
  53834. };
  53835. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53836. this._colorShader.dispose();
  53837. _super.prototype.dispose.call(this, doNotRecurse);
  53838. };
  53839. /**
  53840. * Returns a new LineMesh object cloned from the current one.
  53841. */
  53842. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53843. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53844. };
  53845. return LinesMesh;
  53846. }(BABYLON.Mesh));
  53847. BABYLON.LinesMesh = LinesMesh;
  53848. })(BABYLON || (BABYLON = {}));
  53849. //# sourceMappingURL=babylon.linesMesh.js.map
  53850. var BABYLON;
  53851. (function (BABYLON) {
  53852. var MeshBuilder = /** @class */ (function () {
  53853. function MeshBuilder() {
  53854. }
  53855. MeshBuilder.updateSideOrientation = function (orientation) {
  53856. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53857. return BABYLON.Mesh.DOUBLESIDE;
  53858. }
  53859. if (orientation === undefined || orientation === null) {
  53860. return BABYLON.Mesh.FRONTSIDE;
  53861. }
  53862. return orientation;
  53863. };
  53864. /**
  53865. * Creates a box mesh.
  53866. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53867. * The parameter `size` sets the size (float) of each box side (default 1).
  53868. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53869. * 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).
  53870. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53872. * 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).
  53873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53875. */
  53876. MeshBuilder.CreateBox = function (name, options, scene) {
  53877. if (scene === void 0) { scene = null; }
  53878. var box = new BABYLON.Mesh(name, scene);
  53879. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53880. box._originalBuilderSideOrientation = options.sideOrientation;
  53881. var vertexData = BABYLON.VertexData.CreateBox(options);
  53882. vertexData.applyToMesh(box, options.updatable);
  53883. return box;
  53884. };
  53885. /**
  53886. * Creates a sphere mesh.
  53887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53888. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53889. * 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`).
  53890. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53891. * 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
  53892. * 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).
  53893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53894. * 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).
  53895. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53897. */
  53898. MeshBuilder.CreateSphere = function (name, options, scene) {
  53899. var sphere = new BABYLON.Mesh(name, scene);
  53900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53901. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53902. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53903. vertexData.applyToMesh(sphere, options.updatable);
  53904. return sphere;
  53905. };
  53906. /**
  53907. * Creates a plane polygonal mesh. By default, this is a disc.
  53908. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53909. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53910. * 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.
  53911. * 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
  53912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53913. * 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).
  53914. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53916. */
  53917. MeshBuilder.CreateDisc = function (name, options, scene) {
  53918. if (scene === void 0) { scene = null; }
  53919. var disc = new BABYLON.Mesh(name, scene);
  53920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53921. disc._originalBuilderSideOrientation = options.sideOrientation;
  53922. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53923. vertexData.applyToMesh(disc, options.updatable);
  53924. return disc;
  53925. };
  53926. /**
  53927. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53929. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53930. * 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`).
  53931. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53932. * 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.
  53933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53934. * 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).
  53935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53937. */
  53938. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53939. var sphere = new BABYLON.Mesh(name, scene);
  53940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53941. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53942. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53943. vertexData.applyToMesh(sphere, options.updatable);
  53944. return sphere;
  53945. };
  53946. ;
  53947. /**
  53948. * Creates a ribbon mesh.
  53949. * 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.
  53950. *
  53951. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53952. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53953. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53954. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53955. * 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.
  53956. * 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.
  53957. * 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
  53958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53959. * 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).
  53960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53961. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53962. * 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.
  53963. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53964. * 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
  53965. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53966. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53968. */
  53969. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53970. if (scene === void 0) { scene = null; }
  53971. var pathArray = options.pathArray;
  53972. var closeArray = options.closeArray;
  53973. var closePath = options.closePath;
  53974. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53975. var instance = options.instance;
  53976. var updatable = options.updatable;
  53977. if (instance) {
  53978. // positionFunction : ribbon case
  53979. // only pathArray and sideOrientation parameters are taken into account for positions update
  53980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53982. var positionFunction = function (positions) {
  53983. var minlg = pathArray[0].length;
  53984. var i = 0;
  53985. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53986. for (var si = 1; si <= ns; si++) {
  53987. for (var p = 0; p < pathArray.length; p++) {
  53988. var path = pathArray[p];
  53989. var l = path.length;
  53990. minlg = (minlg < l) ? minlg : l;
  53991. var j = 0;
  53992. while (j < minlg) {
  53993. positions[i] = path[j].x;
  53994. positions[i + 1] = path[j].y;
  53995. positions[i + 2] = path[j].z;
  53996. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53997. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53998. }
  53999. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54000. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54001. }
  54002. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54003. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54004. }
  54005. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54006. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54007. }
  54008. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54009. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54010. }
  54011. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54012. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54013. }
  54014. j++;
  54015. i += 3;
  54016. }
  54017. if (instance._closePath) {
  54018. positions[i] = path[0].x;
  54019. positions[i + 1] = path[0].y;
  54020. positions[i + 2] = path[0].z;
  54021. i += 3;
  54022. }
  54023. }
  54024. }
  54025. };
  54026. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54027. positionFunction(positions);
  54028. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54029. instance._boundingInfo.update(instance._worldMatrix);
  54030. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54031. if (options.colors) {
  54032. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54033. for (var c = 0; c < options.colors.length; c++) {
  54034. colors[c * 4] = options.colors[c].r;
  54035. colors[c * 4 + 1] = options.colors[c].g;
  54036. colors[c * 4 + 2] = options.colors[c].b;
  54037. colors[c * 4 + 3] = options.colors[c].a;
  54038. }
  54039. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54040. }
  54041. if (options.uvs) {
  54042. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54043. for (var i = 0; i < options.uvs.length; i++) {
  54044. uvs[i * 2] = options.uvs[i].x;
  54045. uvs[i * 2 + 1] = options.uvs[i].y;
  54046. }
  54047. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54048. }
  54049. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54050. var indices = instance.getIndices();
  54051. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54052. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54053. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54054. if (instance._closePath) {
  54055. var indexFirst = 0;
  54056. var indexLast = 0;
  54057. for (var p = 0; p < pathArray.length; p++) {
  54058. indexFirst = instance._idx[p] * 3;
  54059. if (p + 1 < pathArray.length) {
  54060. indexLast = (instance._idx[p + 1] - 1) * 3;
  54061. }
  54062. else {
  54063. indexLast = normals.length - 3;
  54064. }
  54065. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54066. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54067. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54068. normals[indexLast] = normals[indexFirst];
  54069. normals[indexLast + 1] = normals[indexFirst + 1];
  54070. normals[indexLast + 2] = normals[indexFirst + 2];
  54071. }
  54072. }
  54073. if (!(instance.areNormalsFrozen)) {
  54074. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54075. }
  54076. }
  54077. return instance;
  54078. }
  54079. else {
  54080. var ribbon = new BABYLON.Mesh(name, scene);
  54081. ribbon._originalBuilderSideOrientation = sideOrientation;
  54082. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54083. if (closePath) {
  54084. ribbon._idx = vertexData._idx;
  54085. }
  54086. ribbon._closePath = closePath;
  54087. ribbon._closeArray = closeArray;
  54088. vertexData.applyToMesh(ribbon, updatable);
  54089. return ribbon;
  54090. }
  54091. };
  54092. /**
  54093. * Creates a cylinder or a cone mesh.
  54094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54095. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54096. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54097. * 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.
  54098. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54099. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54100. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54101. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54102. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54103. * 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).
  54104. * 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
  54105. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54106. * 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
  54107. * 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.
  54108. * If `enclose` is false, a ring surface is one element.
  54109. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54110. * 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
  54111. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54112. * 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).
  54113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54115. */
  54116. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54117. var cylinder = new BABYLON.Mesh(name, scene);
  54118. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54119. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54120. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54121. vertexData.applyToMesh(cylinder, options.updatable);
  54122. return cylinder;
  54123. };
  54124. /**
  54125. * Creates a torus mesh.
  54126. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54127. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54128. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54129. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54131. * 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).
  54132. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54134. */
  54135. MeshBuilder.CreateTorus = function (name, options, scene) {
  54136. var torus = new BABYLON.Mesh(name, scene);
  54137. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54138. torus._originalBuilderSideOrientation = options.sideOrientation;
  54139. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54140. vertexData.applyToMesh(torus, options.updatable);
  54141. return torus;
  54142. };
  54143. /**
  54144. * Creates a torus knot mesh.
  54145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54146. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54147. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54148. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54149. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54151. * 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).
  54152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54154. */
  54155. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54156. var torusKnot = new BABYLON.Mesh(name, scene);
  54157. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54158. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54159. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54160. vertexData.applyToMesh(torusKnot, options.updatable);
  54161. return torusKnot;
  54162. };
  54163. /**
  54164. * Creates a line system mesh.
  54165. * A line system is a pool of many lines gathered in a single mesh.
  54166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54167. * 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.
  54168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54169. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54170. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  54171. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54172. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54173. * 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
  54174. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54176. */
  54177. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54178. var instance = options.instance;
  54179. var lines = options.lines;
  54180. var colors = options.colors;
  54181. if (instance) {
  54182. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54183. var vertexColor;
  54184. var lineColors;
  54185. if (colors) {
  54186. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54187. }
  54188. var i = 0;
  54189. var c = 0;
  54190. for (var l = 0; l < lines.length; l++) {
  54191. var points = lines[l];
  54192. for (var p = 0; p < points.length; p++) {
  54193. positions[i] = points[p].x;
  54194. positions[i + 1] = points[p].y;
  54195. positions[i + 2] = points[p].z;
  54196. if (colors && vertexColor) {
  54197. lineColors = colors[l];
  54198. vertexColor[c] = lineColors[p].r;
  54199. vertexColor[c + 1] = lineColors[p].g;
  54200. vertexColor[c + 2] = lineColors[p].b;
  54201. vertexColor[c + 3] = lineColors[p].a;
  54202. c += 4;
  54203. }
  54204. i += 3;
  54205. }
  54206. }
  54207. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54208. if (colors && vertexColor) {
  54209. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54210. }
  54211. return instance;
  54212. }
  54213. // line system creation
  54214. var useVertexColor = (colors) ? true : false;
  54215. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54216. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54217. vertexData.applyToMesh(lineSystem, options.updatable);
  54218. return lineSystem;
  54219. };
  54220. /**
  54221. * Creates a line mesh.
  54222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54223. * 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.
  54224. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54225. * The parameter `points` is an array successive Vector3.
  54226. * 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
  54227. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54228. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54229. * When updating an instance, remember that only point positions can change, not the number of points.
  54230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54231. */
  54232. MeshBuilder.CreateLines = function (name, options, scene) {
  54233. if (scene === void 0) { scene = null; }
  54234. var colors = (options.colors) ? [options.colors] : null;
  54235. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54236. return lines;
  54237. };
  54238. /**
  54239. * Creates a dashed line mesh.
  54240. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54241. * 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.
  54242. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54243. * The parameter `points` is an array successive Vector3.
  54244. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54245. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54246. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54247. * 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
  54248. * When updating an instance, remember that only point positions can change, not the number of points.
  54249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54250. */
  54251. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54252. if (scene === void 0) { scene = null; }
  54253. var points = options.points;
  54254. var instance = options.instance;
  54255. var gapSize = options.gapSize || 1;
  54256. var dashSize = options.dashSize || 3;
  54257. if (instance) {
  54258. var positionFunction = function (positions) {
  54259. var curvect = BABYLON.Vector3.Zero();
  54260. var nbSeg = positions.length / 6;
  54261. var lg = 0;
  54262. var nb = 0;
  54263. var shft = 0;
  54264. var dashshft = 0;
  54265. var curshft = 0;
  54266. var p = 0;
  54267. var i = 0;
  54268. var j = 0;
  54269. for (i = 0; i < points.length - 1; i++) {
  54270. points[i + 1].subtractToRef(points[i], curvect);
  54271. lg += curvect.length();
  54272. }
  54273. shft = lg / nbSeg;
  54274. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54275. for (i = 0; i < points.length - 1; i++) {
  54276. points[i + 1].subtractToRef(points[i], curvect);
  54277. nb = Math.floor(curvect.length() / shft);
  54278. curvect.normalize();
  54279. j = 0;
  54280. while (j < nb && p < positions.length) {
  54281. curshft = shft * j;
  54282. positions[p] = points[i].x + curshft * curvect.x;
  54283. positions[p + 1] = points[i].y + curshft * curvect.y;
  54284. positions[p + 2] = points[i].z + curshft * curvect.z;
  54285. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54286. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54287. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54288. p += 6;
  54289. j++;
  54290. }
  54291. }
  54292. while (p < positions.length) {
  54293. positions[p] = points[i].x;
  54294. positions[p + 1] = points[i].y;
  54295. positions[p + 2] = points[i].z;
  54296. p += 3;
  54297. }
  54298. };
  54299. instance.updateMeshPositions(positionFunction, false);
  54300. return instance;
  54301. }
  54302. // dashed lines creation
  54303. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54304. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54305. vertexData.applyToMesh(dashedLines, options.updatable);
  54306. dashedLines.dashSize = dashSize;
  54307. dashedLines.gapSize = gapSize;
  54308. return dashedLines;
  54309. };
  54310. /**
  54311. * Creates an extruded shape mesh.
  54312. * 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.
  54313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54314. *
  54315. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54316. * 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
  54317. * extruded along the Z axis.
  54318. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54319. * 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.
  54320. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54321. * 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
  54322. * 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
  54323. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54325. * 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).
  54326. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54327. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54329. */
  54330. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54331. if (scene === void 0) { scene = null; }
  54332. var path = options.path;
  54333. var shape = options.shape;
  54334. var scale = options.scale || 1;
  54335. var rotation = options.rotation || 0;
  54336. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54337. var updatable = options.updatable;
  54338. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54339. var instance = options.instance || null;
  54340. var invertUV = options.invertUV || false;
  54341. 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);
  54342. };
  54343. /**
  54344. * Creates an custom extruded shape mesh.
  54345. * 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.
  54346. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54347. *
  54348. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54349. * 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
  54350. * extruded along the Z axis.
  54351. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54352. * 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
  54353. * and the distance of this point from the begining of the path :
  54354. * ```javascript
  54355. * var rotationFunction = function(i, distance) {
  54356. * // do things
  54357. * return rotationValue; }
  54358. * ```
  54359. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54360. * 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
  54361. * and the distance of this point from the begining of the path :
  54362. * ```javascript
  54363. * var scaleFunction = function(i, distance) {
  54364. * // do things
  54365. * return scaleValue;}
  54366. * ```
  54367. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54368. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54369. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54370. * 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
  54371. * 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
  54372. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54374. * 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).
  54375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54376. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54378. */
  54379. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54380. var path = options.path;
  54381. var shape = options.shape;
  54382. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54383. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54384. var ribbonCloseArray = options.ribbonCloseArray || false;
  54385. var ribbonClosePath = options.ribbonClosePath || false;
  54386. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54387. var updatable = options.updatable;
  54388. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54389. var instance = options.instance;
  54390. var invertUV = options.invertUV || false;
  54391. 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);
  54392. };
  54393. /**
  54394. * Creates lathe mesh.
  54395. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54396. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54397. *
  54398. * 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
  54399. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54400. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54401. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54402. * 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.
  54403. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54404. * 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
  54405. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54406. * 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).
  54407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54408. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54410. */
  54411. MeshBuilder.CreateLathe = function (name, options, scene) {
  54412. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54413. var closed = (options.closed === undefined) ? true : options.closed;
  54414. var shape = options.shape;
  54415. var radius = options.radius || 1;
  54416. var tessellation = options.tessellation || 64;
  54417. var updatable = options.updatable;
  54418. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54419. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54420. var pi2 = Math.PI * 2;
  54421. var paths = new Array();
  54422. var invertUV = options.invertUV || false;
  54423. var i = 0;
  54424. var p = 0;
  54425. var step = pi2 / tessellation * arc;
  54426. var rotated;
  54427. var path = new Array();
  54428. ;
  54429. for (i = 0; i <= tessellation; i++) {
  54430. var path = [];
  54431. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54432. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54433. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54434. }
  54435. for (p = 0; p < shape.length; p++) {
  54436. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54437. path.push(rotated);
  54438. }
  54439. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54440. 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));
  54441. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54442. }
  54443. paths.push(path);
  54444. }
  54445. // lathe ribbon
  54446. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54447. return lathe;
  54448. };
  54449. /**
  54450. * Creates a plane mesh.
  54451. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54452. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54453. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54454. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54455. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54456. * 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).
  54457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54459. */
  54460. MeshBuilder.CreatePlane = function (name, options, scene) {
  54461. var plane = new BABYLON.Mesh(name, scene);
  54462. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54463. plane._originalBuilderSideOrientation = options.sideOrientation;
  54464. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54465. vertexData.applyToMesh(plane, options.updatable);
  54466. if (options.sourcePlane) {
  54467. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54468. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54469. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54470. plane.rotate(vectorProduct, product);
  54471. }
  54472. return plane;
  54473. };
  54474. /**
  54475. * Creates a ground mesh.
  54476. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54477. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54478. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54480. */
  54481. MeshBuilder.CreateGround = function (name, options, scene) {
  54482. var ground = new BABYLON.GroundMesh(name, scene);
  54483. ground._setReady(false);
  54484. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54485. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54486. ground._width = options.width || 1;
  54487. ground._height = options.height || 1;
  54488. ground._maxX = ground._width / 2;
  54489. ground._maxZ = ground._height / 2;
  54490. ground._minX = -ground._maxX;
  54491. ground._minZ = -ground._maxZ;
  54492. var vertexData = BABYLON.VertexData.CreateGround(options);
  54493. vertexData.applyToMesh(ground, options.updatable);
  54494. ground._setReady(true);
  54495. return ground;
  54496. };
  54497. /**
  54498. * Creates a tiled ground mesh.
  54499. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54500. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54501. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54502. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54503. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54504. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54505. * numbers of subdivisions on the ground width and height of each tile.
  54506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54507. */
  54508. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54509. var tiledGround = new BABYLON.Mesh(name, scene);
  54510. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54511. vertexData.applyToMesh(tiledGround, options.updatable);
  54512. return tiledGround;
  54513. };
  54514. /**
  54515. * Creates a ground mesh from a height map.
  54516. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54517. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54518. * The parameter `url` sets the URL of the height map image resource.
  54519. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54520. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54521. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54522. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54523. * 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.
  54524. * 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).
  54525. * This function is passed the newly built mesh :
  54526. * ```javascript
  54527. * function(mesh) { // do things
  54528. * return; }
  54529. * ```
  54530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54531. */
  54532. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54533. var width = options.width || 10.0;
  54534. var height = options.height || 10.0;
  54535. var subdivisions = options.subdivisions || 1 | 0;
  54536. var minHeight = options.minHeight || 0.0;
  54537. var maxHeight = options.maxHeight || 1.0;
  54538. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54539. var updatable = options.updatable;
  54540. var onReady = options.onReady;
  54541. var ground = new BABYLON.GroundMesh(name, scene);
  54542. ground._subdivisionsX = subdivisions;
  54543. ground._subdivisionsY = subdivisions;
  54544. ground._width = width;
  54545. ground._height = height;
  54546. ground._maxX = ground._width / 2.0;
  54547. ground._maxZ = ground._height / 2.0;
  54548. ground._minX = -ground._maxX;
  54549. ground._minZ = -ground._maxZ;
  54550. ground._setReady(false);
  54551. var onload = function (img) {
  54552. // Getting height map data
  54553. var canvas = document.createElement("canvas");
  54554. var context = canvas.getContext("2d");
  54555. if (!context) {
  54556. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54557. }
  54558. if (scene.isDisposed) {
  54559. return;
  54560. }
  54561. var bufferWidth = img.width;
  54562. var bufferHeight = img.height;
  54563. canvas.width = bufferWidth;
  54564. canvas.height = bufferHeight;
  54565. context.drawImage(img, 0, 0);
  54566. // Create VertexData from map data
  54567. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54568. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54569. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54570. width: width, height: height,
  54571. subdivisions: subdivisions,
  54572. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54573. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54574. });
  54575. vertexData.applyToMesh(ground, updatable);
  54576. ground._setReady(true);
  54577. //execute ready callback, if set
  54578. if (onReady) {
  54579. onReady(ground);
  54580. }
  54581. };
  54582. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54583. return ground;
  54584. };
  54585. /**
  54586. * Creates a polygon mesh.
  54587. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54588. * 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.
  54589. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54591. * 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).
  54592. * Remember you can only change the shape positions, not their number when updating a polygon.
  54593. */
  54594. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54595. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54596. var shape = options.shape;
  54597. var holes = options.holes || [];
  54598. var depth = options.depth || 0;
  54599. var contours = [];
  54600. var hole = [];
  54601. for (var i = 0; i < shape.length; i++) {
  54602. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54603. }
  54604. var epsilon = 0.00000001;
  54605. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54606. contours.pop();
  54607. }
  54608. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54609. for (var hNb = 0; hNb < holes.length; hNb++) {
  54610. hole = [];
  54611. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54612. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54613. }
  54614. polygonTriangulation.addHole(hole);
  54615. }
  54616. var polygon = polygonTriangulation.build(options.updatable, depth);
  54617. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54618. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54619. vertexData.applyToMesh(polygon, options.updatable);
  54620. return polygon;
  54621. };
  54622. ;
  54623. /**
  54624. * Creates an extruded polygon mesh, with depth in the Y direction.
  54625. * 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).
  54626. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54627. */
  54628. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54629. return MeshBuilder.CreatePolygon(name, options, scene);
  54630. };
  54631. ;
  54632. /**
  54633. * Creates a tube mesh.
  54634. * 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.
  54635. *
  54636. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54637. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54638. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54639. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54640. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54641. * 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.
  54642. * It must return a radius value (positive float) :
  54643. * ```javascript
  54644. * var radiusFunction = function(i, distance) {
  54645. * // do things
  54646. * return radius; }
  54647. * ```
  54648. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54649. * 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
  54650. * 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
  54651. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54652. * 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).
  54653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54654. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54656. */
  54657. MeshBuilder.CreateTube = function (name, options, scene) {
  54658. var path = options.path;
  54659. var instance = options.instance;
  54660. var radius = 1.0;
  54661. if (instance) {
  54662. radius = instance.radius;
  54663. }
  54664. if (options.radius !== undefined) {
  54665. radius = options.radius;
  54666. }
  54667. ;
  54668. var tessellation = options.tessellation || 64 | 0;
  54669. var radiusFunction = options.radiusFunction || null;
  54670. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54671. var invertUV = options.invertUV || false;
  54672. var updatable = options.updatable;
  54673. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54674. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54675. // tube geometry
  54676. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54677. var tangents = path3D.getTangents();
  54678. var normals = path3D.getNormals();
  54679. var distances = path3D.getDistances();
  54680. var pi2 = Math.PI * 2;
  54681. var step = pi2 / tessellation * arc;
  54682. var returnRadius = function () { return radius; };
  54683. var radiusFunctionFinal = radiusFunction || returnRadius;
  54684. var circlePath;
  54685. var rad;
  54686. var normal;
  54687. var rotated;
  54688. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54689. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54690. for (var i = 0; i < path.length; i++) {
  54691. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54692. circlePath = Array(); // current circle array
  54693. normal = normals[i]; // current normal
  54694. for (var t = 0; t < tessellation; t++) {
  54695. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54696. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54697. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54698. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54699. circlePath[t] = rotated;
  54700. }
  54701. circlePaths[index] = circlePath;
  54702. index++;
  54703. }
  54704. // cap
  54705. var capPath = function (nbPoints, pathIndex) {
  54706. var pointCap = Array();
  54707. for (var i = 0; i < nbPoints; i++) {
  54708. pointCap.push(path[pathIndex]);
  54709. }
  54710. return pointCap;
  54711. };
  54712. switch (cap) {
  54713. case BABYLON.Mesh.NO_CAP:
  54714. break;
  54715. case BABYLON.Mesh.CAP_START:
  54716. circlePaths[0] = capPath(tessellation, 0);
  54717. circlePaths[1] = circlePaths[2].slice(0);
  54718. break;
  54719. case BABYLON.Mesh.CAP_END:
  54720. circlePaths[index] = circlePaths[index - 1].slice(0);
  54721. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54722. break;
  54723. case BABYLON.Mesh.CAP_ALL:
  54724. circlePaths[0] = capPath(tessellation, 0);
  54725. circlePaths[1] = circlePaths[2].slice(0);
  54726. circlePaths[index] = circlePaths[index - 1].slice(0);
  54727. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54728. break;
  54729. default:
  54730. break;
  54731. }
  54732. return circlePaths;
  54733. };
  54734. var path3D;
  54735. var pathArray;
  54736. if (instance) {
  54737. var arc = options.arc || instance.arc;
  54738. path3D = (instance.path3D).update(path);
  54739. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54740. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54741. instance.path3D = path3D;
  54742. instance.pathArray = pathArray;
  54743. instance.arc = arc;
  54744. instance.radius = radius;
  54745. return instance;
  54746. }
  54747. // tube creation
  54748. path3D = new BABYLON.Path3D(path);
  54749. var newPathArray = new Array();
  54750. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54751. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54752. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54753. tube.pathArray = pathArray;
  54754. tube.path3D = path3D;
  54755. tube.tessellation = tessellation;
  54756. tube.cap = cap;
  54757. tube.arc = options.arc;
  54758. tube.radius = radius;
  54759. return tube;
  54760. };
  54761. /**
  54762. * Creates a polyhedron mesh.
  54763. *
  54764. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54765. * 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
  54766. * to choose the wanted type.
  54767. * The parameter `size` (positive float, default 1) sets the polygon size.
  54768. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54769. * 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`.
  54770. * 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
  54771. * 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)`).
  54772. * 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
  54773. * 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.
  54774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54775. * 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).
  54776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54778. */
  54779. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54780. var polyhedron = new BABYLON.Mesh(name, scene);
  54781. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54782. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54783. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54784. vertexData.applyToMesh(polyhedron, options.updatable);
  54785. return polyhedron;
  54786. };
  54787. /**
  54788. * Creates a decal mesh.
  54789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54790. * 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.
  54791. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54792. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54793. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54794. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54795. */
  54796. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54797. var indices = sourceMesh.getIndices();
  54798. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54799. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54800. var position = options.position || BABYLON.Vector3.Zero();
  54801. var normal = options.normal || BABYLON.Vector3.Up();
  54802. var size = options.size || BABYLON.Vector3.One();
  54803. var angle = options.angle || 0;
  54804. // Getting correct rotation
  54805. if (!normal) {
  54806. var target = new BABYLON.Vector3(0, 0, 1);
  54807. var camera = sourceMesh.getScene().activeCamera;
  54808. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54809. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54810. }
  54811. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54812. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54813. var pitch = Math.atan2(normal.y, len);
  54814. // Matrix
  54815. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54816. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54817. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54818. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54819. var vertexData = new BABYLON.VertexData();
  54820. vertexData.indices = [];
  54821. vertexData.positions = [];
  54822. vertexData.normals = [];
  54823. vertexData.uvs = [];
  54824. var currentVertexDataIndex = 0;
  54825. var extractDecalVector3 = function (indexId) {
  54826. var result = new BABYLON.PositionNormalVertex();
  54827. if (!indices || !positions || !normals) {
  54828. return result;
  54829. }
  54830. var vertexId = indices[indexId];
  54831. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54832. // Send vector to decal local world
  54833. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54834. // Get normal
  54835. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54836. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54837. return result;
  54838. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54839. var clip = function (vertices, axis) {
  54840. if (vertices.length === 0) {
  54841. return vertices;
  54842. }
  54843. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54844. var clipVertices = function (v0, v1) {
  54845. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54846. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54847. };
  54848. var result = new Array();
  54849. for (var index = 0; index < vertices.length; index += 3) {
  54850. var v1Out;
  54851. var v2Out;
  54852. var v3Out;
  54853. var total = 0;
  54854. var nV1 = null;
  54855. var nV2 = null;
  54856. var nV3 = null;
  54857. var nV4 = null;
  54858. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54859. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54860. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54861. v1Out = d1 > 0;
  54862. v2Out = d2 > 0;
  54863. v3Out = d3 > 0;
  54864. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54865. switch (total) {
  54866. case 0:
  54867. result.push(vertices[index]);
  54868. result.push(vertices[index + 1]);
  54869. result.push(vertices[index + 2]);
  54870. break;
  54871. case 1:
  54872. if (v1Out) {
  54873. nV1 = vertices[index + 1];
  54874. nV2 = vertices[index + 2];
  54875. nV3 = clipVertices(vertices[index], nV1);
  54876. nV4 = clipVertices(vertices[index], nV2);
  54877. }
  54878. if (v2Out) {
  54879. nV1 = vertices[index];
  54880. nV2 = vertices[index + 2];
  54881. nV3 = clipVertices(vertices[index + 1], nV1);
  54882. nV4 = clipVertices(vertices[index + 1], nV2);
  54883. result.push(nV3);
  54884. result.push(nV2.clone());
  54885. result.push(nV1.clone());
  54886. result.push(nV2.clone());
  54887. result.push(nV3.clone());
  54888. result.push(nV4);
  54889. break;
  54890. }
  54891. if (v3Out) {
  54892. nV1 = vertices[index];
  54893. nV2 = vertices[index + 1];
  54894. nV3 = clipVertices(vertices[index + 2], nV1);
  54895. nV4 = clipVertices(vertices[index + 2], nV2);
  54896. }
  54897. if (nV1 && nV2 && nV3 && nV4) {
  54898. result.push(nV1.clone());
  54899. result.push(nV2.clone());
  54900. result.push(nV3);
  54901. result.push(nV4);
  54902. result.push(nV3.clone());
  54903. result.push(nV2.clone());
  54904. }
  54905. break;
  54906. case 2:
  54907. if (!v1Out) {
  54908. nV1 = vertices[index].clone();
  54909. nV2 = clipVertices(nV1, vertices[index + 1]);
  54910. nV3 = clipVertices(nV1, vertices[index + 2]);
  54911. result.push(nV1);
  54912. result.push(nV2);
  54913. result.push(nV3);
  54914. }
  54915. if (!v2Out) {
  54916. nV1 = vertices[index + 1].clone();
  54917. nV2 = clipVertices(nV1, vertices[index + 2]);
  54918. nV3 = clipVertices(nV1, vertices[index]);
  54919. result.push(nV1);
  54920. result.push(nV2);
  54921. result.push(nV3);
  54922. }
  54923. if (!v3Out) {
  54924. nV1 = vertices[index + 2].clone();
  54925. nV2 = clipVertices(nV1, vertices[index]);
  54926. nV3 = clipVertices(nV1, vertices[index + 1]);
  54927. result.push(nV1);
  54928. result.push(nV2);
  54929. result.push(nV3);
  54930. }
  54931. break;
  54932. case 3:
  54933. break;
  54934. }
  54935. }
  54936. return result;
  54937. };
  54938. for (var index = 0; index < indices.length; index += 3) {
  54939. var faceVertices = new Array();
  54940. faceVertices.push(extractDecalVector3(index));
  54941. faceVertices.push(extractDecalVector3(index + 1));
  54942. faceVertices.push(extractDecalVector3(index + 2));
  54943. // Clip
  54944. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54945. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54946. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54947. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54948. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54949. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54950. if (faceVertices.length === 0) {
  54951. continue;
  54952. }
  54953. // Add UVs and get back to world
  54954. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54955. var vertex = faceVertices[vIndex];
  54956. //TODO check for Int32Array | Uint32Array | Uint16Array
  54957. vertexData.indices.push(currentVertexDataIndex);
  54958. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54959. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54960. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54961. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54962. currentVertexDataIndex++;
  54963. }
  54964. }
  54965. // Return mesh
  54966. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54967. vertexData.applyToMesh(decal);
  54968. decal.position = position.clone();
  54969. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54970. return decal;
  54971. };
  54972. // Privates
  54973. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54974. // extrusion geometry
  54975. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54976. var tangents = path3D.getTangents();
  54977. var normals = path3D.getNormals();
  54978. var binormals = path3D.getBinormals();
  54979. var distances = path3D.getDistances();
  54980. var angle = 0;
  54981. var returnScale = function () { return scale !== null ? scale : 1; };
  54982. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54983. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54984. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54985. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54986. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54987. for (var i = 0; i < curve.length; i++) {
  54988. var shapePath = new Array();
  54989. var angleStep = rotate(i, distances[i]);
  54990. var scaleRatio = scl(i, distances[i]);
  54991. for (var p = 0; p < shape.length; p++) {
  54992. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54993. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54994. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54995. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54996. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54997. shapePath[p] = rotated;
  54998. }
  54999. shapePaths[index] = shapePath;
  55000. angle += angleStep;
  55001. index++;
  55002. }
  55003. // cap
  55004. var capPath = function (shapePath) {
  55005. var pointCap = Array();
  55006. var barycenter = BABYLON.Vector3.Zero();
  55007. var i;
  55008. for (i = 0; i < shapePath.length; i++) {
  55009. barycenter.addInPlace(shapePath[i]);
  55010. }
  55011. barycenter.scaleInPlace(1.0 / shapePath.length);
  55012. for (i = 0; i < shapePath.length; i++) {
  55013. pointCap.push(barycenter);
  55014. }
  55015. return pointCap;
  55016. };
  55017. switch (cap) {
  55018. case BABYLON.Mesh.NO_CAP:
  55019. break;
  55020. case BABYLON.Mesh.CAP_START:
  55021. shapePaths[0] = capPath(shapePaths[2]);
  55022. shapePaths[1] = shapePaths[2];
  55023. break;
  55024. case BABYLON.Mesh.CAP_END:
  55025. shapePaths[index] = shapePaths[index - 1];
  55026. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55027. break;
  55028. case BABYLON.Mesh.CAP_ALL:
  55029. shapePaths[0] = capPath(shapePaths[2]);
  55030. shapePaths[1] = shapePaths[2];
  55031. shapePaths[index] = shapePaths[index - 1];
  55032. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55033. break;
  55034. default:
  55035. break;
  55036. }
  55037. return shapePaths;
  55038. };
  55039. var path3D;
  55040. var pathArray;
  55041. if (instance) {
  55042. path3D = (instance.path3D).update(curve);
  55043. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55044. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55045. return instance;
  55046. }
  55047. // extruded shape creation
  55048. path3D = new BABYLON.Path3D(curve);
  55049. var newShapePaths = new Array();
  55050. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55051. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55052. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55053. extrudedGeneric.pathArray = pathArray;
  55054. extrudedGeneric.path3D = path3D;
  55055. extrudedGeneric.cap = cap;
  55056. return extrudedGeneric;
  55057. };
  55058. return MeshBuilder;
  55059. }());
  55060. BABYLON.MeshBuilder = MeshBuilder;
  55061. })(BABYLON || (BABYLON = {}));
  55062. //# sourceMappingURL=babylon.meshBuilder.js.map
  55063. var BABYLON;
  55064. (function (BABYLON) {
  55065. var AudioEngine = /** @class */ (function () {
  55066. function AudioEngine() {
  55067. this._audioContext = null;
  55068. this._audioContextInitialized = false;
  55069. this.canUseWebAudio = false;
  55070. this.WarnedWebAudioUnsupported = false;
  55071. this.unlocked = false;
  55072. this.isMP3supported = false;
  55073. this.isOGGsupported = false;
  55074. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55075. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55076. this.canUseWebAudio = true;
  55077. }
  55078. var audioElem = document.createElement('audio');
  55079. try {
  55080. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55081. this.isMP3supported = true;
  55082. }
  55083. }
  55084. catch (e) {
  55085. // protect error during capability check.
  55086. }
  55087. try {
  55088. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55089. this.isOGGsupported = true;
  55090. }
  55091. }
  55092. catch (e) {
  55093. // protect error during capability check.
  55094. }
  55095. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55096. this._unlockiOSaudio();
  55097. }
  55098. else {
  55099. this.unlocked = true;
  55100. }
  55101. }
  55102. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55103. get: function () {
  55104. if (!this._audioContextInitialized) {
  55105. this._initializeAudioContext();
  55106. }
  55107. return this._audioContext;
  55108. },
  55109. enumerable: true,
  55110. configurable: true
  55111. });
  55112. AudioEngine.prototype._unlockiOSaudio = function () {
  55113. var _this = this;
  55114. var unlockaudio = function () {
  55115. if (!_this.audioContext) {
  55116. return;
  55117. }
  55118. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55119. var source = _this.audioContext.createBufferSource();
  55120. source.buffer = buffer;
  55121. source.connect(_this.audioContext.destination);
  55122. source.start(0);
  55123. setTimeout(function () {
  55124. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55125. _this.unlocked = true;
  55126. window.removeEventListener('touchend', unlockaudio, false);
  55127. if (_this.onAudioUnlocked) {
  55128. _this.onAudioUnlocked();
  55129. }
  55130. }
  55131. }, 0);
  55132. };
  55133. window.addEventListener('touchend', unlockaudio, false);
  55134. };
  55135. AudioEngine.prototype._initializeAudioContext = function () {
  55136. try {
  55137. if (this.canUseWebAudio) {
  55138. this._audioContext = new AudioContext();
  55139. // create a global volume gain node
  55140. this.masterGain = this._audioContext.createGain();
  55141. this.masterGain.gain.value = 1;
  55142. this.masterGain.connect(this._audioContext.destination);
  55143. this._audioContextInitialized = true;
  55144. }
  55145. }
  55146. catch (e) {
  55147. this.canUseWebAudio = false;
  55148. BABYLON.Tools.Error("Web Audio: " + e.message);
  55149. }
  55150. };
  55151. AudioEngine.prototype.dispose = function () {
  55152. if (this.canUseWebAudio && this._audioContextInitialized) {
  55153. if (this._connectedAnalyser && this._audioContext) {
  55154. this._connectedAnalyser.stopDebugCanvas();
  55155. this._connectedAnalyser.dispose();
  55156. this.masterGain.disconnect();
  55157. this.masterGain.connect(this._audioContext.destination);
  55158. this._connectedAnalyser = null;
  55159. }
  55160. this.masterGain.gain.value = 1;
  55161. }
  55162. this.WarnedWebAudioUnsupported = false;
  55163. };
  55164. AudioEngine.prototype.getGlobalVolume = function () {
  55165. if (this.canUseWebAudio && this._audioContextInitialized) {
  55166. return this.masterGain.gain.value;
  55167. }
  55168. else {
  55169. return -1;
  55170. }
  55171. };
  55172. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55173. if (this.canUseWebAudio && this._audioContextInitialized) {
  55174. this.masterGain.gain.value = newVolume;
  55175. }
  55176. };
  55177. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55178. if (this._connectedAnalyser) {
  55179. this._connectedAnalyser.stopDebugCanvas();
  55180. }
  55181. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55182. this._connectedAnalyser = analyser;
  55183. this.masterGain.disconnect();
  55184. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55185. }
  55186. };
  55187. return AudioEngine;
  55188. }());
  55189. BABYLON.AudioEngine = AudioEngine;
  55190. })(BABYLON || (BABYLON = {}));
  55191. //# sourceMappingURL=babylon.audioEngine.js.map
  55192. var BABYLON;
  55193. (function (BABYLON) {
  55194. var Sound = /** @class */ (function () {
  55195. /**
  55196. * Create a sound and attach it to a scene
  55197. * @param name Name of your sound
  55198. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55199. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55200. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55201. */
  55202. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55203. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55204. var _this = this;
  55205. this.autoplay = false;
  55206. this.loop = false;
  55207. this.useCustomAttenuation = false;
  55208. this.spatialSound = false;
  55209. this.refDistance = 1;
  55210. this.rolloffFactor = 1;
  55211. this.maxDistance = 100;
  55212. this.distanceModel = "linear";
  55213. this._panningModel = "equalpower";
  55214. this._playbackRate = 1;
  55215. this._streaming = false;
  55216. this._startTime = 0;
  55217. this._startOffset = 0;
  55218. this._position = BABYLON.Vector3.Zero();
  55219. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55220. this._volume = 1;
  55221. this._isReadyToPlay = false;
  55222. this.isPlaying = false;
  55223. this.isPaused = false;
  55224. this._isDirectional = false;
  55225. // Used if you'd like to create a directional sound.
  55226. // If not set, the sound will be omnidirectional
  55227. this._coneInnerAngle = 360;
  55228. this._coneOuterAngle = 360;
  55229. this._coneOuterGain = 0;
  55230. this._isOutputConnected = false;
  55231. this._urlType = "Unknown";
  55232. this.name = name;
  55233. this._scene = scene;
  55234. this._readyToPlayCallback = readyToPlayCallback;
  55235. // Default custom attenuation function is a linear attenuation
  55236. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55237. if (currentDistance < maxDistance) {
  55238. return currentVolume * (1 - currentDistance / maxDistance);
  55239. }
  55240. else {
  55241. return 0;
  55242. }
  55243. };
  55244. if (options) {
  55245. this.autoplay = options.autoplay || false;
  55246. this.loop = options.loop || false;
  55247. // if volume === 0, we need another way to check this option
  55248. if (options.volume !== undefined) {
  55249. this._volume = options.volume;
  55250. }
  55251. this.spatialSound = options.spatialSound || false;
  55252. this.maxDistance = options.maxDistance || 100;
  55253. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55254. this.rolloffFactor = options.rolloffFactor || 1;
  55255. this.refDistance = options.refDistance || 1;
  55256. this.distanceModel = options.distanceModel || "linear";
  55257. this._playbackRate = options.playbackRate || 1;
  55258. this._streaming = options.streaming || false;
  55259. }
  55260. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55261. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55262. this._soundGain.gain.value = this._volume;
  55263. this._inputAudioNode = this._soundGain;
  55264. this._ouputAudioNode = this._soundGain;
  55265. if (this.spatialSound) {
  55266. this._createSpatialParameters();
  55267. }
  55268. this._scene.mainSoundTrack.AddSound(this);
  55269. var validParameter = true;
  55270. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55271. if (urlOrArrayBuffer) {
  55272. if (typeof (urlOrArrayBuffer) === "string")
  55273. this._urlType = "String";
  55274. if (Array.isArray(urlOrArrayBuffer))
  55275. this._urlType = "Array";
  55276. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55277. this._urlType = "ArrayBuffer";
  55278. var urls = [];
  55279. var codecSupportedFound = false;
  55280. switch (this._urlType) {
  55281. case "ArrayBuffer":
  55282. if (urlOrArrayBuffer.byteLength > 0) {
  55283. codecSupportedFound = true;
  55284. this._soundLoaded(urlOrArrayBuffer);
  55285. }
  55286. break;
  55287. case "String":
  55288. urls.push(urlOrArrayBuffer);
  55289. case "Array":
  55290. if (urls.length === 0)
  55291. urls = urlOrArrayBuffer;
  55292. // If we found a supported format, we load it immediately and stop the loop
  55293. for (var i = 0; i < urls.length; i++) {
  55294. var url = urls[i];
  55295. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55296. codecSupportedFound = true;
  55297. }
  55298. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55299. codecSupportedFound = true;
  55300. }
  55301. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55302. codecSupportedFound = true;
  55303. }
  55304. if (url.indexOf("blob:") !== -1) {
  55305. codecSupportedFound = true;
  55306. }
  55307. if (codecSupportedFound) {
  55308. // Loading sound using XHR2
  55309. if (!this._streaming) {
  55310. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55311. }
  55312. else {
  55313. this._htmlAudioElement = new Audio(url);
  55314. this._htmlAudioElement.controls = false;
  55315. this._htmlAudioElement.loop = this.loop;
  55316. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55317. this._htmlAudioElement.preload = "auto";
  55318. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55319. _this._isReadyToPlay = true;
  55320. if (_this.autoplay) {
  55321. _this.play();
  55322. }
  55323. if (_this._readyToPlayCallback) {
  55324. _this._readyToPlayCallback();
  55325. }
  55326. });
  55327. document.body.appendChild(this._htmlAudioElement);
  55328. }
  55329. break;
  55330. }
  55331. }
  55332. break;
  55333. default:
  55334. validParameter = false;
  55335. break;
  55336. }
  55337. if (!validParameter) {
  55338. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55339. }
  55340. else {
  55341. if (!codecSupportedFound) {
  55342. this._isReadyToPlay = true;
  55343. // Simulating a ready to play event to avoid breaking code path
  55344. if (this._readyToPlayCallback) {
  55345. window.setTimeout(function () {
  55346. if (_this._readyToPlayCallback) {
  55347. _this._readyToPlayCallback();
  55348. }
  55349. }, 1000);
  55350. }
  55351. }
  55352. }
  55353. }
  55354. }
  55355. else {
  55356. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55357. this._scene.mainSoundTrack.AddSound(this);
  55358. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55359. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55360. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55361. }
  55362. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55363. if (this._readyToPlayCallback) {
  55364. window.setTimeout(function () {
  55365. if (_this._readyToPlayCallback) {
  55366. _this._readyToPlayCallback();
  55367. }
  55368. }, 1000);
  55369. }
  55370. }
  55371. }
  55372. Sound.prototype.dispose = function () {
  55373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55374. if (this.isPlaying) {
  55375. this.stop();
  55376. }
  55377. this._isReadyToPlay = false;
  55378. if (this.soundTrackId === -1) {
  55379. this._scene.mainSoundTrack.RemoveSound(this);
  55380. }
  55381. else {
  55382. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55383. }
  55384. if (this._soundGain) {
  55385. this._soundGain.disconnect();
  55386. this._soundGain = null;
  55387. }
  55388. if (this._soundPanner) {
  55389. this._soundPanner.disconnect();
  55390. this._soundPanner = null;
  55391. }
  55392. if (this._soundSource) {
  55393. this._soundSource.disconnect();
  55394. this._soundSource = null;
  55395. }
  55396. this._audioBuffer = null;
  55397. if (this._htmlAudioElement) {
  55398. this._htmlAudioElement.pause();
  55399. this._htmlAudioElement.src = "";
  55400. document.body.removeChild(this._htmlAudioElement);
  55401. }
  55402. if (this._connectedMesh && this._registerFunc) {
  55403. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55404. this._connectedMesh = null;
  55405. }
  55406. }
  55407. };
  55408. Sound.prototype.isReady = function () {
  55409. return this._isReadyToPlay;
  55410. };
  55411. Sound.prototype._soundLoaded = function (audioData) {
  55412. var _this = this;
  55413. if (!BABYLON.Engine.audioEngine.audioContext) {
  55414. return;
  55415. }
  55416. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55417. _this._audioBuffer = buffer;
  55418. _this._isReadyToPlay = true;
  55419. if (_this.autoplay) {
  55420. _this.play();
  55421. }
  55422. if (_this._readyToPlayCallback) {
  55423. _this._readyToPlayCallback();
  55424. }
  55425. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55426. };
  55427. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55428. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55429. this._audioBuffer = audioBuffer;
  55430. this._isReadyToPlay = true;
  55431. }
  55432. };
  55433. Sound.prototype.updateOptions = function (options) {
  55434. if (options) {
  55435. this.loop = options.loop || this.loop;
  55436. this.maxDistance = options.maxDistance || this.maxDistance;
  55437. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55438. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55439. this.refDistance = options.refDistance || this.refDistance;
  55440. this.distanceModel = options.distanceModel || this.distanceModel;
  55441. this._playbackRate = options.playbackRate || this._playbackRate;
  55442. this._updateSpatialParameters();
  55443. if (this.isPlaying) {
  55444. if (this._streaming) {
  55445. this._htmlAudioElement.playbackRate = this._playbackRate;
  55446. }
  55447. else {
  55448. if (this._soundSource) {
  55449. this._soundSource.playbackRate.value = this._playbackRate;
  55450. }
  55451. }
  55452. }
  55453. }
  55454. };
  55455. Sound.prototype._createSpatialParameters = function () {
  55456. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55457. if (this._scene.headphone) {
  55458. this._panningModel = "HRTF";
  55459. }
  55460. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55461. this._updateSpatialParameters();
  55462. this._soundPanner.connect(this._ouputAudioNode);
  55463. this._inputAudioNode = this._soundPanner;
  55464. }
  55465. };
  55466. Sound.prototype._updateSpatialParameters = function () {
  55467. if (this.spatialSound && this._soundPanner) {
  55468. if (this.useCustomAttenuation) {
  55469. // Tricks to disable in a way embedded Web Audio attenuation
  55470. this._soundPanner.distanceModel = "linear";
  55471. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55472. this._soundPanner.refDistance = 1;
  55473. this._soundPanner.rolloffFactor = 1;
  55474. this._soundPanner.panningModel = this._panningModel;
  55475. }
  55476. else {
  55477. this._soundPanner.distanceModel = this.distanceModel;
  55478. this._soundPanner.maxDistance = this.maxDistance;
  55479. this._soundPanner.refDistance = this.refDistance;
  55480. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55481. this._soundPanner.panningModel = this._panningModel;
  55482. }
  55483. }
  55484. };
  55485. Sound.prototype.switchPanningModelToHRTF = function () {
  55486. this._panningModel = "HRTF";
  55487. this._switchPanningModel();
  55488. };
  55489. Sound.prototype.switchPanningModelToEqualPower = function () {
  55490. this._panningModel = "equalpower";
  55491. this._switchPanningModel();
  55492. };
  55493. Sound.prototype._switchPanningModel = function () {
  55494. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55495. this._soundPanner.panningModel = this._panningModel;
  55496. }
  55497. };
  55498. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55499. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55500. if (this._isOutputConnected) {
  55501. this._ouputAudioNode.disconnect();
  55502. }
  55503. this._ouputAudioNode.connect(soundTrackAudioNode);
  55504. this._isOutputConnected = true;
  55505. }
  55506. };
  55507. /**
  55508. * Transform this sound into a directional source
  55509. * @param coneInnerAngle Size of the inner cone in degree
  55510. * @param coneOuterAngle Size of the outer cone in degree
  55511. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55512. */
  55513. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55514. if (coneOuterAngle < coneInnerAngle) {
  55515. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55516. return;
  55517. }
  55518. this._coneInnerAngle = coneInnerAngle;
  55519. this._coneOuterAngle = coneOuterAngle;
  55520. this._coneOuterGain = coneOuterGain;
  55521. this._isDirectional = true;
  55522. if (this.isPlaying && this.loop) {
  55523. this.stop();
  55524. this.play();
  55525. }
  55526. };
  55527. Sound.prototype.setPosition = function (newPosition) {
  55528. this._position = newPosition;
  55529. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55530. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55531. }
  55532. };
  55533. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55534. this._localDirection = newLocalDirection;
  55535. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55536. this._updateDirection();
  55537. }
  55538. };
  55539. Sound.prototype._updateDirection = function () {
  55540. if (!this._connectedMesh || !this._soundPanner) {
  55541. return;
  55542. }
  55543. var mat = this._connectedMesh.getWorldMatrix();
  55544. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55545. direction.normalize();
  55546. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55547. };
  55548. Sound.prototype.updateDistanceFromListener = function () {
  55549. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55550. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55551. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55552. }
  55553. };
  55554. Sound.prototype.setAttenuationFunction = function (callback) {
  55555. this._customAttenuationFunction = callback;
  55556. };
  55557. /**
  55558. * Play the sound
  55559. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55560. * @param offset (optional) Start the sound setting it at a specific time
  55561. */
  55562. Sound.prototype.play = function (time, offset) {
  55563. var _this = this;
  55564. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55565. try {
  55566. if (this._startOffset < 0) {
  55567. time = -this._startOffset;
  55568. this._startOffset = 0;
  55569. }
  55570. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55571. if (!this._soundSource || !this._streamingSource) {
  55572. if (this.spatialSound && this._soundPanner) {
  55573. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55574. if (this._isDirectional) {
  55575. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55576. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55577. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55578. if (this._connectedMesh) {
  55579. this._updateDirection();
  55580. }
  55581. else {
  55582. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55583. }
  55584. }
  55585. }
  55586. }
  55587. if (this._streaming) {
  55588. if (!this._streamingSource) {
  55589. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55590. this._htmlAudioElement.onended = function () { _this._onended(); };
  55591. this._htmlAudioElement.playbackRate = this._playbackRate;
  55592. }
  55593. this._streamingSource.disconnect();
  55594. this._streamingSource.connect(this._inputAudioNode);
  55595. this._htmlAudioElement.play();
  55596. }
  55597. else {
  55598. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55599. this._soundSource.buffer = this._audioBuffer;
  55600. this._soundSource.connect(this._inputAudioNode);
  55601. this._soundSource.loop = this.loop;
  55602. this._soundSource.playbackRate.value = this._playbackRate;
  55603. this._soundSource.onended = function () { _this._onended(); };
  55604. if (this._soundSource.buffer) {
  55605. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55606. }
  55607. }
  55608. this._startTime = startTime;
  55609. this.isPlaying = true;
  55610. this.isPaused = false;
  55611. }
  55612. catch (ex) {
  55613. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55614. }
  55615. }
  55616. };
  55617. Sound.prototype._onended = function () {
  55618. this.isPlaying = false;
  55619. if (this.onended) {
  55620. this.onended();
  55621. }
  55622. };
  55623. /**
  55624. * Stop the sound
  55625. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55626. */
  55627. Sound.prototype.stop = function (time) {
  55628. if (this.isPlaying) {
  55629. if (this._streaming) {
  55630. this._htmlAudioElement.pause();
  55631. // Test needed for Firefox or it will generate an Invalid State Error
  55632. if (this._htmlAudioElement.currentTime > 0) {
  55633. this._htmlAudioElement.currentTime = 0;
  55634. }
  55635. }
  55636. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55637. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55638. this._soundSource.stop(stopTime);
  55639. this._soundSource.onended = function () { };
  55640. if (!this.isPaused) {
  55641. this._startOffset = 0;
  55642. }
  55643. }
  55644. this.isPlaying = false;
  55645. }
  55646. };
  55647. Sound.prototype.pause = function () {
  55648. if (this.isPlaying) {
  55649. this.isPaused = true;
  55650. if (this._streaming) {
  55651. this._htmlAudioElement.pause();
  55652. }
  55653. else if (BABYLON.Engine.audioEngine.audioContext) {
  55654. this.stop(0);
  55655. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55656. }
  55657. }
  55658. };
  55659. Sound.prototype.setVolume = function (newVolume, time) {
  55660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55661. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55662. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55663. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55664. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55665. }
  55666. else {
  55667. this._soundGain.gain.value = newVolume;
  55668. }
  55669. }
  55670. this._volume = newVolume;
  55671. };
  55672. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55673. this._playbackRate = newPlaybackRate;
  55674. if (this.isPlaying) {
  55675. if (this._streaming) {
  55676. this._htmlAudioElement.playbackRate = this._playbackRate;
  55677. }
  55678. else if (this._soundSource) {
  55679. this._soundSource.playbackRate.value = this._playbackRate;
  55680. }
  55681. }
  55682. };
  55683. Sound.prototype.getVolume = function () {
  55684. return this._volume;
  55685. };
  55686. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55687. var _this = this;
  55688. if (this._connectedMesh && this._registerFunc) {
  55689. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55690. this._registerFunc = null;
  55691. }
  55692. this._connectedMesh = meshToConnectTo;
  55693. if (!this.spatialSound) {
  55694. this.spatialSound = true;
  55695. this._createSpatialParameters();
  55696. if (this.isPlaying && this.loop) {
  55697. this.stop();
  55698. this.play();
  55699. }
  55700. }
  55701. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55702. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55703. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55704. };
  55705. Sound.prototype.detachFromMesh = function () {
  55706. if (this._connectedMesh && this._registerFunc) {
  55707. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55708. this._registerFunc = null;
  55709. this._connectedMesh = null;
  55710. }
  55711. };
  55712. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55713. if (!node.getBoundingInfo) {
  55714. return;
  55715. }
  55716. var mesh = node;
  55717. var boundingInfo = mesh.getBoundingInfo();
  55718. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55719. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55720. this._updateDirection();
  55721. }
  55722. };
  55723. Sound.prototype.clone = function () {
  55724. var _this = this;
  55725. if (!this._streaming) {
  55726. var setBufferAndRun = function () {
  55727. if (_this._isReadyToPlay) {
  55728. clonedSound._audioBuffer = _this.getAudioBuffer();
  55729. clonedSound._isReadyToPlay = true;
  55730. if (clonedSound.autoplay) {
  55731. clonedSound.play();
  55732. }
  55733. }
  55734. else {
  55735. window.setTimeout(setBufferAndRun, 300);
  55736. }
  55737. };
  55738. var currentOptions = {
  55739. autoplay: this.autoplay, loop: this.loop,
  55740. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55741. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55742. refDistance: this.refDistance, distanceModel: this.distanceModel
  55743. };
  55744. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55745. if (this.useCustomAttenuation) {
  55746. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55747. }
  55748. clonedSound.setPosition(this._position);
  55749. clonedSound.setPlaybackRate(this._playbackRate);
  55750. setBufferAndRun();
  55751. return clonedSound;
  55752. }
  55753. else {
  55754. return null;
  55755. }
  55756. };
  55757. Sound.prototype.getAudioBuffer = function () {
  55758. return this._audioBuffer;
  55759. };
  55760. Sound.prototype.serialize = function () {
  55761. var serializationObject = {
  55762. name: this.name,
  55763. url: this.name,
  55764. autoplay: this.autoplay,
  55765. loop: this.loop,
  55766. volume: this._volume,
  55767. spatialSound: this.spatialSound,
  55768. maxDistance: this.maxDistance,
  55769. rolloffFactor: this.rolloffFactor,
  55770. refDistance: this.refDistance,
  55771. distanceModel: this.distanceModel,
  55772. playbackRate: this._playbackRate,
  55773. panningModel: this._panningModel,
  55774. soundTrackId: this.soundTrackId
  55775. };
  55776. if (this.spatialSound) {
  55777. if (this._connectedMesh)
  55778. serializationObject.connectedMeshId = this._connectedMesh.id;
  55779. serializationObject.position = this._position.asArray();
  55780. serializationObject.refDistance = this.refDistance;
  55781. serializationObject.distanceModel = this.distanceModel;
  55782. serializationObject.isDirectional = this._isDirectional;
  55783. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55784. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55785. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55786. serializationObject.coneOuterGain = this._coneOuterGain;
  55787. }
  55788. return serializationObject;
  55789. };
  55790. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55791. var soundName = parsedSound.name;
  55792. var soundUrl;
  55793. if (parsedSound.url) {
  55794. soundUrl = rootUrl + parsedSound.url;
  55795. }
  55796. else {
  55797. soundUrl = rootUrl + soundName;
  55798. }
  55799. var options = {
  55800. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55801. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55802. rolloffFactor: parsedSound.rolloffFactor,
  55803. refDistance: parsedSound.refDistance,
  55804. distanceModel: parsedSound.distanceModel,
  55805. playbackRate: parsedSound.playbackRate
  55806. };
  55807. var newSound;
  55808. if (!sourceSound) {
  55809. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55810. scene._addPendingData(newSound);
  55811. }
  55812. else {
  55813. var setBufferAndRun = function () {
  55814. if (sourceSound._isReadyToPlay) {
  55815. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55816. newSound._isReadyToPlay = true;
  55817. if (newSound.autoplay) {
  55818. newSound.play();
  55819. }
  55820. }
  55821. else {
  55822. window.setTimeout(setBufferAndRun, 300);
  55823. }
  55824. };
  55825. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55826. setBufferAndRun();
  55827. }
  55828. if (parsedSound.position) {
  55829. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55830. newSound.setPosition(soundPosition);
  55831. }
  55832. if (parsedSound.isDirectional) {
  55833. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55834. if (parsedSound.localDirectionToMesh) {
  55835. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55836. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55837. }
  55838. }
  55839. if (parsedSound.connectedMeshId) {
  55840. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55841. if (connectedMesh) {
  55842. newSound.attachToMesh(connectedMesh);
  55843. }
  55844. }
  55845. return newSound;
  55846. };
  55847. return Sound;
  55848. }());
  55849. BABYLON.Sound = Sound;
  55850. })(BABYLON || (BABYLON = {}));
  55851. //# sourceMappingURL=babylon.sound.js.map
  55852. var BABYLON;
  55853. (function (BABYLON) {
  55854. var SoundTrack = /** @class */ (function () {
  55855. function SoundTrack(scene, options) {
  55856. this.id = -1;
  55857. this._isMainTrack = false;
  55858. this._isInitialized = false;
  55859. this._scene = scene;
  55860. this.soundCollection = new Array();
  55861. this._options = options;
  55862. if (!this._isMainTrack) {
  55863. this._scene.soundTracks.push(this);
  55864. this.id = this._scene.soundTracks.length - 1;
  55865. }
  55866. }
  55867. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55868. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55869. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55870. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55871. if (this._options) {
  55872. if (this._options.volume) {
  55873. this._outputAudioNode.gain.value = this._options.volume;
  55874. }
  55875. if (this._options.mainTrack) {
  55876. this._isMainTrack = this._options.mainTrack;
  55877. }
  55878. }
  55879. this._isInitialized = true;
  55880. }
  55881. };
  55882. SoundTrack.prototype.dispose = function () {
  55883. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55884. if (this._connectedAnalyser) {
  55885. this._connectedAnalyser.stopDebugCanvas();
  55886. }
  55887. while (this.soundCollection.length) {
  55888. this.soundCollection[0].dispose();
  55889. }
  55890. if (this._outputAudioNode) {
  55891. this._outputAudioNode.disconnect();
  55892. }
  55893. this._outputAudioNode = null;
  55894. }
  55895. };
  55896. SoundTrack.prototype.AddSound = function (sound) {
  55897. if (!this._isInitialized) {
  55898. this._initializeSoundTrackAudioGraph();
  55899. }
  55900. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55901. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55902. }
  55903. if (sound.soundTrackId) {
  55904. if (sound.soundTrackId === -1) {
  55905. this._scene.mainSoundTrack.RemoveSound(sound);
  55906. }
  55907. else {
  55908. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55909. }
  55910. }
  55911. this.soundCollection.push(sound);
  55912. sound.soundTrackId = this.id;
  55913. };
  55914. SoundTrack.prototype.RemoveSound = function (sound) {
  55915. var index = this.soundCollection.indexOf(sound);
  55916. if (index !== -1) {
  55917. this.soundCollection.splice(index, 1);
  55918. }
  55919. };
  55920. SoundTrack.prototype.setVolume = function (newVolume) {
  55921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55922. this._outputAudioNode.gain.value = newVolume;
  55923. }
  55924. };
  55925. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55927. for (var i = 0; i < this.soundCollection.length; i++) {
  55928. this.soundCollection[i].switchPanningModelToHRTF();
  55929. }
  55930. }
  55931. };
  55932. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55934. for (var i = 0; i < this.soundCollection.length; i++) {
  55935. this.soundCollection[i].switchPanningModelToEqualPower();
  55936. }
  55937. }
  55938. };
  55939. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55940. if (this._connectedAnalyser) {
  55941. this._connectedAnalyser.stopDebugCanvas();
  55942. }
  55943. this._connectedAnalyser = analyser;
  55944. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55945. this._outputAudioNode.disconnect();
  55946. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55947. }
  55948. };
  55949. return SoundTrack;
  55950. }());
  55951. BABYLON.SoundTrack = SoundTrack;
  55952. })(BABYLON || (BABYLON = {}));
  55953. //# sourceMappingURL=babylon.soundtrack.js.map
  55954. var BABYLON;
  55955. (function (BABYLON) {
  55956. var Analyser = /** @class */ (function () {
  55957. function Analyser(scene) {
  55958. this.SMOOTHING = 0.75;
  55959. this.FFT_SIZE = 512;
  55960. this.BARGRAPHAMPLITUDE = 256;
  55961. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55962. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55963. this._scene = scene;
  55964. this._audioEngine = BABYLON.Engine.audioEngine;
  55965. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55966. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55967. this._webAudioAnalyser.minDecibels = -140;
  55968. this._webAudioAnalyser.maxDecibels = 0;
  55969. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55970. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55971. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55972. }
  55973. }
  55974. Analyser.prototype.getFrequencyBinCount = function () {
  55975. if (this._audioEngine.canUseWebAudio) {
  55976. return this._webAudioAnalyser.frequencyBinCount;
  55977. }
  55978. else {
  55979. return 0;
  55980. }
  55981. };
  55982. Analyser.prototype.getByteFrequencyData = function () {
  55983. if (this._audioEngine.canUseWebAudio) {
  55984. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55985. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55986. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55987. }
  55988. return this._byteFreqs;
  55989. };
  55990. Analyser.prototype.getByteTimeDomainData = function () {
  55991. if (this._audioEngine.canUseWebAudio) {
  55992. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55993. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55994. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55995. }
  55996. return this._byteTime;
  55997. };
  55998. Analyser.prototype.getFloatFrequencyData = function () {
  55999. if (this._audioEngine.canUseWebAudio) {
  56000. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56001. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56002. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56003. }
  56004. return this._floatFreqs;
  56005. };
  56006. Analyser.prototype.drawDebugCanvas = function () {
  56007. var _this = this;
  56008. if (this._audioEngine.canUseWebAudio) {
  56009. if (!this._debugCanvas) {
  56010. this._debugCanvas = document.createElement("canvas");
  56011. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56012. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56013. this._debugCanvas.style.position = "absolute";
  56014. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56015. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56016. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56017. document.body.appendChild(this._debugCanvas);
  56018. this._registerFunc = function () {
  56019. _this.drawDebugCanvas();
  56020. };
  56021. this._scene.registerBeforeRender(this._registerFunc);
  56022. }
  56023. if (this._registerFunc && this._debugCanvasContext) {
  56024. var workingArray = this.getByteFrequencyData();
  56025. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56026. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56027. // Draw the frequency domain chart.
  56028. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56029. var value = workingArray[i];
  56030. var percent = value / this.BARGRAPHAMPLITUDE;
  56031. var height = this.DEBUGCANVASSIZE.height * percent;
  56032. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56033. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56034. var hue = i / this.getFrequencyBinCount() * 360;
  56035. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56036. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56037. }
  56038. }
  56039. }
  56040. };
  56041. Analyser.prototype.stopDebugCanvas = function () {
  56042. if (this._debugCanvas) {
  56043. if (this._registerFunc) {
  56044. this._scene.unregisterBeforeRender(this._registerFunc);
  56045. this._registerFunc = null;
  56046. }
  56047. document.body.removeChild(this._debugCanvas);
  56048. this._debugCanvas = null;
  56049. this._debugCanvasContext = null;
  56050. }
  56051. };
  56052. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56053. if (this._audioEngine.canUseWebAudio) {
  56054. inputAudioNode.connect(this._webAudioAnalyser);
  56055. this._webAudioAnalyser.connect(outputAudioNode);
  56056. }
  56057. };
  56058. Analyser.prototype.dispose = function () {
  56059. if (this._audioEngine.canUseWebAudio) {
  56060. this._webAudioAnalyser.disconnect();
  56061. }
  56062. };
  56063. return Analyser;
  56064. }());
  56065. BABYLON.Analyser = Analyser;
  56066. })(BABYLON || (BABYLON = {}));
  56067. //# sourceMappingURL=babylon.analyser.js.map
  56068. var BABYLON;
  56069. (function (BABYLON) {
  56070. var CubeTexture = /** @class */ (function (_super) {
  56071. __extends(CubeTexture, _super);
  56072. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56073. if (extensions === void 0) { extensions = null; }
  56074. if (noMipmap === void 0) { noMipmap = false; }
  56075. if (files === void 0) { files = null; }
  56076. if (onLoad === void 0) { onLoad = null; }
  56077. if (onError === void 0) { onError = null; }
  56078. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56079. if (prefiltered === void 0) { prefiltered = false; }
  56080. if (forcedExtension === void 0) { forcedExtension = null; }
  56081. var _this = _super.call(this, scene) || this;
  56082. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56083. /**
  56084. * Gets or sets the center of the bounding box associated with the cube texture
  56085. * It must define where the camera used to render the texture was set
  56086. */
  56087. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56088. _this.name = rootUrl;
  56089. _this.url = rootUrl;
  56090. _this._noMipmap = noMipmap;
  56091. _this.hasAlpha = false;
  56092. _this._format = format;
  56093. _this._prefiltered = prefiltered;
  56094. _this.isCube = true;
  56095. _this._textureMatrix = BABYLON.Matrix.Identity();
  56096. if (prefiltered) {
  56097. _this.gammaSpace = false;
  56098. }
  56099. if (!rootUrl && !files) {
  56100. return _this;
  56101. }
  56102. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56103. var lastDot = rootUrl.lastIndexOf(".");
  56104. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56105. var isDDS = (extension === ".dds");
  56106. if (!files) {
  56107. if (!isDDS && !extensions) {
  56108. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56109. }
  56110. files = [];
  56111. if (extensions) {
  56112. for (var index = 0; index < extensions.length; index++) {
  56113. files.push(rootUrl + extensions[index]);
  56114. }
  56115. }
  56116. }
  56117. _this._files = files;
  56118. if (!_this._texture) {
  56119. if (!scene.useDelayedTextureLoading) {
  56120. if (prefiltered) {
  56121. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56122. }
  56123. else {
  56124. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56125. }
  56126. }
  56127. else {
  56128. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56129. }
  56130. }
  56131. else if (onLoad) {
  56132. if (_this._texture.isReady) {
  56133. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56134. }
  56135. else {
  56136. _this._texture.onLoadedObservable.add(onLoad);
  56137. }
  56138. }
  56139. return _this;
  56140. }
  56141. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56142. get: function () {
  56143. return this._boundingBoxSize;
  56144. },
  56145. /**
  56146. * Gets or sets the size of the bounding box associated with the cube texture
  56147. * When defined, the cubemap will switch to local mode
  56148. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56149. * @example https://www.babylonjs-playground.com/#RNASML
  56150. */
  56151. set: function (value) {
  56152. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56153. return;
  56154. }
  56155. this._boundingBoxSize = value;
  56156. var scene = this.getScene();
  56157. if (scene) {
  56158. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56159. }
  56160. },
  56161. enumerable: true,
  56162. configurable: true
  56163. });
  56164. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56165. return new CubeTexture("", scene, null, noMipmap, files);
  56166. };
  56167. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56168. if (forcedExtension === void 0) { forcedExtension = null; }
  56169. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56170. };
  56171. // Methods
  56172. CubeTexture.prototype.delayLoad = function () {
  56173. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56174. return;
  56175. }
  56176. var scene = this.getScene();
  56177. if (!scene) {
  56178. return;
  56179. }
  56180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56181. this._texture = this._getFromCache(this.url, this._noMipmap);
  56182. if (!this._texture) {
  56183. if (this._prefiltered) {
  56184. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56185. }
  56186. else {
  56187. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56188. }
  56189. }
  56190. };
  56191. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56192. return this._textureMatrix;
  56193. };
  56194. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56195. this._textureMatrix = value;
  56196. };
  56197. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56198. var texture = BABYLON.SerializationHelper.Parse(function () {
  56199. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56200. }, parsedTexture, scene);
  56201. // Animations
  56202. if (parsedTexture.animations) {
  56203. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56204. var parsedAnimation = parsedTexture.animations[animationIndex];
  56205. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56206. }
  56207. }
  56208. return texture;
  56209. };
  56210. CubeTexture.prototype.clone = function () {
  56211. var _this = this;
  56212. return BABYLON.SerializationHelper.Clone(function () {
  56213. var scene = _this.getScene();
  56214. if (!scene) {
  56215. return _this;
  56216. }
  56217. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56218. }, this);
  56219. };
  56220. return CubeTexture;
  56221. }(BABYLON.BaseTexture));
  56222. BABYLON.CubeTexture = CubeTexture;
  56223. })(BABYLON || (BABYLON = {}));
  56224. //# sourceMappingURL=babylon.cubeTexture.js.map
  56225. var BABYLON;
  56226. (function (BABYLON) {
  56227. var RenderTargetTexture = /** @class */ (function (_super) {
  56228. __extends(RenderTargetTexture, _super);
  56229. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56230. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56231. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56232. if (isCube === void 0) { isCube = false; }
  56233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56234. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56235. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56236. if (isMulti === void 0) { isMulti = false; }
  56237. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56238. _this.isCube = isCube;
  56239. /**
  56240. * Use this list to define the list of mesh you want to render.
  56241. */
  56242. _this.renderList = new Array();
  56243. _this.renderParticles = true;
  56244. _this.renderSprites = false;
  56245. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56246. _this.ignoreCameraViewport = false;
  56247. // Events
  56248. /**
  56249. * An event triggered when the texture is unbind.
  56250. * @type {BABYLON.Observable}
  56251. */
  56252. _this.onBeforeBindObservable = new BABYLON.Observable();
  56253. /**
  56254. * An event triggered when the texture is unbind.
  56255. * @type {BABYLON.Observable}
  56256. */
  56257. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56258. /**
  56259. * An event triggered before rendering the texture
  56260. * @type {BABYLON.Observable}
  56261. */
  56262. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56263. /**
  56264. * An event triggered after rendering the texture
  56265. * @type {BABYLON.Observable}
  56266. */
  56267. _this.onAfterRenderObservable = new BABYLON.Observable();
  56268. /**
  56269. * An event triggered after the texture clear
  56270. * @type {BABYLON.Observable}
  56271. */
  56272. _this.onClearObservable = new BABYLON.Observable();
  56273. _this._currentRefreshId = -1;
  56274. _this._refreshRate = 1;
  56275. _this._samples = 1;
  56276. /**
  56277. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56278. * It must define where the camera used to render the texture is set
  56279. */
  56280. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56281. scene = _this.getScene();
  56282. if (!scene) {
  56283. return _this;
  56284. }
  56285. _this._engine = scene.getEngine();
  56286. _this.name = name;
  56287. _this.isRenderTarget = true;
  56288. _this._initialSizeParameter = size;
  56289. _this._processSizeParameter(size);
  56290. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56291. });
  56292. _this._generateMipMaps = generateMipMaps ? true : false;
  56293. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56294. // Rendering groups
  56295. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56296. if (isMulti) {
  56297. return _this;
  56298. }
  56299. _this._renderTargetOptions = {
  56300. generateMipMaps: generateMipMaps,
  56301. type: type,
  56302. samplingMode: samplingMode,
  56303. generateDepthBuffer: generateDepthBuffer,
  56304. generateStencilBuffer: generateStencilBuffer
  56305. };
  56306. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56307. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56308. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56309. }
  56310. if (isCube) {
  56311. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56312. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56313. _this._textureMatrix = BABYLON.Matrix.Identity();
  56314. }
  56315. else {
  56316. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56317. }
  56318. return _this;
  56319. }
  56320. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56321. get: function () {
  56322. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56323. },
  56324. enumerable: true,
  56325. configurable: true
  56326. });
  56327. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56328. get: function () {
  56329. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56330. },
  56331. enumerable: true,
  56332. configurable: true
  56333. });
  56334. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56335. get: function () {
  56336. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56337. },
  56338. enumerable: true,
  56339. configurable: true
  56340. });
  56341. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56342. set: function (callback) {
  56343. if (this._onAfterUnbindObserver) {
  56344. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56345. }
  56346. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56352. set: function (callback) {
  56353. if (this._onBeforeRenderObserver) {
  56354. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56355. }
  56356. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56357. },
  56358. enumerable: true,
  56359. configurable: true
  56360. });
  56361. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56362. set: function (callback) {
  56363. if (this._onAfterRenderObserver) {
  56364. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56365. }
  56366. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56367. },
  56368. enumerable: true,
  56369. configurable: true
  56370. });
  56371. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56372. set: function (callback) {
  56373. if (this._onClearObserver) {
  56374. this.onClearObservable.remove(this._onClearObserver);
  56375. }
  56376. this._onClearObserver = this.onClearObservable.add(callback);
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56382. get: function () {
  56383. return this._renderTargetOptions;
  56384. },
  56385. enumerable: true,
  56386. configurable: true
  56387. });
  56388. RenderTargetTexture.prototype._onRatioRescale = function () {
  56389. if (this._sizeRatio) {
  56390. this.resize(this._initialSizeParameter);
  56391. }
  56392. };
  56393. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56394. get: function () {
  56395. return this._boundingBoxSize;
  56396. },
  56397. /**
  56398. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56399. * When defined, the cubemap will switch to local mode
  56400. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56401. * @example https://www.babylonjs-playground.com/#RNASML
  56402. */
  56403. set: function (value) {
  56404. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56405. return;
  56406. }
  56407. this._boundingBoxSize = value;
  56408. var scene = this.getScene();
  56409. if (scene) {
  56410. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56411. }
  56412. },
  56413. enumerable: true,
  56414. configurable: true
  56415. });
  56416. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56417. if (size.ratio) {
  56418. this._sizeRatio = size.ratio;
  56419. this._size = {
  56420. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56421. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56422. };
  56423. }
  56424. else {
  56425. this._size = size;
  56426. }
  56427. };
  56428. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56429. get: function () {
  56430. return this._samples;
  56431. },
  56432. set: function (value) {
  56433. if (this._samples === value) {
  56434. return;
  56435. }
  56436. var scene = this.getScene();
  56437. if (!scene) {
  56438. return;
  56439. }
  56440. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56441. },
  56442. enumerable: true,
  56443. configurable: true
  56444. });
  56445. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56446. this._currentRefreshId = -1;
  56447. };
  56448. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56449. get: function () {
  56450. return this._refreshRate;
  56451. },
  56452. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56453. set: function (value) {
  56454. this._refreshRate = value;
  56455. this.resetRefreshCounter();
  56456. },
  56457. enumerable: true,
  56458. configurable: true
  56459. });
  56460. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56461. if (!this._postProcessManager) {
  56462. var scene = this.getScene();
  56463. if (!scene) {
  56464. return;
  56465. }
  56466. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56467. this._postProcesses = new Array();
  56468. }
  56469. this._postProcesses.push(postProcess);
  56470. this._postProcesses[0].autoClear = false;
  56471. };
  56472. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56473. if (!this._postProcesses) {
  56474. return;
  56475. }
  56476. if (dispose) {
  56477. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56478. var postProcess = _a[_i];
  56479. postProcess.dispose();
  56480. }
  56481. }
  56482. this._postProcesses = [];
  56483. };
  56484. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56485. if (!this._postProcesses) {
  56486. return;
  56487. }
  56488. var index = this._postProcesses.indexOf(postProcess);
  56489. if (index === -1) {
  56490. return;
  56491. }
  56492. this._postProcesses.splice(index, 1);
  56493. if (this._postProcesses.length > 0) {
  56494. this._postProcesses[0].autoClear = false;
  56495. }
  56496. };
  56497. RenderTargetTexture.prototype._shouldRender = function () {
  56498. if (this._currentRefreshId === -1) {
  56499. this._currentRefreshId = 1;
  56500. return true;
  56501. }
  56502. if (this.refreshRate === this._currentRefreshId) {
  56503. this._currentRefreshId = 1;
  56504. return true;
  56505. }
  56506. this._currentRefreshId++;
  56507. return false;
  56508. };
  56509. RenderTargetTexture.prototype.getRenderSize = function () {
  56510. if (this._size.width) {
  56511. return this._size.width;
  56512. }
  56513. return this._size;
  56514. };
  56515. RenderTargetTexture.prototype.getRenderWidth = function () {
  56516. if (this._size.width) {
  56517. return this._size.width;
  56518. }
  56519. return this._size;
  56520. };
  56521. RenderTargetTexture.prototype.getRenderHeight = function () {
  56522. if (this._size.width) {
  56523. return this._size.height;
  56524. }
  56525. return this._size;
  56526. };
  56527. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56528. get: function () {
  56529. return true;
  56530. },
  56531. enumerable: true,
  56532. configurable: true
  56533. });
  56534. RenderTargetTexture.prototype.scale = function (ratio) {
  56535. var newSize = this.getRenderSize() * ratio;
  56536. this.resize(newSize);
  56537. };
  56538. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56539. if (this.isCube) {
  56540. return this._textureMatrix;
  56541. }
  56542. return _super.prototype.getReflectionTextureMatrix.call(this);
  56543. };
  56544. RenderTargetTexture.prototype.resize = function (size) {
  56545. this.releaseInternalTexture();
  56546. var scene = this.getScene();
  56547. if (!scene) {
  56548. return;
  56549. }
  56550. this._processSizeParameter(size);
  56551. if (this.isCube) {
  56552. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56553. }
  56554. else {
  56555. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56556. }
  56557. };
  56558. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56559. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56560. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56561. var scene = this.getScene();
  56562. if (!scene) {
  56563. return;
  56564. }
  56565. var engine = scene.getEngine();
  56566. if (this.useCameraPostProcesses !== undefined) {
  56567. useCameraPostProcess = this.useCameraPostProcesses;
  56568. }
  56569. if (this._waitingRenderList) {
  56570. this.renderList = [];
  56571. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56572. var id = this._waitingRenderList[index];
  56573. var mesh_1 = scene.getMeshByID(id);
  56574. if (mesh_1) {
  56575. this.renderList.push(mesh_1);
  56576. }
  56577. }
  56578. delete this._waitingRenderList;
  56579. }
  56580. // Is predicate defined?
  56581. if (this.renderListPredicate) {
  56582. if (this.renderList) {
  56583. this.renderList.splice(0); // Clear previous renderList
  56584. }
  56585. else {
  56586. this.renderList = [];
  56587. }
  56588. var scene = this.getScene();
  56589. if (!scene) {
  56590. return;
  56591. }
  56592. var sceneMeshes = scene.meshes;
  56593. for (var index = 0; index < sceneMeshes.length; index++) {
  56594. var mesh = sceneMeshes[index];
  56595. if (this.renderListPredicate(mesh)) {
  56596. this.renderList.push(mesh);
  56597. }
  56598. }
  56599. }
  56600. this.onBeforeBindObservable.notifyObservers(this);
  56601. // Set custom projection.
  56602. // Needs to be before binding to prevent changing the aspect ratio.
  56603. var camera;
  56604. if (this.activeCamera) {
  56605. camera = this.activeCamera;
  56606. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56607. if (this.activeCamera !== scene.activeCamera) {
  56608. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56609. }
  56610. }
  56611. else {
  56612. camera = scene.activeCamera;
  56613. if (camera) {
  56614. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56615. }
  56616. }
  56617. // Prepare renderingManager
  56618. this._renderingManager.reset();
  56619. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56620. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56621. var sceneRenderId = scene.getRenderId();
  56622. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56623. var mesh = currentRenderList[meshIndex];
  56624. if (mesh) {
  56625. if (!mesh.isReady()) {
  56626. // Reset _currentRefreshId
  56627. this.resetRefreshCounter();
  56628. continue;
  56629. }
  56630. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56631. var isMasked = void 0;
  56632. if (!this.renderList && camera) {
  56633. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56634. }
  56635. else {
  56636. isMasked = false;
  56637. }
  56638. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56639. mesh._activate(sceneRenderId);
  56640. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56641. var subMesh = mesh.subMeshes[subIndex];
  56642. scene._activeIndices.addCount(subMesh.indexCount, false);
  56643. this._renderingManager.dispatch(subMesh, mesh);
  56644. }
  56645. }
  56646. }
  56647. }
  56648. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56649. var particleSystem = scene.particleSystems[particleIndex];
  56650. var emitter = particleSystem.emitter;
  56651. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56652. continue;
  56653. }
  56654. if (currentRenderList.indexOf(emitter) >= 0) {
  56655. this._renderingManager.dispatchParticles(particleSystem);
  56656. }
  56657. }
  56658. if (this.isCube) {
  56659. for (var face = 0; face < 6; face++) {
  56660. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56661. scene.incrementRenderId();
  56662. scene.resetCachedMaterial();
  56663. }
  56664. }
  56665. else {
  56666. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56667. }
  56668. this.onAfterUnbindObservable.notifyObservers(this);
  56669. if (scene.activeCamera) {
  56670. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56671. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56672. }
  56673. engine.setViewport(scene.activeCamera.viewport);
  56674. }
  56675. scene.resetCachedMaterial();
  56676. };
  56677. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56678. var minimum = 128;
  56679. var x = renderDimension * scale;
  56680. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56681. // Ensure we don't exceed the render dimension (while staying POT)
  56682. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56683. };
  56684. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56685. var _this = this;
  56686. if (!this._texture) {
  56687. return;
  56688. }
  56689. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56690. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56691. });
  56692. };
  56693. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56694. var scene = this.getScene();
  56695. if (!scene) {
  56696. return;
  56697. }
  56698. var engine = scene.getEngine();
  56699. if (!this._texture) {
  56700. return;
  56701. }
  56702. // Bind
  56703. if (this._postProcessManager) {
  56704. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56705. }
  56706. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56707. if (this._texture) {
  56708. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56709. }
  56710. }
  56711. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56712. // Clear
  56713. if (this.onClearObservable.hasObservers()) {
  56714. this.onClearObservable.notifyObservers(engine);
  56715. }
  56716. else {
  56717. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56718. }
  56719. if (!this._doNotChangeAspectRatio) {
  56720. scene.updateTransformMatrix(true);
  56721. }
  56722. // Render
  56723. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56724. if (this._postProcessManager) {
  56725. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56726. }
  56727. else if (useCameraPostProcess) {
  56728. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56729. }
  56730. if (!this._doNotChangeAspectRatio) {
  56731. scene.updateTransformMatrix(true);
  56732. }
  56733. // Dump ?
  56734. if (dumpForDebug) {
  56735. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56736. }
  56737. // Unbind
  56738. if (!this.isCube || faceIndex === 5) {
  56739. if (this.isCube) {
  56740. if (faceIndex === 5) {
  56741. engine.generateMipMapsForCubemap(this._texture);
  56742. }
  56743. }
  56744. this.unbindFrameBuffer(engine, faceIndex);
  56745. }
  56746. else {
  56747. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56748. }
  56749. };
  56750. /**
  56751. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56752. * This allowed control for front to back rendering or reversly depending of the special needs.
  56753. *
  56754. * @param renderingGroupId The rendering group id corresponding to its index
  56755. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56756. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56757. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56758. */
  56759. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56760. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56761. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56762. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56763. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56764. };
  56765. /**
  56766. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56767. *
  56768. * @param renderingGroupId The rendering group id corresponding to its index
  56769. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56770. */
  56771. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56772. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56773. };
  56774. RenderTargetTexture.prototype.clone = function () {
  56775. var textureSize = this.getSize();
  56776. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  56777. // Base texture
  56778. newTexture.hasAlpha = this.hasAlpha;
  56779. newTexture.level = this.level;
  56780. // RenderTarget Texture
  56781. newTexture.coordinatesMode = this.coordinatesMode;
  56782. if (this.renderList) {
  56783. newTexture.renderList = this.renderList.slice(0);
  56784. }
  56785. return newTexture;
  56786. };
  56787. RenderTargetTexture.prototype.serialize = function () {
  56788. if (!this.name) {
  56789. return null;
  56790. }
  56791. var serializationObject = _super.prototype.serialize.call(this);
  56792. serializationObject.renderTargetSize = this.getRenderSize();
  56793. serializationObject.renderList = [];
  56794. if (this.renderList) {
  56795. for (var index = 0; index < this.renderList.length; index++) {
  56796. serializationObject.renderList.push(this.renderList[index].id);
  56797. }
  56798. }
  56799. return serializationObject;
  56800. };
  56801. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56802. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56803. var objBuffer = this.getInternalTexture();
  56804. var scene = this.getScene();
  56805. if (objBuffer && scene) {
  56806. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56807. }
  56808. };
  56809. RenderTargetTexture.prototype.dispose = function () {
  56810. if (this._postProcessManager) {
  56811. this._postProcessManager.dispose();
  56812. this._postProcessManager = null;
  56813. }
  56814. this.clearPostProcesses(true);
  56815. if (this._resizeObserver) {
  56816. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56817. this._resizeObserver = null;
  56818. }
  56819. this.renderList = null;
  56820. // Remove from custom render targets
  56821. var scene = this.getScene();
  56822. if (!scene) {
  56823. return;
  56824. }
  56825. var index = scene.customRenderTargets.indexOf(this);
  56826. if (index >= 0) {
  56827. scene.customRenderTargets.splice(index, 1);
  56828. }
  56829. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56830. var camera = _a[_i];
  56831. index = camera.customRenderTargets.indexOf(this);
  56832. if (index >= 0) {
  56833. camera.customRenderTargets.splice(index, 1);
  56834. }
  56835. }
  56836. _super.prototype.dispose.call(this);
  56837. };
  56838. RenderTargetTexture.prototype._rebuild = function () {
  56839. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56840. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56841. }
  56842. if (this._postProcessManager) {
  56843. this._postProcessManager._rebuild();
  56844. }
  56845. };
  56846. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56847. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56848. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56849. return RenderTargetTexture;
  56850. }(BABYLON.Texture));
  56851. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56852. })(BABYLON || (BABYLON = {}));
  56853. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56854. var BABYLON;
  56855. (function (BABYLON) {
  56856. ;
  56857. var MultiRenderTarget = /** @class */ (function (_super) {
  56858. __extends(MultiRenderTarget, _super);
  56859. function MultiRenderTarget(name, size, count, scene, options) {
  56860. var _this = this;
  56861. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56862. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56863. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56864. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56865. _this._engine = scene.getEngine();
  56866. if (!_this.isSupported) {
  56867. _this.dispose();
  56868. return;
  56869. }
  56870. var types = [];
  56871. var samplingModes = [];
  56872. for (var i = 0; i < count; i++) {
  56873. if (options && options.types && options.types[i] !== undefined) {
  56874. types.push(options.types[i]);
  56875. }
  56876. else {
  56877. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56878. }
  56879. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56880. samplingModes.push(options.samplingModes[i]);
  56881. }
  56882. else {
  56883. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56884. }
  56885. }
  56886. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56887. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56888. _this._size = size;
  56889. _this._multiRenderTargetOptions = {
  56890. samplingModes: samplingModes,
  56891. generateMipMaps: generateMipMaps,
  56892. generateDepthBuffer: generateDepthBuffer,
  56893. generateStencilBuffer: generateStencilBuffer,
  56894. generateDepthTexture: generateDepthTexture,
  56895. types: types,
  56896. textureCount: count
  56897. };
  56898. _this._createInternalTextures();
  56899. _this._createTextures();
  56900. return _this;
  56901. }
  56902. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56903. get: function () {
  56904. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56905. },
  56906. enumerable: true,
  56907. configurable: true
  56908. });
  56909. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56910. get: function () {
  56911. return this._textures;
  56912. },
  56913. enumerable: true,
  56914. configurable: true
  56915. });
  56916. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56917. get: function () {
  56918. return this._textures[this._textures.length - 1];
  56919. },
  56920. enumerable: true,
  56921. configurable: true
  56922. });
  56923. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56924. set: function (wrap) {
  56925. if (this._textures) {
  56926. for (var i = 0; i < this._textures.length; i++) {
  56927. this._textures[i].wrapU = wrap;
  56928. }
  56929. }
  56930. },
  56931. enumerable: true,
  56932. configurable: true
  56933. });
  56934. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56935. set: function (wrap) {
  56936. if (this._textures) {
  56937. for (var i = 0; i < this._textures.length; i++) {
  56938. this._textures[i].wrapV = wrap;
  56939. }
  56940. }
  56941. },
  56942. enumerable: true,
  56943. configurable: true
  56944. });
  56945. MultiRenderTarget.prototype._rebuild = function () {
  56946. this.releaseInternalTextures();
  56947. this._createInternalTextures();
  56948. for (var i = 0; i < this._internalTextures.length; i++) {
  56949. var texture = this._textures[i];
  56950. texture._texture = this._internalTextures[i];
  56951. }
  56952. // Keeps references to frame buffer and stencil/depth buffer
  56953. this._texture = this._internalTextures[0];
  56954. };
  56955. MultiRenderTarget.prototype._createInternalTextures = function () {
  56956. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56957. };
  56958. MultiRenderTarget.prototype._createTextures = function () {
  56959. this._textures = [];
  56960. for (var i = 0; i < this._internalTextures.length; i++) {
  56961. var texture = new BABYLON.Texture(null, this.getScene());
  56962. texture._texture = this._internalTextures[i];
  56963. this._textures.push(texture);
  56964. }
  56965. // Keeps references to frame buffer and stencil/depth buffer
  56966. this._texture = this._internalTextures[0];
  56967. };
  56968. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56969. get: function () {
  56970. return this._samples;
  56971. },
  56972. set: function (value) {
  56973. if (this._samples === value) {
  56974. return;
  56975. }
  56976. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56977. },
  56978. enumerable: true,
  56979. configurable: true
  56980. });
  56981. MultiRenderTarget.prototype.resize = function (size) {
  56982. this.releaseInternalTextures();
  56983. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56984. this._createInternalTextures();
  56985. };
  56986. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56987. var _this = this;
  56988. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56989. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56990. });
  56991. };
  56992. MultiRenderTarget.prototype.dispose = function () {
  56993. this.releaseInternalTextures();
  56994. _super.prototype.dispose.call(this);
  56995. };
  56996. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56997. if (!this._internalTextures) {
  56998. return;
  56999. }
  57000. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57001. if (this._internalTextures[i] !== undefined) {
  57002. this._internalTextures[i].dispose();
  57003. this._internalTextures.splice(i, 1);
  57004. }
  57005. }
  57006. };
  57007. return MultiRenderTarget;
  57008. }(BABYLON.RenderTargetTexture));
  57009. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57010. })(BABYLON || (BABYLON = {}));
  57011. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57012. var BABYLON;
  57013. (function (BABYLON) {
  57014. var MirrorTexture = /** @class */ (function (_super) {
  57015. __extends(MirrorTexture, _super);
  57016. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57017. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57019. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57020. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57021. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57022. _this._transformMatrix = BABYLON.Matrix.Zero();
  57023. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57024. _this._adaptiveBlurKernel = 0;
  57025. _this._blurKernelX = 0;
  57026. _this._blurKernelY = 0;
  57027. _this._blurRatio = 1.0;
  57028. _this.ignoreCameraViewport = true;
  57029. _this.onBeforeRenderObservable.add(function () {
  57030. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57031. _this._savedViewMatrix = scene.getViewMatrix();
  57032. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57033. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57034. scene.clipPlane = _this.mirrorPlane;
  57035. scene.getEngine().cullBackFaces = false;
  57036. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57037. });
  57038. _this.onAfterRenderObservable.add(function () {
  57039. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57040. scene.getEngine().cullBackFaces = true;
  57041. scene._mirroredCameraPosition = null;
  57042. delete scene.clipPlane;
  57043. });
  57044. return _this;
  57045. }
  57046. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57047. get: function () {
  57048. return this._blurRatio;
  57049. },
  57050. set: function (value) {
  57051. if (this._blurRatio === value) {
  57052. return;
  57053. }
  57054. this._blurRatio = value;
  57055. this._preparePostProcesses();
  57056. },
  57057. enumerable: true,
  57058. configurable: true
  57059. });
  57060. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57061. set: function (value) {
  57062. this._adaptiveBlurKernel = value;
  57063. this._autoComputeBlurKernel();
  57064. },
  57065. enumerable: true,
  57066. configurable: true
  57067. });
  57068. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57069. set: function (value) {
  57070. this.blurKernelX = value;
  57071. this.blurKernelY = value;
  57072. },
  57073. enumerable: true,
  57074. configurable: true
  57075. });
  57076. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57077. get: function () {
  57078. return this._blurKernelX;
  57079. },
  57080. set: function (value) {
  57081. if (this._blurKernelX === value) {
  57082. return;
  57083. }
  57084. this._blurKernelX = value;
  57085. this._preparePostProcesses();
  57086. },
  57087. enumerable: true,
  57088. configurable: true
  57089. });
  57090. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57091. get: function () {
  57092. return this._blurKernelY;
  57093. },
  57094. set: function (value) {
  57095. if (this._blurKernelY === value) {
  57096. return;
  57097. }
  57098. this._blurKernelY = value;
  57099. this._preparePostProcesses();
  57100. },
  57101. enumerable: true,
  57102. configurable: true
  57103. });
  57104. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57105. var engine = this.getScene().getEngine();
  57106. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57107. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57108. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57109. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57110. };
  57111. MirrorTexture.prototype._onRatioRescale = function () {
  57112. if (this._sizeRatio) {
  57113. this.resize(this._initialSizeParameter);
  57114. if (!this._adaptiveBlurKernel) {
  57115. this._preparePostProcesses();
  57116. }
  57117. }
  57118. if (this._adaptiveBlurKernel) {
  57119. this._autoComputeBlurKernel();
  57120. }
  57121. };
  57122. MirrorTexture.prototype._preparePostProcesses = function () {
  57123. this.clearPostProcesses(true);
  57124. if (this._blurKernelX && this._blurKernelY) {
  57125. var engine = this.getScene().getEngine();
  57126. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57127. 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);
  57128. this._blurX.autoClear = false;
  57129. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57130. this._blurX.inputTexture = this._texture;
  57131. }
  57132. else {
  57133. this._blurX.alwaysForcePOT = true;
  57134. }
  57135. 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);
  57136. this._blurY.autoClear = false;
  57137. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57138. this.addPostProcess(this._blurX);
  57139. this.addPostProcess(this._blurY);
  57140. }
  57141. else {
  57142. if (this._blurY) {
  57143. this.removePostProcess(this._blurY);
  57144. this._blurY.dispose();
  57145. this._blurY = null;
  57146. }
  57147. if (this._blurX) {
  57148. this.removePostProcess(this._blurX);
  57149. this._blurX.dispose();
  57150. this._blurX = null;
  57151. }
  57152. }
  57153. };
  57154. MirrorTexture.prototype.clone = function () {
  57155. var scene = this.getScene();
  57156. if (!scene) {
  57157. return this;
  57158. }
  57159. var textureSize = this.getSize();
  57160. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57161. // Base texture
  57162. newTexture.hasAlpha = this.hasAlpha;
  57163. newTexture.level = this.level;
  57164. // Mirror Texture
  57165. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57166. if (this.renderList) {
  57167. newTexture.renderList = this.renderList.slice(0);
  57168. }
  57169. return newTexture;
  57170. };
  57171. MirrorTexture.prototype.serialize = function () {
  57172. if (!this.name) {
  57173. return null;
  57174. }
  57175. var serializationObject = _super.prototype.serialize.call(this);
  57176. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57177. return serializationObject;
  57178. };
  57179. return MirrorTexture;
  57180. }(BABYLON.RenderTargetTexture));
  57181. BABYLON.MirrorTexture = MirrorTexture;
  57182. })(BABYLON || (BABYLON = {}));
  57183. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57184. var BABYLON;
  57185. (function (BABYLON) {
  57186. /**
  57187. * Creates a refraction texture used by refraction channel of the standard material.
  57188. * @param name the texture name
  57189. * @param size size of the underlying texture
  57190. * @param scene root scene
  57191. */
  57192. var RefractionTexture = /** @class */ (function (_super) {
  57193. __extends(RefractionTexture, _super);
  57194. function RefractionTexture(name, size, scene, generateMipMaps) {
  57195. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57196. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57197. _this.depth = 2.0;
  57198. _this.onBeforeRenderObservable.add(function () {
  57199. scene.clipPlane = _this.refractionPlane;
  57200. });
  57201. _this.onAfterRenderObservable.add(function () {
  57202. delete scene.clipPlane;
  57203. });
  57204. return _this;
  57205. }
  57206. RefractionTexture.prototype.clone = function () {
  57207. var scene = this.getScene();
  57208. if (!scene) {
  57209. return this;
  57210. }
  57211. var textureSize = this.getSize();
  57212. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57213. // Base texture
  57214. newTexture.hasAlpha = this.hasAlpha;
  57215. newTexture.level = this.level;
  57216. // Refraction Texture
  57217. newTexture.refractionPlane = this.refractionPlane.clone();
  57218. if (this.renderList) {
  57219. newTexture.renderList = this.renderList.slice(0);
  57220. }
  57221. newTexture.depth = this.depth;
  57222. return newTexture;
  57223. };
  57224. RefractionTexture.prototype.serialize = function () {
  57225. if (!this.name) {
  57226. return null;
  57227. }
  57228. var serializationObject = _super.prototype.serialize.call(this);
  57229. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57230. serializationObject.depth = this.depth;
  57231. return serializationObject;
  57232. };
  57233. return RefractionTexture;
  57234. }(BABYLON.RenderTargetTexture));
  57235. BABYLON.RefractionTexture = RefractionTexture;
  57236. })(BABYLON || (BABYLON = {}));
  57237. //# sourceMappingURL=babylon.refractionTexture.js.map
  57238. var BABYLON;
  57239. (function (BABYLON) {
  57240. var DynamicTexture = /** @class */ (function (_super) {
  57241. __extends(DynamicTexture, _super);
  57242. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57243. if (scene === void 0) { scene = null; }
  57244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57245. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57246. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57247. _this.name = name;
  57248. _this._engine = _this.getScene().getEngine();
  57249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57251. _this._generateMipMaps = generateMipMaps;
  57252. if (options.getContext) {
  57253. _this._canvas = options;
  57254. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57255. }
  57256. else {
  57257. _this._canvas = document.createElement("canvas");
  57258. if (options.width) {
  57259. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57260. }
  57261. else {
  57262. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57263. }
  57264. }
  57265. var textureSize = _this.getSize();
  57266. _this._canvas.width = textureSize.width;
  57267. _this._canvas.height = textureSize.height;
  57268. _this._context = _this._canvas.getContext("2d");
  57269. return _this;
  57270. }
  57271. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57272. get: function () {
  57273. return true;
  57274. },
  57275. enumerable: true,
  57276. configurable: true
  57277. });
  57278. DynamicTexture.prototype._recreate = function (textureSize) {
  57279. this._canvas.width = textureSize.width;
  57280. this._canvas.height = textureSize.height;
  57281. this.releaseInternalTexture();
  57282. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57283. };
  57284. DynamicTexture.prototype.scale = function (ratio) {
  57285. var textureSize = this.getSize();
  57286. textureSize.width *= ratio;
  57287. textureSize.height *= ratio;
  57288. this._recreate(textureSize);
  57289. };
  57290. DynamicTexture.prototype.scaleTo = function (width, height) {
  57291. var textureSize = this.getSize();
  57292. textureSize.width = width;
  57293. textureSize.height = height;
  57294. this._recreate(textureSize);
  57295. };
  57296. DynamicTexture.prototype.getContext = function () {
  57297. return this._context;
  57298. };
  57299. DynamicTexture.prototype.clear = function () {
  57300. var size = this.getSize();
  57301. this._context.fillRect(0, 0, size.width, size.height);
  57302. };
  57303. DynamicTexture.prototype.update = function (invertY) {
  57304. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57305. };
  57306. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57307. if (update === void 0) { update = true; }
  57308. var size = this.getSize();
  57309. if (clearColor) {
  57310. this._context.fillStyle = clearColor;
  57311. this._context.fillRect(0, 0, size.width, size.height);
  57312. }
  57313. this._context.font = font;
  57314. if (x === null || x === undefined) {
  57315. var textSize = this._context.measureText(text);
  57316. x = (size.width - textSize.width) / 2;
  57317. }
  57318. if (y === null || y === undefined) {
  57319. var fontSize = parseInt((font.replace(/\D/g, '')));
  57320. ;
  57321. y = (size.height / 2) + (fontSize / 3.65);
  57322. }
  57323. this._context.fillStyle = color;
  57324. this._context.fillText(text, x, y);
  57325. if (update) {
  57326. this.update(invertY);
  57327. }
  57328. };
  57329. DynamicTexture.prototype.clone = function () {
  57330. var scene = this.getScene();
  57331. if (!scene) {
  57332. return this;
  57333. }
  57334. var textureSize = this.getSize();
  57335. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57336. // Base texture
  57337. newTexture.hasAlpha = this.hasAlpha;
  57338. newTexture.level = this.level;
  57339. // Dynamic Texture
  57340. newTexture.wrapU = this.wrapU;
  57341. newTexture.wrapV = this.wrapV;
  57342. return newTexture;
  57343. };
  57344. DynamicTexture.prototype._rebuild = function () {
  57345. this.update();
  57346. };
  57347. return DynamicTexture;
  57348. }(BABYLON.Texture));
  57349. BABYLON.DynamicTexture = DynamicTexture;
  57350. })(BABYLON || (BABYLON = {}));
  57351. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57352. var BABYLON;
  57353. (function (BABYLON) {
  57354. var VideoTexture = /** @class */ (function (_super) {
  57355. __extends(VideoTexture, _super);
  57356. /**
  57357. * Creates a video texture.
  57358. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57359. * @param {string | null} name optional name, will detect from video source, if not defined
  57360. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57361. * @param {BABYLON.Scene} scene is obviously the current scene.
  57362. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57363. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57364. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57365. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57366. */
  57367. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57368. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57369. if (invertY === void 0) { invertY = false; }
  57370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57371. if (settings === void 0) { settings = {
  57372. autoPlay: true,
  57373. loop: true,
  57374. autoUpdateTexture: true,
  57375. }; }
  57376. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57377. _this._createInternalTexture = function () {
  57378. if (_this._texture != null) {
  57379. return;
  57380. }
  57381. if (!_this._engine.needPOTTextures ||
  57382. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57383. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57384. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57385. }
  57386. else {
  57387. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57388. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57389. _this._generateMipMaps = false;
  57390. }
  57391. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57392. _this._texture.isReady = true;
  57393. _this._updateInternalTexture();
  57394. };
  57395. _this.reset = function () {
  57396. if (_this._texture == null) {
  57397. return;
  57398. }
  57399. _this._texture.dispose();
  57400. _this._texture = null;
  57401. };
  57402. _this._updateInternalTexture = function (e) {
  57403. if (_this._texture == null || !_this._texture.isReady) {
  57404. return;
  57405. }
  57406. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57407. return;
  57408. }
  57409. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57410. };
  57411. _this._engine = _this.getScene().getEngine();
  57412. _this._generateMipMaps = generateMipMaps;
  57413. _this._samplingMode = samplingMode;
  57414. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57415. _this.name = name || _this._getName(src);
  57416. _this.video = _this._getVideo(src);
  57417. if (settings.autoPlay !== undefined) {
  57418. _this.video.autoplay = settings.autoPlay;
  57419. }
  57420. if (settings.loop !== undefined) {
  57421. _this.video.loop = settings.loop;
  57422. }
  57423. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57424. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57425. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57426. _this.video.addEventListener("emptied", _this.reset);
  57427. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57428. _this._createInternalTexture();
  57429. }
  57430. return _this;
  57431. }
  57432. VideoTexture.prototype._getName = function (src) {
  57433. if (src instanceof HTMLVideoElement) {
  57434. return src.currentSrc;
  57435. }
  57436. if (typeof src === "object") {
  57437. return src.toString();
  57438. }
  57439. return src;
  57440. };
  57441. ;
  57442. VideoTexture.prototype._getVideo = function (src) {
  57443. if (src instanceof HTMLVideoElement) {
  57444. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57445. return src;
  57446. }
  57447. var video = document.createElement("video");
  57448. if (typeof src === "string") {
  57449. BABYLON.Tools.SetCorsBehavior(src, video);
  57450. video.src = src;
  57451. }
  57452. else {
  57453. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57454. src.forEach(function (url) {
  57455. var source = document.createElement("source");
  57456. source.src = url;
  57457. video.appendChild(source);
  57458. });
  57459. }
  57460. return video;
  57461. };
  57462. ;
  57463. /**
  57464. * Internal method to initiate `update`.
  57465. */
  57466. VideoTexture.prototype._rebuild = function () {
  57467. this.update();
  57468. };
  57469. /**
  57470. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57471. */
  57472. VideoTexture.prototype.update = function () {
  57473. if (!this.autoUpdateTexture) {
  57474. // Expecting user to call `updateTexture` manually
  57475. return;
  57476. }
  57477. this.updateTexture(true);
  57478. };
  57479. /**
  57480. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57481. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57482. */
  57483. VideoTexture.prototype.updateTexture = function (isVisible) {
  57484. if (!isVisible) {
  57485. return;
  57486. }
  57487. if (this.video.paused) {
  57488. return;
  57489. }
  57490. this._updateInternalTexture();
  57491. };
  57492. /**
  57493. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57494. * @param url New url.
  57495. */
  57496. VideoTexture.prototype.updateURL = function (url) {
  57497. this.video.src = url;
  57498. };
  57499. VideoTexture.prototype.dispose = function () {
  57500. _super.prototype.dispose.call(this);
  57501. this.video.removeEventListener("canplay", this._createInternalTexture);
  57502. this.video.removeEventListener("paused", this._updateInternalTexture);
  57503. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57504. this.video.removeEventListener("emptied", this.reset);
  57505. };
  57506. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57507. var video = document.createElement("video");
  57508. var constraintsDeviceId;
  57509. if (constraints && constraints.deviceId) {
  57510. constraintsDeviceId = {
  57511. exact: constraints.deviceId,
  57512. };
  57513. }
  57514. navigator.getUserMedia =
  57515. navigator.getUserMedia ||
  57516. navigator.webkitGetUserMedia ||
  57517. navigator.mozGetUserMedia ||
  57518. navigator.msGetUserMedia;
  57519. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57520. if (navigator.getUserMedia) {
  57521. navigator.getUserMedia({
  57522. video: {
  57523. deviceId: constraintsDeviceId,
  57524. width: {
  57525. min: (constraints && constraints.minWidth) || 256,
  57526. max: (constraints && constraints.maxWidth) || 640,
  57527. },
  57528. height: {
  57529. min: (constraints && constraints.minHeight) || 256,
  57530. max: (constraints && constraints.maxHeight) || 480,
  57531. },
  57532. },
  57533. }, function (stream) {
  57534. if (video.mozSrcObject !== undefined) {
  57535. // hack for Firefox < 19
  57536. video.mozSrcObject = stream;
  57537. }
  57538. else {
  57539. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57540. }
  57541. video.play();
  57542. if (onReady) {
  57543. onReady(new VideoTexture("video", video, scene, true, true));
  57544. }
  57545. }, function (e) {
  57546. BABYLON.Tools.Error(e.name);
  57547. });
  57548. }
  57549. };
  57550. return VideoTexture;
  57551. }(BABYLON.Texture));
  57552. BABYLON.VideoTexture = VideoTexture;
  57553. })(BABYLON || (BABYLON = {}));
  57554. //# sourceMappingURL=babylon.videoTexture.js.map
  57555. var BABYLON;
  57556. (function (BABYLON) {
  57557. var RawTexture = /** @class */ (function (_super) {
  57558. __extends(RawTexture, _super);
  57559. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57560. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57561. if (invertY === void 0) { invertY = false; }
  57562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57563. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57564. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57565. _this.format = format;
  57566. _this._engine = scene.getEngine();
  57567. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57568. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57569. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57570. return _this;
  57571. }
  57572. RawTexture.prototype.update = function (data) {
  57573. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57574. };
  57575. // Statics
  57576. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57577. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57578. if (invertY === void 0) { invertY = false; }
  57579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57580. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57581. };
  57582. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57583. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57584. if (invertY === void 0) { invertY = false; }
  57585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57586. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57587. };
  57588. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57589. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57590. if (invertY === void 0) { invertY = false; }
  57591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57592. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57593. };
  57594. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57595. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57596. if (invertY === void 0) { invertY = false; }
  57597. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57598. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57600. };
  57601. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57603. if (invertY === void 0) { invertY = false; }
  57604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57605. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57606. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57607. };
  57608. return RawTexture;
  57609. }(BABYLON.Texture));
  57610. BABYLON.RawTexture = RawTexture;
  57611. })(BABYLON || (BABYLON = {}));
  57612. //# sourceMappingURL=babylon.rawTexture.js.map
  57613. var BABYLON;
  57614. (function (BABYLON) {
  57615. /**
  57616. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57617. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57618. */
  57619. var PostProcess = /** @class */ (function () {
  57620. /**
  57621. * Creates a new instance of @see PostProcess
  57622. * @param name The name of the PostProcess.
  57623. * @param fragmentUrl The url of the fragment shader to be used.
  57624. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57625. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57626. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57627. * @param camera The camera to apply the render pass to.
  57628. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57629. * @param engine The engine which the post process will be applied. (default: current engine)
  57630. * @param reusable If the post process can be reused on the same frame. (default: false)
  57631. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57632. * @param textureType Type of textures used when performing the post process. (default: 0)
  57633. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57634. * @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
  57635. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57636. */
  57637. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57639. if (defines === void 0) { defines = null; }
  57640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57641. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57642. if (blockCompilation === void 0) { blockCompilation = false; }
  57643. this.name = name;
  57644. /**
  57645. * Width of the texture to apply the post process on
  57646. */
  57647. this.width = -1;
  57648. /**
  57649. * Height of the texture to apply the post process on
  57650. */
  57651. this.height = -1;
  57652. /**
  57653. * If the buffer needs to be cleared before applying the post process. (default: true)
  57654. * Should be set to false if shader will overwrite all previous pixels.
  57655. */
  57656. this.autoClear = true;
  57657. /**
  57658. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57659. */
  57660. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57661. /**
  57662. * Animations to be used for the post processing
  57663. */
  57664. this.animations = new Array();
  57665. /**
  57666. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57667. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57668. */
  57669. this.enablePixelPerfectMode = false;
  57670. /**
  57671. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57672. */
  57673. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57674. /**
  57675. * Force textures to be a power of two (default: false)
  57676. */
  57677. this.alwaysForcePOT = false;
  57678. /**
  57679. * Number of sample textures (default: 1)
  57680. */
  57681. this.samples = 1;
  57682. /**
  57683. * Modify the scale of the post process to be the same as the viewport (default: false)
  57684. */
  57685. this.adaptScaleToCurrentViewport = false;
  57686. this._reusable = false;
  57687. /**
  57688. * Smart array of input and output textures for the post process.
  57689. */
  57690. this._textures = new BABYLON.SmartArray(2);
  57691. /**
  57692. * The index in _textures that corresponds to the output texture.
  57693. */
  57694. this._currentRenderTextureInd = 0;
  57695. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57696. this._texelSize = BABYLON.Vector2.Zero();
  57697. // Events
  57698. /**
  57699. * An event triggered when the postprocess is activated.
  57700. * @type {BABYLON.Observable}
  57701. */
  57702. this.onActivateObservable = new BABYLON.Observable();
  57703. /**
  57704. * An event triggered when the postprocess changes its size.
  57705. * @type {BABYLON.Observable}
  57706. */
  57707. this.onSizeChangedObservable = new BABYLON.Observable();
  57708. /**
  57709. * An event triggered when the postprocess applies its effect.
  57710. * @type {BABYLON.Observable}
  57711. */
  57712. this.onApplyObservable = new BABYLON.Observable();
  57713. /**
  57714. * An event triggered before rendering the postprocess
  57715. * @type {BABYLON.Observable}
  57716. */
  57717. this.onBeforeRenderObservable = new BABYLON.Observable();
  57718. /**
  57719. * An event triggered after rendering the postprocess
  57720. * @type {BABYLON.Observable}
  57721. */
  57722. this.onAfterRenderObservable = new BABYLON.Observable();
  57723. if (camera != null) {
  57724. this._camera = camera;
  57725. this._scene = camera.getScene();
  57726. camera.attachPostProcess(this);
  57727. this._engine = this._scene.getEngine();
  57728. this._scene.postProcesses.push(this);
  57729. }
  57730. else if (engine) {
  57731. this._engine = engine;
  57732. this._engine.postProcesses.push(this);
  57733. }
  57734. this._options = options;
  57735. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57736. this._reusable = reusable || false;
  57737. this._textureType = textureType;
  57738. this._samplers = samplers || [];
  57739. this._samplers.push("textureSampler");
  57740. this._fragmentUrl = fragmentUrl;
  57741. this._vertexUrl = vertexUrl;
  57742. this._parameters = parameters || [];
  57743. this._parameters.push("scale");
  57744. this._indexParameters = indexParameters;
  57745. if (!blockCompilation) {
  57746. this.updateEffect(defines);
  57747. }
  57748. }
  57749. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57750. /**
  57751. * A function that is added to the onActivateObservable
  57752. */
  57753. set: function (callback) {
  57754. if (this._onActivateObserver) {
  57755. this.onActivateObservable.remove(this._onActivateObserver);
  57756. }
  57757. if (callback) {
  57758. this._onActivateObserver = this.onActivateObservable.add(callback);
  57759. }
  57760. },
  57761. enumerable: true,
  57762. configurable: true
  57763. });
  57764. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57765. /**
  57766. * A function that is added to the onSizeChangedObservable
  57767. */
  57768. set: function (callback) {
  57769. if (this._onSizeChangedObserver) {
  57770. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57771. }
  57772. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57773. },
  57774. enumerable: true,
  57775. configurable: true
  57776. });
  57777. Object.defineProperty(PostProcess.prototype, "onApply", {
  57778. /**
  57779. * A function that is added to the onApplyObservable
  57780. */
  57781. set: function (callback) {
  57782. if (this._onApplyObserver) {
  57783. this.onApplyObservable.remove(this._onApplyObserver);
  57784. }
  57785. this._onApplyObserver = this.onApplyObservable.add(callback);
  57786. },
  57787. enumerable: true,
  57788. configurable: true
  57789. });
  57790. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57791. /**
  57792. * A function that is added to the onBeforeRenderObservable
  57793. */
  57794. set: function (callback) {
  57795. if (this._onBeforeRenderObserver) {
  57796. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57797. }
  57798. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57799. },
  57800. enumerable: true,
  57801. configurable: true
  57802. });
  57803. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57804. /**
  57805. * A function that is added to the onAfterRenderObservable
  57806. */
  57807. set: function (callback) {
  57808. if (this._onAfterRenderObserver) {
  57809. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57810. }
  57811. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57812. },
  57813. enumerable: true,
  57814. configurable: true
  57815. });
  57816. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57817. /**
  57818. * 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
  57819. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57820. */
  57821. get: function () {
  57822. return this._textures.data[this._currentRenderTextureInd];
  57823. },
  57824. set: function (value) {
  57825. this._forcedOutputTexture = value;
  57826. },
  57827. enumerable: true,
  57828. configurable: true
  57829. });
  57830. /**
  57831. * Gets the camera which post process is applied to.
  57832. * @returns The camera the post process is applied to.
  57833. */
  57834. PostProcess.prototype.getCamera = function () {
  57835. return this._camera;
  57836. };
  57837. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57838. /**
  57839. * Gets the texel size of the postprocess.
  57840. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57841. */
  57842. get: function () {
  57843. if (this._shareOutputWithPostProcess) {
  57844. return this._shareOutputWithPostProcess.texelSize;
  57845. }
  57846. if (this._forcedOutputTexture) {
  57847. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57848. }
  57849. return this._texelSize;
  57850. },
  57851. enumerable: true,
  57852. configurable: true
  57853. });
  57854. /**
  57855. * Gets the engine which this post process belongs to.
  57856. * @returns The engine the post process was enabled with.
  57857. */
  57858. PostProcess.prototype.getEngine = function () {
  57859. return this._engine;
  57860. };
  57861. /**
  57862. * The effect that is created when initializing the post process.
  57863. * @returns The created effect corrisponding the the postprocess.
  57864. */
  57865. PostProcess.prototype.getEffect = function () {
  57866. return this._effect;
  57867. };
  57868. /**
  57869. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57870. * @param postProcess The post process to share the output with.
  57871. * @returns This post process.
  57872. */
  57873. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57874. this._disposeTextures();
  57875. this._shareOutputWithPostProcess = postProcess;
  57876. return this;
  57877. };
  57878. /**
  57879. * Updates the effect with the current post process compile time values and recompiles the shader.
  57880. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57881. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57882. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57883. * @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
  57884. * @param onCompiled Called when the shader has been compiled.
  57885. * @param onError Called if there is an error when compiling a shader.
  57886. */
  57887. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57888. if (defines === void 0) { defines = null; }
  57889. if (uniforms === void 0) { uniforms = null; }
  57890. if (samplers === void 0) { samplers = null; }
  57891. 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);
  57892. };
  57893. /**
  57894. * The post process is reusable if it can be used multiple times within one frame.
  57895. * @returns If the post process is reusable
  57896. */
  57897. PostProcess.prototype.isReusable = function () {
  57898. return this._reusable;
  57899. };
  57900. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57901. PostProcess.prototype.markTextureDirty = function () {
  57902. this.width = -1;
  57903. };
  57904. /**
  57905. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57906. * 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.
  57907. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57908. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57909. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57910. */
  57911. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57912. var _this = this;
  57913. if (sourceTexture === void 0) { sourceTexture = null; }
  57914. camera = camera || this._camera;
  57915. var scene = camera.getScene();
  57916. var engine = scene.getEngine();
  57917. var maxSize = engine.getCaps().maxTextureSize;
  57918. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57919. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57920. var desiredWidth = (this._options.width || requiredWidth);
  57921. var desiredHeight = this._options.height || requiredHeight;
  57922. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57923. if (this.adaptScaleToCurrentViewport) {
  57924. var currentViewport = engine.currentViewport;
  57925. if (currentViewport) {
  57926. desiredWidth *= currentViewport.width;
  57927. desiredHeight *= currentViewport.height;
  57928. }
  57929. }
  57930. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57931. if (!this._options.width) {
  57932. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57933. }
  57934. if (!this._options.height) {
  57935. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57936. }
  57937. }
  57938. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57939. if (this._textures.length > 0) {
  57940. for (var i = 0; i < this._textures.length; i++) {
  57941. this._engine._releaseTexture(this._textures.data[i]);
  57942. }
  57943. this._textures.reset();
  57944. }
  57945. this.width = desiredWidth;
  57946. this.height = desiredHeight;
  57947. var textureSize = { width: this.width, height: this.height };
  57948. var textureOptions = {
  57949. generateMipMaps: false,
  57950. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57951. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57952. samplingMode: this.renderTargetSamplingMode,
  57953. type: this._textureType
  57954. };
  57955. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57956. if (this._reusable) {
  57957. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57958. }
  57959. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57960. this.onSizeChangedObservable.notifyObservers(this);
  57961. }
  57962. this._textures.forEach(function (texture) {
  57963. if (texture.samples !== _this.samples) {
  57964. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57965. }
  57966. });
  57967. }
  57968. var target;
  57969. if (this._shareOutputWithPostProcess) {
  57970. target = this._shareOutputWithPostProcess.inputTexture;
  57971. }
  57972. else if (this._forcedOutputTexture) {
  57973. target = this._forcedOutputTexture;
  57974. this.width = this._forcedOutputTexture.width;
  57975. this.height = this._forcedOutputTexture.height;
  57976. }
  57977. else {
  57978. target = this.inputTexture;
  57979. }
  57980. // Bind the input of this post process to be used as the output of the previous post process.
  57981. if (this.enablePixelPerfectMode) {
  57982. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57983. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57984. }
  57985. else {
  57986. this._scaleRatio.copyFromFloats(1, 1);
  57987. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57988. }
  57989. this.onActivateObservable.notifyObservers(camera);
  57990. // Clear
  57991. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57992. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57993. }
  57994. if (this._reusable) {
  57995. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57996. }
  57997. };
  57998. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57999. /**
  58000. * If the post process is supported.
  58001. */
  58002. get: function () {
  58003. return this._effect.isSupported;
  58004. },
  58005. enumerable: true,
  58006. configurable: true
  58007. });
  58008. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58009. /**
  58010. * The aspect ratio of the output texture.
  58011. */
  58012. get: function () {
  58013. if (this._shareOutputWithPostProcess) {
  58014. return this._shareOutputWithPostProcess.aspectRatio;
  58015. }
  58016. if (this._forcedOutputTexture) {
  58017. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58018. }
  58019. return this.width / this.height;
  58020. },
  58021. enumerable: true,
  58022. configurable: true
  58023. });
  58024. /**
  58025. * Get a value indicating if the post-process is ready to be used
  58026. * @returns true if the post-process is ready (shader is compiled)
  58027. */
  58028. PostProcess.prototype.isReady = function () {
  58029. return this._effect && this._effect.isReady();
  58030. };
  58031. /**
  58032. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58033. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58034. */
  58035. PostProcess.prototype.apply = function () {
  58036. // Check
  58037. if (!this._effect || !this._effect.isReady())
  58038. return null;
  58039. // States
  58040. this._engine.enableEffect(this._effect);
  58041. this._engine.setState(false);
  58042. this._engine.setDepthBuffer(false);
  58043. this._engine.setDepthWrite(false);
  58044. // Alpha
  58045. this._engine.setAlphaMode(this.alphaMode);
  58046. if (this.alphaConstants) {
  58047. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58048. }
  58049. // Bind the output texture of the preivous post process as the input to this post process.
  58050. var source;
  58051. if (this._shareOutputWithPostProcess) {
  58052. source = this._shareOutputWithPostProcess.inputTexture;
  58053. }
  58054. else if (this._forcedOutputTexture) {
  58055. source = this._forcedOutputTexture;
  58056. }
  58057. else {
  58058. source = this.inputTexture;
  58059. }
  58060. this._effect._bindTexture("textureSampler", source);
  58061. // Parameters
  58062. this._effect.setVector2("scale", this._scaleRatio);
  58063. this.onApplyObservable.notifyObservers(this._effect);
  58064. return this._effect;
  58065. };
  58066. PostProcess.prototype._disposeTextures = function () {
  58067. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58068. return;
  58069. }
  58070. if (this._textures.length > 0) {
  58071. for (var i = 0; i < this._textures.length; i++) {
  58072. this._engine._releaseTexture(this._textures.data[i]);
  58073. }
  58074. }
  58075. this._textures.dispose();
  58076. };
  58077. /**
  58078. * Disposes the post process.
  58079. * @param camera The camera to dispose the post process on.
  58080. */
  58081. PostProcess.prototype.dispose = function (camera) {
  58082. camera = camera || this._camera;
  58083. this._disposeTextures();
  58084. if (this._scene) {
  58085. var index_1 = this._scene.postProcesses.indexOf(this);
  58086. if (index_1 !== -1) {
  58087. this._scene.postProcesses.splice(index_1, 1);
  58088. }
  58089. }
  58090. else {
  58091. var index_2 = this._engine.postProcesses.indexOf(this);
  58092. if (index_2 !== -1) {
  58093. this._engine.postProcesses.splice(index_2, 1);
  58094. }
  58095. }
  58096. if (!camera) {
  58097. return;
  58098. }
  58099. camera.detachPostProcess(this);
  58100. var index = camera._postProcesses.indexOf(this);
  58101. if (index === 0 && camera._postProcesses.length > 0) {
  58102. this._camera._postProcesses[0].markTextureDirty();
  58103. }
  58104. this.onActivateObservable.clear();
  58105. this.onAfterRenderObservable.clear();
  58106. this.onApplyObservable.clear();
  58107. this.onBeforeRenderObservable.clear();
  58108. this.onSizeChangedObservable.clear();
  58109. };
  58110. return PostProcess;
  58111. }());
  58112. BABYLON.PostProcess = PostProcess;
  58113. })(BABYLON || (BABYLON = {}));
  58114. //# sourceMappingURL=babylon.postProcess.js.map
  58115. var BABYLON;
  58116. (function (BABYLON) {
  58117. var PassPostProcess = /** @class */ (function (_super) {
  58118. __extends(PassPostProcess, _super);
  58119. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58120. if (camera === void 0) { camera = null; }
  58121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58122. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58123. }
  58124. return PassPostProcess;
  58125. }(BABYLON.PostProcess));
  58126. BABYLON.PassPostProcess = PassPostProcess;
  58127. })(BABYLON || (BABYLON = {}));
  58128. //# sourceMappingURL=babylon.passPostProcess.js.map
  58129. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58130. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58131. s = arguments[i];
  58132. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58133. t[p] = s[p];
  58134. }
  58135. return t;
  58136. };
  58137. var BABYLON;
  58138. (function (BABYLON) {
  58139. /**
  58140. * Default implementation of @see IShadowGenerator.
  58141. * This is the main object responsible of generating shadows in the framework.
  58142. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58143. */
  58144. var ShadowGenerator = /** @class */ (function () {
  58145. /**
  58146. * Creates a ShadowGenerator object.
  58147. * A ShadowGenerator is the required tool to use the shadows.
  58148. * Each light casting shadows needs to use its own ShadowGenerator.
  58149. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58150. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58151. * @param light The light object generating the shadows.
  58152. * @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.
  58153. */
  58154. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58155. this._bias = 0.00005;
  58156. this._blurBoxOffset = 1;
  58157. this._blurScale = 2;
  58158. this._blurKernel = 1;
  58159. this._useKernelBlur = false;
  58160. this._filter = ShadowGenerator.FILTER_NONE;
  58161. this._darkness = 0;
  58162. this._transparencyShadow = false;
  58163. /**
  58164. * Controls the extent to which the shadows fade out at the edge of the frustum
  58165. * Used only by directionals and spots
  58166. */
  58167. this.frustumEdgeFalloff = 0;
  58168. /**
  58169. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58170. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58171. * It might on the other hand introduce peter panning.
  58172. */
  58173. this.forceBackFacesOnly = false;
  58174. this._lightDirection = BABYLON.Vector3.Zero();
  58175. this._viewMatrix = BABYLON.Matrix.Zero();
  58176. this._projectionMatrix = BABYLON.Matrix.Zero();
  58177. this._transformMatrix = BABYLON.Matrix.Zero();
  58178. this._currentFaceIndex = 0;
  58179. this._currentFaceIndexCache = 0;
  58180. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58181. this._mapSize = mapSize;
  58182. this._light = light;
  58183. this._scene = light.getScene();
  58184. light._shadowGenerator = this;
  58185. // Texture type fallback from float to int if not supported.
  58186. var caps = this._scene.getEngine().getCaps();
  58187. if (!useFullFloatFirst) {
  58188. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58189. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58190. }
  58191. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58192. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58193. }
  58194. else {
  58195. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58196. }
  58197. }
  58198. else {
  58199. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58200. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58201. }
  58202. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58203. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58204. }
  58205. else {
  58206. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58207. }
  58208. }
  58209. this._initializeGenerator();
  58210. }
  58211. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58212. /**
  58213. * Shadow generator mode None: no filtering applied.
  58214. */
  58215. get: function () {
  58216. return ShadowGenerator._FILTER_NONE;
  58217. },
  58218. enumerable: true,
  58219. configurable: true
  58220. });
  58221. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58222. /**
  58223. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58224. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58225. */
  58226. get: function () {
  58227. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58228. },
  58229. enumerable: true,
  58230. configurable: true
  58231. });
  58232. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58233. /**
  58234. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58235. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58236. */
  58237. get: function () {
  58238. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58239. },
  58240. enumerable: true,
  58241. configurable: true
  58242. });
  58243. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58244. /**
  58245. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58246. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58247. */
  58248. get: function () {
  58249. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58250. },
  58251. enumerable: true,
  58252. configurable: true
  58253. });
  58254. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58255. /**
  58256. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58257. * edge artifacts on steep falloff.
  58258. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58259. */
  58260. get: function () {
  58261. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58262. },
  58263. enumerable: true,
  58264. configurable: true
  58265. });
  58266. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58267. /**
  58268. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58269. * edge artifacts on steep falloff.
  58270. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58271. */
  58272. get: function () {
  58273. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58274. },
  58275. enumerable: true,
  58276. configurable: true
  58277. });
  58278. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58279. /**
  58280. * Gets the bias: offset applied on the depth preventing acnea.
  58281. */
  58282. get: function () {
  58283. return this._bias;
  58284. },
  58285. /**
  58286. * Sets the bias: offset applied on the depth preventing acnea.
  58287. */
  58288. set: function (bias) {
  58289. this._bias = bias;
  58290. },
  58291. enumerable: true,
  58292. configurable: true
  58293. });
  58294. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58295. /**
  58296. * Gets the blur box offset: offset applied during the blur pass.
  58297. * Only usefull if useKernelBlur = false
  58298. */
  58299. get: function () {
  58300. return this._blurBoxOffset;
  58301. },
  58302. /**
  58303. * Sets the blur box offset: offset applied during the blur pass.
  58304. * Only usefull if useKernelBlur = false
  58305. */
  58306. set: function (value) {
  58307. if (this._blurBoxOffset === value) {
  58308. return;
  58309. }
  58310. this._blurBoxOffset = value;
  58311. this._disposeBlurPostProcesses();
  58312. },
  58313. enumerable: true,
  58314. configurable: true
  58315. });
  58316. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58317. /**
  58318. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58319. * 2 means half of the size.
  58320. */
  58321. get: function () {
  58322. return this._blurScale;
  58323. },
  58324. /**
  58325. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58326. * 2 means half of the size.
  58327. */
  58328. set: function (value) {
  58329. if (this._blurScale === value) {
  58330. return;
  58331. }
  58332. this._blurScale = value;
  58333. this._disposeBlurPostProcesses();
  58334. },
  58335. enumerable: true,
  58336. configurable: true
  58337. });
  58338. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58339. /**
  58340. * Gets the blur kernel: kernel size of the blur pass.
  58341. * Only usefull if useKernelBlur = true
  58342. */
  58343. get: function () {
  58344. return this._blurKernel;
  58345. },
  58346. /**
  58347. * Sets the blur kernel: kernel size of the blur pass.
  58348. * Only usefull if useKernelBlur = true
  58349. */
  58350. set: function (value) {
  58351. if (this._blurKernel === value) {
  58352. return;
  58353. }
  58354. this._blurKernel = value;
  58355. this._disposeBlurPostProcesses();
  58356. },
  58357. enumerable: true,
  58358. configurable: true
  58359. });
  58360. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58361. /**
  58362. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58363. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58364. */
  58365. get: function () {
  58366. return this._useKernelBlur;
  58367. },
  58368. /**
  58369. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58370. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58371. */
  58372. set: function (value) {
  58373. if (this._useKernelBlur === value) {
  58374. return;
  58375. }
  58376. this._useKernelBlur = value;
  58377. this._disposeBlurPostProcesses();
  58378. },
  58379. enumerable: true,
  58380. configurable: true
  58381. });
  58382. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58383. /**
  58384. * Gets the depth scale used in ESM mode.
  58385. */
  58386. get: function () {
  58387. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58388. },
  58389. /**
  58390. * Sets the depth scale used in ESM mode.
  58391. * This can override the scale stored on the light.
  58392. */
  58393. set: function (value) {
  58394. this._depthScale = value;
  58395. },
  58396. enumerable: true,
  58397. configurable: true
  58398. });
  58399. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58400. /**
  58401. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58402. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58403. */
  58404. get: function () {
  58405. return this._filter;
  58406. },
  58407. /**
  58408. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58409. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58410. */
  58411. set: function (value) {
  58412. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58413. if (this._light.needCube()) {
  58414. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58415. this.useExponentialShadowMap = true;
  58416. return;
  58417. }
  58418. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58419. this.useCloseExponentialShadowMap = true;
  58420. return;
  58421. }
  58422. }
  58423. if (this._filter === value) {
  58424. return;
  58425. }
  58426. this._filter = value;
  58427. this._disposeBlurPostProcesses();
  58428. this._applyFilterValues();
  58429. this._light._markMeshesAsLightDirty();
  58430. },
  58431. enumerable: true,
  58432. configurable: true
  58433. });
  58434. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58435. /**
  58436. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58437. */
  58438. get: function () {
  58439. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58440. },
  58441. /**
  58442. * Sets the current filter to Poisson Sampling aka PCF.
  58443. */
  58444. set: function (value) {
  58445. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58446. return;
  58447. }
  58448. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58449. },
  58450. enumerable: true,
  58451. configurable: true
  58452. });
  58453. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58454. /**
  58455. * Gets if the current filter is set to VSM.
  58456. * DEPRECATED. Should use useExponentialShadowMap instead.
  58457. */
  58458. get: function () {
  58459. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58460. return this.useExponentialShadowMap;
  58461. },
  58462. /**
  58463. * Sets the current filter is to VSM.
  58464. * DEPRECATED. Should use useExponentialShadowMap instead.
  58465. */
  58466. set: function (value) {
  58467. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58468. this.useExponentialShadowMap = value;
  58469. },
  58470. enumerable: true,
  58471. configurable: true
  58472. });
  58473. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58474. /**
  58475. * Gets if the current filter is set to blurred VSM.
  58476. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58477. */
  58478. get: function () {
  58479. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58480. return this.useBlurExponentialShadowMap;
  58481. },
  58482. /**
  58483. * Sets the current filter is to blurred VSM.
  58484. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58485. */
  58486. set: function (value) {
  58487. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58488. this.useBlurExponentialShadowMap = value;
  58489. },
  58490. enumerable: true,
  58491. configurable: true
  58492. });
  58493. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58494. /**
  58495. * Gets if the current filter is set to ESM.
  58496. */
  58497. get: function () {
  58498. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58499. },
  58500. /**
  58501. * Sets the current filter is to ESM.
  58502. */
  58503. set: function (value) {
  58504. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58505. return;
  58506. }
  58507. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58508. },
  58509. enumerable: true,
  58510. configurable: true
  58511. });
  58512. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58513. /**
  58514. * Gets if the current filter is set to filtered ESM.
  58515. */
  58516. get: function () {
  58517. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58518. },
  58519. /**
  58520. * Gets if the current filter is set to filtered ESM.
  58521. */
  58522. set: function (value) {
  58523. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58524. return;
  58525. }
  58526. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58527. },
  58528. enumerable: true,
  58529. configurable: true
  58530. });
  58531. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58532. /**
  58533. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58534. * exponential to prevent steep falloff artifacts).
  58535. */
  58536. get: function () {
  58537. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58538. },
  58539. /**
  58540. * Sets the current filter to "close ESM" (using the inverse of the
  58541. * exponential to prevent steep falloff artifacts).
  58542. */
  58543. set: function (value) {
  58544. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58545. return;
  58546. }
  58547. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58548. },
  58549. enumerable: true,
  58550. configurable: true
  58551. });
  58552. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58553. /**
  58554. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58555. * exponential to prevent steep falloff artifacts).
  58556. */
  58557. get: function () {
  58558. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58559. },
  58560. /**
  58561. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58562. * exponential to prevent steep falloff artifacts).
  58563. */
  58564. set: function (value) {
  58565. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58566. return;
  58567. }
  58568. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58569. },
  58570. enumerable: true,
  58571. configurable: true
  58572. });
  58573. /**
  58574. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58575. * 0 means strongest and 1 would means no shadow.
  58576. * @returns the darkness.
  58577. */
  58578. ShadowGenerator.prototype.getDarkness = function () {
  58579. return this._darkness;
  58580. };
  58581. /**
  58582. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58583. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58584. * @returns the shadow generator allowing fluent coding.
  58585. */
  58586. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58587. if (darkness >= 1.0)
  58588. this._darkness = 1.0;
  58589. else if (darkness <= 0.0)
  58590. this._darkness = 0.0;
  58591. else
  58592. this._darkness = darkness;
  58593. return this;
  58594. };
  58595. /**
  58596. * Sets the ability to have transparent shadow (boolean).
  58597. * @param transparent True if transparent else False
  58598. * @returns the shadow generator allowing fluent coding
  58599. */
  58600. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58601. this._transparencyShadow = transparent;
  58602. return this;
  58603. };
  58604. /**
  58605. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58606. * @returns The render target texture if present otherwise, null
  58607. */
  58608. ShadowGenerator.prototype.getShadowMap = function () {
  58609. return this._shadowMap;
  58610. };
  58611. /**
  58612. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58613. * @returns The render target texture if the shadow map is present otherwise, null
  58614. */
  58615. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58616. if (this._shadowMap2) {
  58617. return this._shadowMap2;
  58618. }
  58619. return this._shadowMap;
  58620. };
  58621. /**
  58622. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58623. * @param mesh Mesh to add
  58624. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58625. * @returns the Shadow Generator itself
  58626. */
  58627. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58628. if (includeDescendants === void 0) { includeDescendants = true; }
  58629. if (!this._shadowMap) {
  58630. return this;
  58631. }
  58632. if (!this._shadowMap.renderList) {
  58633. this._shadowMap.renderList = [];
  58634. }
  58635. this._shadowMap.renderList.push(mesh);
  58636. if (includeDescendants) {
  58637. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58638. }
  58639. return this;
  58640. var _a;
  58641. };
  58642. /**
  58643. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58644. * @param mesh Mesh to remove
  58645. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58646. * @returns the Shadow Generator itself
  58647. */
  58648. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58649. if (includeDescendants === void 0) { includeDescendants = true; }
  58650. if (!this._shadowMap || !this._shadowMap.renderList) {
  58651. return this;
  58652. }
  58653. var index = this._shadowMap.renderList.indexOf(mesh);
  58654. if (index !== -1) {
  58655. this._shadowMap.renderList.splice(index, 1);
  58656. }
  58657. if (includeDescendants) {
  58658. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58659. var child = _a[_i];
  58660. this.removeShadowCaster(child);
  58661. }
  58662. }
  58663. return this;
  58664. };
  58665. /**
  58666. * Returns the associated light object.
  58667. * @returns the light generating the shadow
  58668. */
  58669. ShadowGenerator.prototype.getLight = function () {
  58670. return this._light;
  58671. };
  58672. ShadowGenerator.prototype._initializeGenerator = function () {
  58673. this._light._markMeshesAsLightDirty();
  58674. this._initializeShadowMap();
  58675. };
  58676. ShadowGenerator.prototype._initializeShadowMap = function () {
  58677. var _this = this;
  58678. // Render target
  58679. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58680. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58681. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58682. this._shadowMap.anisotropicFilteringLevel = 1;
  58683. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58684. this._shadowMap.renderParticles = false;
  58685. this._shadowMap.ignoreCameraViewport = true;
  58686. // Record Face Index before render.
  58687. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58688. _this._currentFaceIndex = faceIndex;
  58689. });
  58690. // Custom render function.
  58691. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58692. // Blur if required afer render.
  58693. this._shadowMap.onAfterUnbindObservable.add(function () {
  58694. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58695. return;
  58696. }
  58697. var shadowMap = _this.getShadowMapForRendering();
  58698. if (shadowMap) {
  58699. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58700. }
  58701. });
  58702. // Clear according to the chosen filter.
  58703. this._shadowMap.onClearObservable.add(function (engine) {
  58704. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58705. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58706. }
  58707. else {
  58708. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58709. }
  58710. });
  58711. };
  58712. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58713. var _this = this;
  58714. var engine = this._scene.getEngine();
  58715. var targetSize = this._mapSize / this.blurScale;
  58716. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58717. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58718. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58719. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58720. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58721. }
  58722. if (this.useKernelBlur) {
  58723. 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);
  58724. this._kernelBlurXPostprocess.width = targetSize;
  58725. this._kernelBlurXPostprocess.height = targetSize;
  58726. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58727. effect.setTexture("textureSampler", _this._shadowMap);
  58728. });
  58729. 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);
  58730. this._kernelBlurXPostprocess.autoClear = false;
  58731. this._kernelBlurYPostprocess.autoClear = false;
  58732. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58733. this._kernelBlurXPostprocess.packedFloat = true;
  58734. this._kernelBlurYPostprocess.packedFloat = true;
  58735. }
  58736. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58737. }
  58738. else {
  58739. 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);
  58740. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58741. effect.setFloat2("screenSize", targetSize, targetSize);
  58742. effect.setTexture("textureSampler", _this._shadowMap);
  58743. });
  58744. this._boxBlurPostprocess.autoClear = false;
  58745. this._blurPostProcesses = [this._boxBlurPostprocess];
  58746. }
  58747. };
  58748. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58749. var index;
  58750. var engine = this._scene.getEngine();
  58751. if (depthOnlySubMeshes.length) {
  58752. engine.setColorWrite(false);
  58753. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58754. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58755. }
  58756. engine.setColorWrite(true);
  58757. }
  58758. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58759. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58760. }
  58761. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58762. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58763. }
  58764. if (this._transparencyShadow) {
  58765. for (index = 0; index < transparentSubMeshes.length; index++) {
  58766. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58767. }
  58768. }
  58769. };
  58770. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58771. var _this = this;
  58772. var mesh = subMesh.getRenderingMesh();
  58773. var scene = this._scene;
  58774. var engine = scene.getEngine();
  58775. var material = subMesh.getMaterial();
  58776. if (!material) {
  58777. return;
  58778. }
  58779. // Culling
  58780. engine.setState(material.backFaceCulling);
  58781. // Managing instances
  58782. var batch = mesh._getInstancesRenderList(subMesh._id);
  58783. if (batch.mustReturn) {
  58784. return;
  58785. }
  58786. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58787. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58788. engine.enableEffect(this._effect);
  58789. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58790. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58791. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58792. this._effect.setVector3("lightPosition", this.getLight().position);
  58793. if (scene.activeCamera) {
  58794. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58795. }
  58796. // Alpha test
  58797. if (material && material.needAlphaTesting()) {
  58798. var alphaTexture = material.getAlphaTestTexture();
  58799. if (alphaTexture) {
  58800. this._effect.setTexture("diffuseSampler", alphaTexture);
  58801. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58802. }
  58803. }
  58804. // Bones
  58805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58806. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58807. }
  58808. if (this.forceBackFacesOnly) {
  58809. engine.setState(true, 0, false, true);
  58810. }
  58811. // Draw
  58812. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58813. if (this.forceBackFacesOnly) {
  58814. engine.setState(true, 0, false, false);
  58815. }
  58816. }
  58817. else {
  58818. // Need to reset refresh rate of the shadowMap
  58819. if (this._shadowMap) {
  58820. this._shadowMap.resetRefreshCounter();
  58821. }
  58822. }
  58823. };
  58824. ShadowGenerator.prototype._applyFilterValues = function () {
  58825. if (!this._shadowMap) {
  58826. return;
  58827. }
  58828. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58829. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58830. }
  58831. else {
  58832. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58833. }
  58834. };
  58835. /**
  58836. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58837. * @param onCompiled Callback triggered at the and of the effects compilation
  58838. * @param options Sets of optional options forcing the compilation with different modes
  58839. */
  58840. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58841. var _this = this;
  58842. var localOptions = __assign({ useInstances: false }, options);
  58843. var shadowMap = this.getShadowMap();
  58844. if (!shadowMap) {
  58845. if (onCompiled) {
  58846. onCompiled(this);
  58847. }
  58848. return;
  58849. }
  58850. var renderList = shadowMap.renderList;
  58851. if (!renderList) {
  58852. if (onCompiled) {
  58853. onCompiled(this);
  58854. }
  58855. return;
  58856. }
  58857. var subMeshes = new Array();
  58858. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58859. var mesh = renderList_1[_i];
  58860. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58861. }
  58862. if (subMeshes.length === 0) {
  58863. if (onCompiled) {
  58864. onCompiled(this);
  58865. }
  58866. return;
  58867. }
  58868. var currentIndex = 0;
  58869. var checkReady = function () {
  58870. if (!_this._scene || !_this._scene.getEngine()) {
  58871. return;
  58872. }
  58873. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58874. currentIndex++;
  58875. if (currentIndex >= subMeshes.length) {
  58876. if (onCompiled) {
  58877. onCompiled(_this);
  58878. }
  58879. return;
  58880. }
  58881. }
  58882. setTimeout(checkReady, 16);
  58883. };
  58884. checkReady();
  58885. };
  58886. /**
  58887. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58888. * @param options Sets of optional options forcing the compilation with different modes
  58889. * @returns A promise that resolves when the compilation completes
  58890. */
  58891. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58892. var _this = this;
  58893. return new Promise(function (resolve) {
  58894. _this.forceCompilation(function () {
  58895. resolve();
  58896. }, options);
  58897. });
  58898. };
  58899. /**
  58900. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58901. * @param subMesh The submesh we want to render in the shadow map
  58902. * @param useInstances Defines wether will draw in the map using instances
  58903. * @returns true if ready otherwise, false
  58904. */
  58905. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58906. var defines = [];
  58907. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58908. defines.push("#define FLOAT");
  58909. }
  58910. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58911. defines.push("#define ESM");
  58912. }
  58913. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58914. var mesh = subMesh.getMesh();
  58915. var material = subMesh.getMaterial();
  58916. // Alpha test
  58917. if (material && material.needAlphaTesting()) {
  58918. var alphaTexture = material.getAlphaTestTexture();
  58919. if (alphaTexture) {
  58920. defines.push("#define ALPHATEST");
  58921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58922. attribs.push(BABYLON.VertexBuffer.UVKind);
  58923. defines.push("#define UV1");
  58924. }
  58925. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58926. if (alphaTexture.coordinatesIndex === 1) {
  58927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58928. defines.push("#define UV2");
  58929. }
  58930. }
  58931. }
  58932. }
  58933. // Bones
  58934. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58937. if (mesh.numBoneInfluencers > 4) {
  58938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58940. }
  58941. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58942. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58943. }
  58944. else {
  58945. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58946. }
  58947. // Instances
  58948. if (useInstances) {
  58949. defines.push("#define INSTANCES");
  58950. attribs.push("world0");
  58951. attribs.push("world1");
  58952. attribs.push("world2");
  58953. attribs.push("world3");
  58954. }
  58955. // Get correct effect
  58956. var join = defines.join("\n");
  58957. if (this._cachedDefines !== join) {
  58958. this._cachedDefines = join;
  58959. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58960. }
  58961. if (!this._effect.isReady()) {
  58962. return false;
  58963. }
  58964. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58965. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58966. this._initializeBlurRTTAndPostProcesses();
  58967. }
  58968. }
  58969. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58970. return false;
  58971. }
  58972. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58973. return false;
  58974. }
  58975. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58976. return false;
  58977. }
  58978. return true;
  58979. };
  58980. /**
  58981. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58982. * @param defines Defines of the material we want to update
  58983. * @param lightIndex Index of the light in the enabled light list of the material
  58984. */
  58985. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58986. var scene = this._scene;
  58987. var light = this._light;
  58988. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58989. return;
  58990. }
  58991. defines["SHADOW" + lightIndex] = true;
  58992. if (this.usePoissonSampling) {
  58993. defines["SHADOWPCF" + lightIndex] = true;
  58994. }
  58995. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58996. defines["SHADOWESM" + lightIndex] = true;
  58997. }
  58998. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58999. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59000. }
  59001. if (light.needCube()) {
  59002. defines["SHADOWCUBE" + lightIndex] = true;
  59003. }
  59004. };
  59005. /**
  59006. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59007. * defined in the generator but impacting the effect).
  59008. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59009. * @param effect The effect we are binfing the information for
  59010. */
  59011. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59012. var light = this._light;
  59013. var scene = this._scene;
  59014. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59015. return;
  59016. }
  59017. var camera = scene.activeCamera;
  59018. if (!camera) {
  59019. return;
  59020. }
  59021. var shadowMap = this.getShadowMap();
  59022. if (!shadowMap) {
  59023. return;
  59024. }
  59025. if (!light.needCube()) {
  59026. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59027. }
  59028. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59029. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59030. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59031. };
  59032. /**
  59033. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59034. * (eq to shadow prjection matrix * light transform matrix)
  59035. * @returns The transform matrix used to create the shadow map
  59036. */
  59037. ShadowGenerator.prototype.getTransformMatrix = function () {
  59038. var scene = this._scene;
  59039. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59040. return this._transformMatrix;
  59041. }
  59042. this._currentRenderID = scene.getRenderId();
  59043. this._currentFaceIndexCache = this._currentFaceIndex;
  59044. var lightPosition = this._light.position;
  59045. if (this._light.computeTransformedInformation()) {
  59046. lightPosition = this._light.transformedPosition;
  59047. }
  59048. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59049. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59050. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59051. }
  59052. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59053. this._cachedPosition = lightPosition.clone();
  59054. this._cachedDirection = this._lightDirection.clone();
  59055. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59056. var shadowMap = this.getShadowMap();
  59057. if (shadowMap) {
  59058. var renderList = shadowMap.renderList;
  59059. if (renderList) {
  59060. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59061. }
  59062. }
  59063. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59064. }
  59065. return this._transformMatrix;
  59066. };
  59067. /**
  59068. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59069. * Cube and 2D textures for instance.
  59070. */
  59071. ShadowGenerator.prototype.recreateShadowMap = function () {
  59072. var shadowMap = this._shadowMap;
  59073. if (!shadowMap) {
  59074. return;
  59075. }
  59076. // Track render list.
  59077. var renderList = shadowMap.renderList;
  59078. // Clean up existing data.
  59079. this._disposeRTTandPostProcesses();
  59080. // Reinitializes.
  59081. this._initializeGenerator();
  59082. // Reaffect the filter to ensure a correct fallback if necessary.
  59083. this.filter = this.filter;
  59084. // Reaffect the filter.
  59085. this._applyFilterValues();
  59086. // Reaffect Render List.
  59087. this._shadowMap.renderList = renderList;
  59088. };
  59089. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59090. if (this._shadowMap2) {
  59091. this._shadowMap2.dispose();
  59092. this._shadowMap2 = null;
  59093. }
  59094. if (this._boxBlurPostprocess) {
  59095. this._boxBlurPostprocess.dispose();
  59096. this._boxBlurPostprocess = null;
  59097. }
  59098. if (this._kernelBlurXPostprocess) {
  59099. this._kernelBlurXPostprocess.dispose();
  59100. this._kernelBlurXPostprocess = null;
  59101. }
  59102. if (this._kernelBlurYPostprocess) {
  59103. this._kernelBlurYPostprocess.dispose();
  59104. this._kernelBlurYPostprocess = null;
  59105. }
  59106. this._blurPostProcesses = [];
  59107. };
  59108. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59109. if (this._shadowMap) {
  59110. this._shadowMap.dispose();
  59111. this._shadowMap = null;
  59112. }
  59113. this._disposeBlurPostProcesses();
  59114. };
  59115. /**
  59116. * Disposes the ShadowGenerator.
  59117. * Returns nothing.
  59118. */
  59119. ShadowGenerator.prototype.dispose = function () {
  59120. this._disposeRTTandPostProcesses();
  59121. if (this._light) {
  59122. this._light._shadowGenerator = null;
  59123. this._light._markMeshesAsLightDirty();
  59124. }
  59125. };
  59126. /**
  59127. * Serializes the shadow generator setup to a json object.
  59128. * @returns The serialized JSON object
  59129. */
  59130. ShadowGenerator.prototype.serialize = function () {
  59131. var serializationObject = {};
  59132. var shadowMap = this.getShadowMap();
  59133. if (!shadowMap) {
  59134. return serializationObject;
  59135. }
  59136. serializationObject.lightId = this._light.id;
  59137. serializationObject.mapSize = shadowMap.getRenderSize();
  59138. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59139. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59140. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59141. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59142. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59143. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59144. serializationObject.depthScale = this.depthScale;
  59145. serializationObject.darkness = this.getDarkness();
  59146. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59147. serializationObject.blurKernel = this.blurKernel;
  59148. serializationObject.blurScale = this.blurScale;
  59149. serializationObject.useKernelBlur = this.useKernelBlur;
  59150. serializationObject.transparencyShadow = this._transparencyShadow;
  59151. serializationObject.renderList = [];
  59152. if (shadowMap.renderList) {
  59153. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59154. var mesh = shadowMap.renderList[meshIndex];
  59155. serializationObject.renderList.push(mesh.id);
  59156. }
  59157. }
  59158. return serializationObject;
  59159. };
  59160. /**
  59161. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59162. * @param parsedShadowGenerator The JSON object to parse
  59163. * @param scene The scene to create the shadow map for
  59164. * @returns The parsed shadow generator
  59165. */
  59166. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59167. //casting to point light, as light is missing the position attr and typescript complains.
  59168. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59169. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59170. var shadowMap = shadowGenerator.getShadowMap();
  59171. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59172. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59173. meshes.forEach(function (mesh) {
  59174. if (!shadowMap) {
  59175. return;
  59176. }
  59177. if (!shadowMap.renderList) {
  59178. shadowMap.renderList = [];
  59179. }
  59180. shadowMap.renderList.push(mesh);
  59181. });
  59182. }
  59183. if (parsedShadowGenerator.usePoissonSampling) {
  59184. shadowGenerator.usePoissonSampling = true;
  59185. }
  59186. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59187. shadowGenerator.useExponentialShadowMap = true;
  59188. }
  59189. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59190. shadowGenerator.useBlurExponentialShadowMap = true;
  59191. }
  59192. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59193. shadowGenerator.useCloseExponentialShadowMap = true;
  59194. }
  59195. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59196. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59197. }
  59198. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59199. shadowGenerator.useExponentialShadowMap = true;
  59200. }
  59201. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59202. shadowGenerator.useBlurExponentialShadowMap = true;
  59203. }
  59204. if (parsedShadowGenerator.depthScale) {
  59205. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59206. }
  59207. if (parsedShadowGenerator.blurScale) {
  59208. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59209. }
  59210. if (parsedShadowGenerator.blurBoxOffset) {
  59211. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59212. }
  59213. if (parsedShadowGenerator.useKernelBlur) {
  59214. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59215. }
  59216. if (parsedShadowGenerator.blurKernel) {
  59217. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59218. }
  59219. if (parsedShadowGenerator.bias !== undefined) {
  59220. shadowGenerator.bias = parsedShadowGenerator.bias;
  59221. }
  59222. if (parsedShadowGenerator.darkness) {
  59223. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59224. }
  59225. if (parsedShadowGenerator.transparencyShadow) {
  59226. shadowGenerator.setTransparencyShadow(true);
  59227. }
  59228. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59229. return shadowGenerator;
  59230. };
  59231. ShadowGenerator._FILTER_NONE = 0;
  59232. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59233. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59234. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59235. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59236. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59237. return ShadowGenerator;
  59238. }());
  59239. BABYLON.ShadowGenerator = ShadowGenerator;
  59240. })(BABYLON || (BABYLON = {}));
  59241. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59242. var BABYLON;
  59243. (function (BABYLON) {
  59244. var DefaultLoadingScreen = /** @class */ (function () {
  59245. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59246. if (_loadingText === void 0) { _loadingText = ""; }
  59247. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59248. var _this = this;
  59249. this._renderingCanvas = _renderingCanvas;
  59250. this._loadingText = _loadingText;
  59251. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59252. // Resize
  59253. this._resizeLoadingUI = function () {
  59254. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59255. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59256. if (!_this._loadingDiv) {
  59257. return;
  59258. }
  59259. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59260. _this._loadingDiv.style.left = canvasRect.left + "px";
  59261. _this._loadingDiv.style.top = canvasRect.top + "px";
  59262. _this._loadingDiv.style.width = canvasRect.width + "px";
  59263. _this._loadingDiv.style.height = canvasRect.height + "px";
  59264. };
  59265. }
  59266. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59267. if (this._loadingDiv) {
  59268. // Do not add a loading screen if there is already one
  59269. return;
  59270. }
  59271. this._loadingDiv = document.createElement("div");
  59272. this._loadingDiv.id = "babylonjsLoadingDiv";
  59273. this._loadingDiv.style.opacity = "0";
  59274. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59275. this._loadingDiv.style.pointerEvents = "none";
  59276. // Loading text
  59277. this._loadingTextDiv = document.createElement("div");
  59278. this._loadingTextDiv.style.position = "absolute";
  59279. this._loadingTextDiv.style.left = "0";
  59280. this._loadingTextDiv.style.top = "50%";
  59281. this._loadingTextDiv.style.marginTop = "80px";
  59282. this._loadingTextDiv.style.width = "100%";
  59283. this._loadingTextDiv.style.height = "20px";
  59284. this._loadingTextDiv.style.fontFamily = "Arial";
  59285. this._loadingTextDiv.style.fontSize = "14px";
  59286. this._loadingTextDiv.style.color = "white";
  59287. this._loadingTextDiv.style.textAlign = "center";
  59288. this._loadingTextDiv.innerHTML = "Loading";
  59289. this._loadingDiv.appendChild(this._loadingTextDiv);
  59290. //set the predefined text
  59291. this._loadingTextDiv.innerHTML = this._loadingText;
  59292. // Generating keyframes
  59293. var style = document.createElement('style');
  59294. style.type = 'text/css';
  59295. 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 }";
  59296. style.innerHTML = keyFrames;
  59297. document.getElementsByTagName('head')[0].appendChild(style);
  59298. // Loading img
  59299. var imgBack = new Image();
  59300. 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";
  59301. imgBack.style.position = "absolute";
  59302. imgBack.style.left = "50%";
  59303. imgBack.style.top = "50%";
  59304. imgBack.style.marginLeft = "-60px";
  59305. imgBack.style.marginTop = "-60px";
  59306. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59307. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59308. imgBack.style.transformOrigin = "50% 50%";
  59309. imgBack.style.webkitTransformOrigin = "50% 50%";
  59310. this._loadingDiv.appendChild(imgBack);
  59311. this._resizeLoadingUI();
  59312. window.addEventListener("resize", this._resizeLoadingUI);
  59313. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59314. document.body.appendChild(this._loadingDiv);
  59315. this._loadingDiv.style.opacity = "1";
  59316. };
  59317. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59318. var _this = this;
  59319. if (!this._loadingDiv) {
  59320. return;
  59321. }
  59322. var onTransitionEnd = function () {
  59323. if (!_this._loadingDiv) {
  59324. return;
  59325. }
  59326. document.body.removeChild(_this._loadingDiv);
  59327. window.removeEventListener("resize", _this._resizeLoadingUI);
  59328. _this._loadingDiv = null;
  59329. };
  59330. this._loadingDiv.style.opacity = "0";
  59331. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59332. };
  59333. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59334. set: function (text) {
  59335. this._loadingText = text;
  59336. if (this._loadingTextDiv) {
  59337. this._loadingTextDiv.innerHTML = this._loadingText;
  59338. }
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59344. get: function () {
  59345. return this._loadingDivBackgroundColor;
  59346. },
  59347. set: function (color) {
  59348. this._loadingDivBackgroundColor = color;
  59349. if (!this._loadingDiv) {
  59350. return;
  59351. }
  59352. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59353. },
  59354. enumerable: true,
  59355. configurable: true
  59356. });
  59357. return DefaultLoadingScreen;
  59358. }());
  59359. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59360. })(BABYLON || (BABYLON = {}));
  59361. //# sourceMappingURL=babylon.loadingScreen.js.map
  59362. var BABYLON;
  59363. (function (BABYLON) {
  59364. var SceneLoaderProgressEvent = /** @class */ (function () {
  59365. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59366. this.lengthComputable = lengthComputable;
  59367. this.loaded = loaded;
  59368. this.total = total;
  59369. }
  59370. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59371. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59372. };
  59373. return SceneLoaderProgressEvent;
  59374. }());
  59375. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59376. var SceneLoader = /** @class */ (function () {
  59377. function SceneLoader() {
  59378. }
  59379. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59380. get: function () {
  59381. return 0;
  59382. },
  59383. enumerable: true,
  59384. configurable: true
  59385. });
  59386. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59387. get: function () {
  59388. return 1;
  59389. },
  59390. enumerable: true,
  59391. configurable: true
  59392. });
  59393. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59394. get: function () {
  59395. return 2;
  59396. },
  59397. enumerable: true,
  59398. configurable: true
  59399. });
  59400. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59401. get: function () {
  59402. return 3;
  59403. },
  59404. enumerable: true,
  59405. configurable: true
  59406. });
  59407. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59408. get: function () {
  59409. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59410. },
  59411. set: function (value) {
  59412. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59413. },
  59414. enumerable: true,
  59415. configurable: true
  59416. });
  59417. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59418. get: function () {
  59419. return SceneLoader._ShowLoadingScreen;
  59420. },
  59421. set: function (value) {
  59422. SceneLoader._ShowLoadingScreen = value;
  59423. },
  59424. enumerable: true,
  59425. configurable: true
  59426. });
  59427. Object.defineProperty(SceneLoader, "loggingLevel", {
  59428. get: function () {
  59429. return SceneLoader._loggingLevel;
  59430. },
  59431. set: function (value) {
  59432. SceneLoader._loggingLevel = value;
  59433. },
  59434. enumerable: true,
  59435. configurable: true
  59436. });
  59437. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59438. get: function () {
  59439. return SceneLoader._CleanBoneMatrixWeights;
  59440. },
  59441. set: function (value) {
  59442. SceneLoader._CleanBoneMatrixWeights = value;
  59443. },
  59444. enumerable: true,
  59445. configurable: true
  59446. });
  59447. SceneLoader._getDefaultPlugin = function () {
  59448. return SceneLoader._registeredPlugins[".babylon"];
  59449. };
  59450. SceneLoader._getPluginForExtension = function (extension) {
  59451. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59452. if (registeredPlugin) {
  59453. return registeredPlugin;
  59454. }
  59455. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59456. return SceneLoader._getDefaultPlugin();
  59457. };
  59458. SceneLoader._getPluginForDirectLoad = function (data) {
  59459. for (var extension in SceneLoader._registeredPlugins) {
  59460. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59461. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59462. return SceneLoader._registeredPlugins[extension];
  59463. }
  59464. }
  59465. return SceneLoader._getDefaultPlugin();
  59466. };
  59467. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59468. if (sceneFilename.name) {
  59469. sceneFilename = sceneFilename.name;
  59470. }
  59471. var queryStringPosition = sceneFilename.indexOf("?");
  59472. if (queryStringPosition !== -1) {
  59473. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59474. }
  59475. var dotPosition = sceneFilename.lastIndexOf(".");
  59476. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59477. return SceneLoader._getPluginForExtension(extension);
  59478. };
  59479. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59480. SceneLoader._getDirectLoad = function (sceneFilename) {
  59481. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59482. return sceneFilename.substr(5);
  59483. }
  59484. return null;
  59485. };
  59486. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59487. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59488. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59489. var plugin;
  59490. if (registeredPlugin.plugin.createPlugin) {
  59491. plugin = registeredPlugin.plugin.createPlugin();
  59492. }
  59493. else {
  59494. plugin = registeredPlugin.plugin;
  59495. }
  59496. var useArrayBuffer = registeredPlugin.isBinary;
  59497. var database;
  59498. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59499. var dataCallback = function (data, responseURL) {
  59500. if (scene.isDisposed) {
  59501. onError("Scene has been disposed");
  59502. return;
  59503. }
  59504. scene.database = database;
  59505. onSuccess(plugin, data, responseURL);
  59506. };
  59507. var request = null;
  59508. var pluginDisposed = false;
  59509. var onDisposeObservable = plugin.onDisposeObservable;
  59510. if (onDisposeObservable) {
  59511. onDisposeObservable.add(function () {
  59512. pluginDisposed = true;
  59513. if (request) {
  59514. request.abort();
  59515. request = null;
  59516. }
  59517. onDispose();
  59518. });
  59519. }
  59520. var manifestChecked = function () {
  59521. if (pluginDisposed) {
  59522. return;
  59523. }
  59524. var url = rootUrl + sceneFilename;
  59525. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59526. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59527. } : undefined, database, useArrayBuffer, function (request, exception) {
  59528. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59529. });
  59530. };
  59531. if (directLoad) {
  59532. dataCallback(directLoad);
  59533. return plugin;
  59534. }
  59535. if (rootUrl.indexOf("file:") === -1) {
  59536. if (scene.getEngine().enableOfflineSupport) {
  59537. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59538. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59539. }
  59540. else {
  59541. manifestChecked();
  59542. }
  59543. }
  59544. else {
  59545. var fileOrString = sceneFilename;
  59546. if (fileOrString.name) {
  59547. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59548. }
  59549. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59550. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59551. }
  59552. else {
  59553. onError("Unable to find file named " + sceneFilename);
  59554. }
  59555. }
  59556. return plugin;
  59557. };
  59558. // Public functions
  59559. SceneLoader.GetPluginForExtension = function (extension) {
  59560. return SceneLoader._getPluginForExtension(extension).plugin;
  59561. };
  59562. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59563. return !!SceneLoader._registeredPlugins[extension];
  59564. };
  59565. SceneLoader.RegisterPlugin = function (plugin) {
  59566. if (typeof plugin.extensions === "string") {
  59567. var extension = plugin.extensions;
  59568. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59569. plugin: plugin,
  59570. isBinary: false
  59571. };
  59572. }
  59573. else {
  59574. var extensions = plugin.extensions;
  59575. Object.keys(extensions).forEach(function (extension) {
  59576. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59577. plugin: plugin,
  59578. isBinary: extensions[extension].isBinary
  59579. };
  59580. });
  59581. }
  59582. };
  59583. /**
  59584. * Import meshes into a scene
  59585. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59586. * @param rootUrl a string that defines the root url for scene and resources
  59587. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59588. * @param scene the instance of BABYLON.Scene to append to
  59589. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59590. * @param onProgress a callback with a progress event for each file being loaded
  59591. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59592. * @param pluginExtension the extension used to determine the plugin
  59593. * @returns The loaded plugin
  59594. */
  59595. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59596. if (onSuccess === void 0) { onSuccess = null; }
  59597. if (onProgress === void 0) { onProgress = null; }
  59598. if (onError === void 0) { onError = null; }
  59599. if (pluginExtension === void 0) { pluginExtension = null; }
  59600. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59601. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59602. return null;
  59603. }
  59604. var loadingToken = {};
  59605. scene._addPendingData(loadingToken);
  59606. var disposeHandler = function () {
  59607. scene._removePendingData(loadingToken);
  59608. };
  59609. var errorHandler = function (message, exception) {
  59610. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59611. if (onError) {
  59612. onError(scene, errorMessage, exception);
  59613. }
  59614. else {
  59615. BABYLON.Tools.Error(errorMessage);
  59616. // should the exception be thrown?
  59617. }
  59618. disposeHandler();
  59619. };
  59620. var progressHandler = onProgress ? function (event) {
  59621. try {
  59622. onProgress(event);
  59623. }
  59624. catch (e) {
  59625. errorHandler("Error in onProgress callback", e);
  59626. }
  59627. } : undefined;
  59628. var successHandler = function (meshes, particleSystems, skeletons) {
  59629. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59630. if (onSuccess) {
  59631. try {
  59632. onSuccess(meshes, particleSystems, skeletons);
  59633. }
  59634. catch (e) {
  59635. errorHandler("Error in onSuccess callback", e);
  59636. }
  59637. }
  59638. scene._removePendingData(loadingToken);
  59639. };
  59640. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59641. if (plugin.rewriteRootURL) {
  59642. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59643. }
  59644. if (sceneFilename === "") {
  59645. if (sceneFilename === "") {
  59646. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59647. }
  59648. }
  59649. if (plugin.importMesh) {
  59650. var syncedPlugin = plugin;
  59651. var meshes = new Array();
  59652. var particleSystems = new Array();
  59653. var skeletons = new Array();
  59654. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59655. return;
  59656. }
  59657. scene.loadingPluginName = plugin.name;
  59658. successHandler(meshes, particleSystems, skeletons);
  59659. }
  59660. else {
  59661. var asyncedPlugin = plugin;
  59662. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59663. scene.loadingPluginName = plugin.name;
  59664. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59665. }).catch(function (error) {
  59666. errorHandler(error.message, error);
  59667. });
  59668. }
  59669. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59670. };
  59671. /**
  59672. * Import meshes into a scene
  59673. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59674. * @param rootUrl a string that defines the root url for scene and resources
  59675. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59676. * @param scene the instance of BABYLON.Scene to append to
  59677. * @param onProgress a callback with a progress event for each file being loaded
  59678. * @param pluginExtension the extension used to determine the plugin
  59679. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59680. */
  59681. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59682. if (onProgress === void 0) { onProgress = null; }
  59683. if (pluginExtension === void 0) { pluginExtension = null; }
  59684. return new Promise(function (resolve, reject) {
  59685. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59686. resolve({
  59687. meshes: meshes,
  59688. particleSystems: particleSystems,
  59689. skeletons: skeletons
  59690. });
  59691. }, onProgress, function (scene, message, exception) {
  59692. reject(exception || new Error(message));
  59693. });
  59694. });
  59695. };
  59696. /**
  59697. * Load a scene
  59698. * @param rootUrl a string that defines the root url for scene and resources
  59699. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59700. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59701. * @param onSuccess a callback with the scene when import succeeds
  59702. * @param onProgress a callback with a progress event for each file being loaded
  59703. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59704. * @param pluginExtension the extension used to determine the plugin
  59705. * @returns The loaded plugin
  59706. */
  59707. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59708. if (onSuccess === void 0) { onSuccess = null; }
  59709. if (onProgress === void 0) { onProgress = null; }
  59710. if (onError === void 0) { onError = null; }
  59711. if (pluginExtension === void 0) { pluginExtension = null; }
  59712. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59713. };
  59714. /**
  59715. * Load a scene
  59716. * @param rootUrl a string that defines the root url for scene and resources
  59717. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59718. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59719. * @param onProgress a callback with a progress event for each file being loaded
  59720. * @param pluginExtension the extension used to determine the plugin
  59721. * @returns The loaded scene
  59722. */
  59723. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59724. if (onProgress === void 0) { onProgress = null; }
  59725. if (pluginExtension === void 0) { pluginExtension = null; }
  59726. return new Promise(function (resolve, reject) {
  59727. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59728. resolve(scene);
  59729. }, onProgress, function (scene, message, exception) {
  59730. reject(exception || new Error(message));
  59731. }, pluginExtension);
  59732. });
  59733. };
  59734. /**
  59735. * Append a scene
  59736. * @param rootUrl a string that defines the root url for scene and resources
  59737. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59738. * @param scene is the instance of BABYLON.Scene to append to
  59739. * @param onSuccess a callback with the scene when import succeeds
  59740. * @param onProgress a callback with a progress event for each file being loaded
  59741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59742. * @param pluginExtension the extension used to determine the plugin
  59743. * @returns The loaded plugin
  59744. */
  59745. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59746. if (onSuccess === void 0) { onSuccess = null; }
  59747. if (onProgress === void 0) { onProgress = null; }
  59748. if (onError === void 0) { onError = null; }
  59749. if (pluginExtension === void 0) { pluginExtension = null; }
  59750. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59751. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59752. return null;
  59753. }
  59754. if (SceneLoader.ShowLoadingScreen) {
  59755. scene.getEngine().displayLoadingUI();
  59756. }
  59757. var loadingToken = {};
  59758. scene._addPendingData(loadingToken);
  59759. var disposeHandler = function () {
  59760. scene._removePendingData(loadingToken);
  59761. scene.getEngine().hideLoadingUI();
  59762. };
  59763. var errorHandler = function (message, exception) {
  59764. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59765. if (onError) {
  59766. onError(scene, errorMessage, exception);
  59767. }
  59768. else {
  59769. BABYLON.Tools.Error(errorMessage);
  59770. // should the exception be thrown?
  59771. }
  59772. disposeHandler();
  59773. };
  59774. var progressHandler = onProgress ? function (event) {
  59775. try {
  59776. onProgress(event);
  59777. }
  59778. catch (e) {
  59779. errorHandler("Error in onProgress callback", e);
  59780. }
  59781. } : undefined;
  59782. var successHandler = function () {
  59783. if (onSuccess) {
  59784. try {
  59785. onSuccess(scene);
  59786. }
  59787. catch (e) {
  59788. errorHandler("Error in onSuccess callback", e);
  59789. }
  59790. }
  59791. scene._removePendingData(loadingToken);
  59792. };
  59793. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59794. if (sceneFilename === "") {
  59795. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59796. }
  59797. if (plugin.load) {
  59798. var syncedPlugin = plugin;
  59799. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59800. return;
  59801. }
  59802. scene.loadingPluginName = plugin.name;
  59803. successHandler();
  59804. }
  59805. else {
  59806. var asyncedPlugin = plugin;
  59807. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59808. scene.loadingPluginName = plugin.name;
  59809. successHandler();
  59810. }).catch(function (error) {
  59811. errorHandler(error.message, error);
  59812. });
  59813. }
  59814. if (SceneLoader.ShowLoadingScreen) {
  59815. scene.executeWhenReady(function () {
  59816. scene.getEngine().hideLoadingUI();
  59817. });
  59818. }
  59819. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59820. };
  59821. /**
  59822. * Append a scene
  59823. * @param rootUrl a string that defines the root url for scene and resources
  59824. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59825. * @param scene is the instance of BABYLON.Scene to append to
  59826. * @param onProgress a callback with a progress event for each file being loaded
  59827. * @param pluginExtension the extension used to determine the plugin
  59828. * @returns The given scene
  59829. */
  59830. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59831. if (onProgress === void 0) { onProgress = null; }
  59832. if (pluginExtension === void 0) { pluginExtension = null; }
  59833. return new Promise(function (resolve, reject) {
  59834. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59835. resolve(scene);
  59836. }, onProgress, function (scene, message, exception) {
  59837. reject(exception || new Error(message));
  59838. }, pluginExtension);
  59839. });
  59840. };
  59841. /**
  59842. * Load a scene into an asset container
  59843. * @param rootUrl a string that defines the root url for scene and resources
  59844. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59845. * @param scene is the instance of BABYLON.Scene to append to
  59846. * @param onSuccess a callback with the scene when import succeeds
  59847. * @param onProgress a callback with a progress event for each file being loaded
  59848. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59849. * @param pluginExtension the extension used to determine the plugin
  59850. * @returns The loaded plugin
  59851. */
  59852. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59853. if (onSuccess === void 0) { onSuccess = null; }
  59854. if (onProgress === void 0) { onProgress = null; }
  59855. if (onError === void 0) { onError = null; }
  59856. if (pluginExtension === void 0) { pluginExtension = null; }
  59857. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59858. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59859. return null;
  59860. }
  59861. var loadingToken = {};
  59862. scene._addPendingData(loadingToken);
  59863. var disposeHandler = function () {
  59864. scene._removePendingData(loadingToken);
  59865. };
  59866. var errorHandler = function (message, exception) {
  59867. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59868. if (onError) {
  59869. onError(scene, errorMessage, exception);
  59870. }
  59871. else {
  59872. BABYLON.Tools.Error(errorMessage);
  59873. // should the exception be thrown?
  59874. }
  59875. disposeHandler();
  59876. };
  59877. var progressHandler = onProgress ? function (event) {
  59878. try {
  59879. onProgress(event);
  59880. }
  59881. catch (e) {
  59882. errorHandler("Error in onProgress callback", e);
  59883. }
  59884. } : undefined;
  59885. var successHandler = function (assets) {
  59886. if (onSuccess) {
  59887. try {
  59888. onSuccess(assets);
  59889. }
  59890. catch (e) {
  59891. errorHandler("Error in onSuccess callback", e);
  59892. }
  59893. }
  59894. scene._removePendingData(loadingToken);
  59895. };
  59896. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59897. if (plugin.loadAssetContainer) {
  59898. var syncedPlugin = plugin;
  59899. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59900. if (!assetContainer) {
  59901. return;
  59902. }
  59903. scene.loadingPluginName = plugin.name;
  59904. successHandler(assetContainer);
  59905. }
  59906. else if (plugin.loadAssetContainerAsync) {
  59907. var asyncedPlugin = plugin;
  59908. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59909. scene.loadingPluginName = plugin.name;
  59910. successHandler(assetContainer);
  59911. }).catch(function (error) {
  59912. errorHandler(error.message, error);
  59913. });
  59914. }
  59915. else {
  59916. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59917. }
  59918. if (SceneLoader.ShowLoadingScreen) {
  59919. scene.executeWhenReady(function () {
  59920. scene.getEngine().hideLoadingUI();
  59921. });
  59922. }
  59923. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59924. };
  59925. /**
  59926. * Load a scene into an asset container
  59927. * @param rootUrl a string that defines the root url for scene and resources
  59928. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59929. * @param scene is the instance of BABYLON.Scene to append to
  59930. * @param onProgress a callback with a progress event for each file being loaded
  59931. * @param pluginExtension the extension used to determine the plugin
  59932. * @returns The loaded asset container
  59933. */
  59934. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59935. if (onProgress === void 0) { onProgress = null; }
  59936. if (pluginExtension === void 0) { pluginExtension = null; }
  59937. return new Promise(function (resolve, reject) {
  59938. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59939. resolve(assetContainer);
  59940. }, onProgress, function (scene, message, exception) {
  59941. reject(exception || new Error(message));
  59942. }, pluginExtension);
  59943. });
  59944. };
  59945. // Flags
  59946. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59947. SceneLoader._ShowLoadingScreen = true;
  59948. SceneLoader._CleanBoneMatrixWeights = false;
  59949. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59950. // Members
  59951. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59952. SceneLoader._registeredPlugins = {};
  59953. return SceneLoader;
  59954. }());
  59955. BABYLON.SceneLoader = SceneLoader;
  59956. ;
  59957. })(BABYLON || (BABYLON = {}));
  59958. //# sourceMappingURL=babylon.sceneLoader.js.map
  59959. var BABYLON;
  59960. (function (BABYLON) {
  59961. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59962. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59963. var parsedMaterial = parsedData.materials[index];
  59964. if (parsedMaterial.id === id) {
  59965. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59966. }
  59967. }
  59968. return null;
  59969. };
  59970. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59971. for (var i in names) {
  59972. if (mesh.name === names[i]) {
  59973. hierarchyIds.push(mesh.id);
  59974. return true;
  59975. }
  59976. }
  59977. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59978. hierarchyIds.push(mesh.id);
  59979. return true;
  59980. }
  59981. return false;
  59982. };
  59983. var logOperation = function (operation, producer) {
  59984. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59985. };
  59986. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59987. if (addToScene === void 0) { addToScene = false; }
  59988. var container = new BABYLON.AssetContainer(scene);
  59989. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59990. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59991. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59992. // and avoid problems with multiple concurrent .babylon loads.
  59993. var log = "importScene has failed JSON parse";
  59994. try {
  59995. var parsedData = JSON.parse(data);
  59996. log = "";
  59997. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59998. var index;
  59999. var cache;
  60000. // Lights
  60001. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60002. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60003. var parsedLight = parsedData.lights[index];
  60004. var light = BABYLON.Light.Parse(parsedLight, scene);
  60005. if (light) {
  60006. container.lights.push(light);
  60007. log += (index === 0 ? "\n\tLights:" : "");
  60008. log += "\n\t\t" + light.toString(fullDetails);
  60009. }
  60010. }
  60011. }
  60012. // Animations
  60013. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60014. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60015. var parsedAnimation = parsedData.animations[index];
  60016. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60017. scene.animations.push(animation);
  60018. container.animations.push(animation);
  60019. log += (index === 0 ? "\n\tAnimations:" : "");
  60020. log += "\n\t\t" + animation.toString(fullDetails);
  60021. }
  60022. }
  60023. // Materials
  60024. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60025. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60026. var parsedMaterial = parsedData.materials[index];
  60027. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60028. container.materials.push(mat);
  60029. log += (index === 0 ? "\n\tMaterials:" : "");
  60030. log += "\n\t\t" + mat.toString(fullDetails);
  60031. }
  60032. }
  60033. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60034. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60035. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60036. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60037. container.multiMaterials.push(mmat);
  60038. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60039. log += "\n\t\t" + mmat.toString(fullDetails);
  60040. }
  60041. }
  60042. // Morph targets
  60043. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60044. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60045. var managerData = _a[_i];
  60046. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60047. }
  60048. }
  60049. // Skeletons
  60050. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60051. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60052. var parsedSkeleton = parsedData.skeletons[index];
  60053. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60054. container.skeletons.push(skeleton);
  60055. log += (index === 0 ? "\n\tSkeletons:" : "");
  60056. log += "\n\t\t" + skeleton.toString(fullDetails);
  60057. }
  60058. }
  60059. // Geometries
  60060. var geometries = parsedData.geometries;
  60061. if (geometries !== undefined && geometries !== null) {
  60062. var addedGeometry = new Array();
  60063. // Boxes
  60064. var boxes = geometries.boxes;
  60065. if (boxes !== undefined && boxes !== null) {
  60066. for (index = 0, cache = boxes.length; index < cache; index++) {
  60067. var parsedBox = boxes[index];
  60068. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60069. }
  60070. }
  60071. // Spheres
  60072. var spheres = geometries.spheres;
  60073. if (spheres !== undefined && spheres !== null) {
  60074. for (index = 0, cache = spheres.length; index < cache; index++) {
  60075. var parsedSphere = spheres[index];
  60076. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60077. }
  60078. }
  60079. // Cylinders
  60080. var cylinders = geometries.cylinders;
  60081. if (cylinders !== undefined && cylinders !== null) {
  60082. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60083. var parsedCylinder = cylinders[index];
  60084. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60085. }
  60086. }
  60087. // Toruses
  60088. var toruses = geometries.toruses;
  60089. if (toruses !== undefined && toruses !== null) {
  60090. for (index = 0, cache = toruses.length; index < cache; index++) {
  60091. var parsedTorus = toruses[index];
  60092. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60093. }
  60094. }
  60095. // Grounds
  60096. var grounds = geometries.grounds;
  60097. if (grounds !== undefined && grounds !== null) {
  60098. for (index = 0, cache = grounds.length; index < cache; index++) {
  60099. var parsedGround = grounds[index];
  60100. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60101. }
  60102. }
  60103. // Planes
  60104. var planes = geometries.planes;
  60105. if (planes !== undefined && planes !== null) {
  60106. for (index = 0, cache = planes.length; index < cache; index++) {
  60107. var parsedPlane = planes[index];
  60108. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60109. }
  60110. }
  60111. // TorusKnots
  60112. var torusKnots = geometries.torusKnots;
  60113. if (torusKnots !== undefined && torusKnots !== null) {
  60114. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60115. var parsedTorusKnot = torusKnots[index];
  60116. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60117. }
  60118. }
  60119. // VertexData
  60120. var vertexData = geometries.vertexData;
  60121. if (vertexData !== undefined && vertexData !== null) {
  60122. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60123. var parsedVertexData = vertexData[index];
  60124. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60125. }
  60126. }
  60127. addedGeometry.forEach(function (g) {
  60128. if (g) {
  60129. container.geometries.push(g);
  60130. }
  60131. });
  60132. }
  60133. // Transform nodes
  60134. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60135. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60136. var parsedTransformNode = parsedData.transformNodes[index];
  60137. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60138. container.transformNodes.push(node);
  60139. }
  60140. }
  60141. // Meshes
  60142. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60143. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60144. var parsedMesh = parsedData.meshes[index];
  60145. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60146. container.meshes.push(mesh);
  60147. log += (index === 0 ? "\n\tMeshes:" : "");
  60148. log += "\n\t\t" + mesh.toString(fullDetails);
  60149. }
  60150. }
  60151. // Cameras
  60152. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60153. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60154. var parsedCamera = parsedData.cameras[index];
  60155. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60156. container.cameras.push(camera);
  60157. log += (index === 0 ? "\n\tCameras:" : "");
  60158. log += "\n\t\t" + camera.toString(fullDetails);
  60159. }
  60160. }
  60161. // Browsing all the graph to connect the dots
  60162. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60163. var camera = scene.cameras[index];
  60164. if (camera._waitingParentId) {
  60165. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60166. camera._waitingParentId = null;
  60167. }
  60168. }
  60169. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60170. var light_1 = scene.lights[index];
  60171. if (light_1 && light_1._waitingParentId) {
  60172. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60173. light_1._waitingParentId = null;
  60174. }
  60175. }
  60176. // Sounds
  60177. // TODO: add sound
  60178. var loadedSounds = [];
  60179. var loadedSound;
  60180. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60181. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60182. var parsedSound = parsedData.sounds[index];
  60183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60184. if (!parsedSound.url)
  60185. parsedSound.url = parsedSound.name;
  60186. if (!loadedSounds[parsedSound.url]) {
  60187. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60188. loadedSounds[parsedSound.url] = loadedSound;
  60189. container.sounds.push(loadedSound);
  60190. }
  60191. else {
  60192. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60193. }
  60194. }
  60195. else {
  60196. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60197. }
  60198. }
  60199. }
  60200. loadedSounds = [];
  60201. // Connect parents & children and parse actions
  60202. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60203. var transformNode = scene.transformNodes[index];
  60204. if (transformNode._waitingParentId) {
  60205. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60206. transformNode._waitingParentId = null;
  60207. }
  60208. }
  60209. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60210. var mesh = scene.meshes[index];
  60211. if (mesh._waitingParentId) {
  60212. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60213. mesh._waitingParentId = null;
  60214. }
  60215. if (mesh._waitingActions) {
  60216. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60217. mesh._waitingActions = null;
  60218. }
  60219. }
  60220. // freeze world matrix application
  60221. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60222. var currentMesh = scene.meshes[index];
  60223. if (currentMesh._waitingFreezeWorldMatrix) {
  60224. currentMesh.freezeWorldMatrix();
  60225. currentMesh._waitingFreezeWorldMatrix = null;
  60226. }
  60227. else {
  60228. currentMesh.computeWorldMatrix(true);
  60229. }
  60230. }
  60231. // Particles Systems
  60232. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60233. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60234. var parsedParticleSystem = parsedData.particleSystems[index];
  60235. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60236. container.particleSystems.push(ps);
  60237. }
  60238. }
  60239. // Lens flares
  60240. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60241. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60242. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60243. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60244. container.lensFlareSystems.push(lf);
  60245. }
  60246. }
  60247. // Shadows
  60248. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60249. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60250. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60251. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60252. container.shadowGenerators.push(sg);
  60253. }
  60254. }
  60255. // Lights exclusions / inclusions
  60256. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60257. var light_2 = scene.lights[index];
  60258. // Excluded check
  60259. if (light_2._excludedMeshesIds.length > 0) {
  60260. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60261. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60262. if (excludedMesh) {
  60263. light_2.excludedMeshes.push(excludedMesh);
  60264. }
  60265. }
  60266. light_2._excludedMeshesIds = [];
  60267. }
  60268. // Included check
  60269. if (light_2._includedOnlyMeshesIds.length > 0) {
  60270. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60271. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60272. if (includedOnlyMesh) {
  60273. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60274. }
  60275. }
  60276. light_2._includedOnlyMeshesIds = [];
  60277. }
  60278. }
  60279. // Actions (scene)
  60280. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60281. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60282. }
  60283. if (!addToScene) {
  60284. container.removeAllFromScene();
  60285. }
  60286. }
  60287. catch (err) {
  60288. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60289. if (onError) {
  60290. onError(msg, err);
  60291. }
  60292. else {
  60293. BABYLON.Tools.Log(msg);
  60294. throw err;
  60295. }
  60296. }
  60297. finally {
  60298. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60299. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60300. }
  60301. }
  60302. return container;
  60303. };
  60304. BABYLON.SceneLoader.RegisterPlugin({
  60305. name: "babylon.js",
  60306. extensions: ".babylon",
  60307. canDirectLoad: function (data) {
  60308. if (data.indexOf("babylon") !== -1) {
  60309. return true;
  60310. }
  60311. return false;
  60312. },
  60313. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60314. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60315. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60316. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60317. // and avoid problems with multiple concurrent .babylon loads.
  60318. var log = "importMesh has failed JSON parse";
  60319. try {
  60320. var parsedData = JSON.parse(data);
  60321. log = "";
  60322. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60323. if (!meshesNames) {
  60324. meshesNames = null;
  60325. }
  60326. else if (!Array.isArray(meshesNames)) {
  60327. meshesNames = [meshesNames];
  60328. }
  60329. var hierarchyIds = new Array();
  60330. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60331. var loadedSkeletonsIds = [];
  60332. var loadedMaterialsIds = [];
  60333. var index;
  60334. var cache;
  60335. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60336. var parsedMesh = parsedData.meshes[index];
  60337. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60338. if (meshesNames !== null) {
  60339. // Remove found mesh name from list.
  60340. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60341. }
  60342. //Geometry?
  60343. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60344. //does the file contain geometries?
  60345. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60346. //find the correct geometry and add it to the scene
  60347. var found = false;
  60348. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60349. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60350. return;
  60351. }
  60352. else {
  60353. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60354. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60355. switch (geometryType) {
  60356. case "boxes":
  60357. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60358. break;
  60359. case "spheres":
  60360. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60361. break;
  60362. case "cylinders":
  60363. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60364. break;
  60365. case "toruses":
  60366. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60367. break;
  60368. case "grounds":
  60369. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60370. break;
  60371. case "planes":
  60372. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60373. break;
  60374. case "torusKnots":
  60375. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60376. break;
  60377. case "vertexData":
  60378. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60379. break;
  60380. }
  60381. found = true;
  60382. }
  60383. });
  60384. }
  60385. });
  60386. if (found === false) {
  60387. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60388. }
  60389. }
  60390. }
  60391. // Material ?
  60392. if (parsedMesh.materialId) {
  60393. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60394. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60395. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60396. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60397. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60398. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60399. var subMatId = parsedMultiMaterial.materials[matIndex];
  60400. loadedMaterialsIds.push(subMatId);
  60401. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60402. if (mat) {
  60403. log += "\n\tMaterial " + mat.toString(fullDetails);
  60404. }
  60405. }
  60406. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60407. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60408. if (mmat) {
  60409. materialFound = true;
  60410. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60411. }
  60412. break;
  60413. }
  60414. }
  60415. }
  60416. if (materialFound === false) {
  60417. loadedMaterialsIds.push(parsedMesh.materialId);
  60418. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60419. if (!mat) {
  60420. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60421. }
  60422. else {
  60423. log += "\n\tMaterial " + mat.toString(fullDetails);
  60424. }
  60425. }
  60426. }
  60427. // Skeleton ?
  60428. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60429. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60430. if (skeletonAlreadyLoaded === false) {
  60431. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60432. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60433. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60434. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60435. skeletons.push(skeleton);
  60436. loadedSkeletonsIds.push(parsedSkeleton.id);
  60437. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60438. }
  60439. }
  60440. }
  60441. }
  60442. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60443. meshes.push(mesh);
  60444. log += "\n\tMesh " + mesh.toString(fullDetails);
  60445. }
  60446. }
  60447. // Connecting parents
  60448. var currentMesh;
  60449. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60450. currentMesh = scene.meshes[index];
  60451. if (currentMesh._waitingParentId) {
  60452. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60453. currentMesh._waitingParentId = null;
  60454. }
  60455. }
  60456. // freeze and compute world matrix application
  60457. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60458. currentMesh = scene.meshes[index];
  60459. if (currentMesh._waitingFreezeWorldMatrix) {
  60460. currentMesh.freezeWorldMatrix();
  60461. currentMesh._waitingFreezeWorldMatrix = null;
  60462. }
  60463. else {
  60464. currentMesh.computeWorldMatrix(true);
  60465. }
  60466. }
  60467. }
  60468. // Particles
  60469. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60470. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60471. var parsedParticleSystem = parsedData.particleSystems[index];
  60472. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60473. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60474. }
  60475. }
  60476. }
  60477. return true;
  60478. }
  60479. catch (err) {
  60480. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60481. if (onError) {
  60482. onError(msg, err);
  60483. }
  60484. else {
  60485. BABYLON.Tools.Log(msg);
  60486. throw err;
  60487. }
  60488. }
  60489. finally {
  60490. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60491. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60492. }
  60493. }
  60494. return false;
  60495. },
  60496. load: function (scene, data, rootUrl, onError) {
  60497. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60498. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60499. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60500. // and avoid problems with multiple concurrent .babylon loads.
  60501. var log = "importScene has failed JSON parse";
  60502. try {
  60503. var parsedData = JSON.parse(data);
  60504. log = "";
  60505. // Scene
  60506. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60507. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60508. }
  60509. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60510. scene.autoClear = parsedData.autoClear;
  60511. }
  60512. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60513. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60514. }
  60515. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60516. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60517. }
  60518. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60519. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60520. }
  60521. // Fog
  60522. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60523. scene.fogMode = parsedData.fogMode;
  60524. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60525. scene.fogStart = parsedData.fogStart;
  60526. scene.fogEnd = parsedData.fogEnd;
  60527. scene.fogDensity = parsedData.fogDensity;
  60528. log += "\tFog mode for scene: ";
  60529. switch (scene.fogMode) {
  60530. // getters not compiling, so using hardcoded
  60531. case 1:
  60532. log += "exp\n";
  60533. break;
  60534. case 2:
  60535. log += "exp2\n";
  60536. break;
  60537. case 3:
  60538. log += "linear\n";
  60539. break;
  60540. }
  60541. }
  60542. //Physics
  60543. if (parsedData.physicsEnabled) {
  60544. var physicsPlugin;
  60545. if (parsedData.physicsEngine === "cannon") {
  60546. physicsPlugin = new BABYLON.CannonJSPlugin();
  60547. }
  60548. else if (parsedData.physicsEngine === "oimo") {
  60549. physicsPlugin = new BABYLON.OimoJSPlugin();
  60550. }
  60551. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60552. //else - default engine, which is currently oimo
  60553. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60554. scene.enablePhysics(physicsGravity, physicsPlugin);
  60555. }
  60556. // Metadata
  60557. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60558. scene.metadata = parsedData.metadata;
  60559. }
  60560. //collisions, if defined. otherwise, default is true
  60561. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60562. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60563. }
  60564. scene.workerCollisions = !!parsedData.workerCollisions;
  60565. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60566. if (!container) {
  60567. return false;
  60568. }
  60569. if (parsedData.autoAnimate) {
  60570. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60571. }
  60572. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60573. scene.setActiveCameraByID(parsedData.activeCameraID);
  60574. }
  60575. // Environment texture
  60576. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60577. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60578. if (parsedData.createDefaultSkybox === true) {
  60579. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60580. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60581. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60582. }
  60583. }
  60584. // Finish
  60585. return true;
  60586. }
  60587. catch (err) {
  60588. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60589. if (onError) {
  60590. onError(msg, err);
  60591. }
  60592. else {
  60593. BABYLON.Tools.Log(msg);
  60594. throw err;
  60595. }
  60596. }
  60597. finally {
  60598. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60599. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60600. }
  60601. }
  60602. return false;
  60603. },
  60604. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60605. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60606. return container;
  60607. }
  60608. });
  60609. })(BABYLON || (BABYLON = {}));
  60610. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60611. var BABYLON;
  60612. (function (BABYLON) {
  60613. var FilesInput = /** @class */ (function () {
  60614. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60615. this.onProcessFileCallback = function () { return true; };
  60616. this._engine = engine;
  60617. this._currentScene = scene;
  60618. this._sceneLoadedCallback = sceneLoadedCallback;
  60619. this._progressCallback = progressCallback;
  60620. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60621. this._textureLoadingCallback = textureLoadingCallback;
  60622. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60623. this._onReloadCallback = onReloadCallback;
  60624. this._errorCallback = errorCallback;
  60625. }
  60626. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60627. var _this = this;
  60628. if (elementToMonitor) {
  60629. this._elementToMonitor = elementToMonitor;
  60630. this._dragEnterHandler = function (e) { _this.drag(e); };
  60631. this._dragOverHandler = function (e) { _this.drag(e); };
  60632. this._dropHandler = function (e) { _this.drop(e); };
  60633. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60634. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60635. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60636. }
  60637. };
  60638. FilesInput.prototype.dispose = function () {
  60639. if (!this._elementToMonitor) {
  60640. return;
  60641. }
  60642. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60643. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60644. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60645. };
  60646. FilesInput.prototype.renderFunction = function () {
  60647. if (this._additionalRenderLoopLogicCallback) {
  60648. this._additionalRenderLoopLogicCallback();
  60649. }
  60650. if (this._currentScene) {
  60651. if (this._textureLoadingCallback) {
  60652. var remaining = this._currentScene.getWaitingItemsCount();
  60653. if (remaining > 0) {
  60654. this._textureLoadingCallback(remaining);
  60655. }
  60656. }
  60657. this._currentScene.render();
  60658. }
  60659. };
  60660. FilesInput.prototype.drag = function (e) {
  60661. e.stopPropagation();
  60662. e.preventDefault();
  60663. };
  60664. FilesInput.prototype.drop = function (eventDrop) {
  60665. eventDrop.stopPropagation();
  60666. eventDrop.preventDefault();
  60667. this.loadFiles(eventDrop);
  60668. };
  60669. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60670. var _this = this;
  60671. var reader = folder.createReader();
  60672. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60673. reader.readEntries(function (entries) {
  60674. remaining.count += entries.length;
  60675. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60676. var entry = entries_1[_i];
  60677. if (entry.isFile) {
  60678. entry.file(function (file) {
  60679. file.correctName = relativePath + file.name;
  60680. files.push(file);
  60681. if (--remaining.count === 0) {
  60682. callback();
  60683. }
  60684. });
  60685. }
  60686. else if (entry.isDirectory) {
  60687. _this._traverseFolder(entry, files, remaining, callback);
  60688. }
  60689. }
  60690. if (--remaining.count) {
  60691. callback();
  60692. }
  60693. });
  60694. };
  60695. FilesInput.prototype._processFiles = function (files) {
  60696. for (var i = 0; i < files.length; i++) {
  60697. var name = files[i].correctName.toLowerCase();
  60698. var extension = name.split('.').pop();
  60699. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60700. continue;
  60701. }
  60702. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60703. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60704. this._sceneFileToLoad = files[i];
  60705. }
  60706. else {
  60707. FilesInput.FilesToLoad[name] = files[i];
  60708. }
  60709. }
  60710. };
  60711. FilesInput.prototype.loadFiles = function (event) {
  60712. var _this = this;
  60713. if (this._startingProcessingFilesCallback)
  60714. this._startingProcessingFilesCallback();
  60715. // Handling data transfer via drag'n'drop
  60716. if (event && event.dataTransfer && event.dataTransfer.files) {
  60717. this._filesToLoad = event.dataTransfer.files;
  60718. }
  60719. // Handling files from input files
  60720. if (event && event.target && event.target.files) {
  60721. this._filesToLoad = event.target.files;
  60722. }
  60723. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60724. var files_1 = new Array();
  60725. var folders = [];
  60726. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60727. for (var i = 0; i < this._filesToLoad.length; i++) {
  60728. var fileToLoad = this._filesToLoad[i];
  60729. var name_1 = fileToLoad.name.toLowerCase();
  60730. var entry = void 0;
  60731. fileToLoad.correctName = name_1;
  60732. if (items) {
  60733. var item = items[i];
  60734. if (item.getAsEntry) {
  60735. entry = item.getAsEntry();
  60736. }
  60737. else if (item.webkitGetAsEntry) {
  60738. entry = item.webkitGetAsEntry();
  60739. }
  60740. }
  60741. if (!entry) {
  60742. files_1.push(fileToLoad);
  60743. }
  60744. else {
  60745. if (entry.isDirectory) {
  60746. folders.push(entry);
  60747. }
  60748. else {
  60749. files_1.push(fileToLoad);
  60750. }
  60751. }
  60752. }
  60753. if (folders.length === 0) {
  60754. this._processFiles(files_1);
  60755. this._processReload();
  60756. }
  60757. else {
  60758. var remaining = { count: folders.length };
  60759. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60760. var folder = folders_1[_i];
  60761. this._traverseFolder(folder, files_1, remaining, function () {
  60762. _this._processFiles(files_1);
  60763. if (remaining.count === 0) {
  60764. _this._processReload();
  60765. }
  60766. });
  60767. }
  60768. }
  60769. }
  60770. };
  60771. FilesInput.prototype._processReload = function () {
  60772. if (this._onReloadCallback) {
  60773. this._onReloadCallback(this._sceneFileToLoad);
  60774. }
  60775. else {
  60776. this.reload();
  60777. }
  60778. };
  60779. FilesInput.prototype.reload = function () {
  60780. var _this = this;
  60781. // If a scene file has been provided
  60782. if (this._sceneFileToLoad) {
  60783. if (this._currentScene) {
  60784. if (BABYLON.Tools.errorsCount > 0) {
  60785. BABYLON.Tools.ClearLogCache();
  60786. }
  60787. this._engine.stopRenderLoop();
  60788. this._currentScene.dispose();
  60789. }
  60790. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60791. if (_this._progressCallback) {
  60792. _this._progressCallback(progress);
  60793. }
  60794. }).then(function (scene) {
  60795. _this._currentScene = scene;
  60796. if (_this._sceneLoadedCallback) {
  60797. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60798. }
  60799. // Wait for textures and shaders to be ready
  60800. _this._currentScene.executeWhenReady(function () {
  60801. _this._engine.runRenderLoop(function () {
  60802. _this.renderFunction();
  60803. });
  60804. });
  60805. }).catch(function (error) {
  60806. if (_this._errorCallback) {
  60807. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60808. }
  60809. });
  60810. }
  60811. else {
  60812. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60813. }
  60814. };
  60815. FilesInput.FilesToLoad = {};
  60816. return FilesInput;
  60817. }());
  60818. BABYLON.FilesInput = FilesInput;
  60819. })(BABYLON || (BABYLON = {}));
  60820. //# sourceMappingURL=babylon.filesInput.js.map
  60821. var BABYLON;
  60822. (function (BABYLON) {
  60823. /**
  60824. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60825. * The underlying implementation relies on an associative array to ensure the best performances.
  60826. * The value can be anything including 'null' but except 'undefined'
  60827. */
  60828. var StringDictionary = /** @class */ (function () {
  60829. function StringDictionary() {
  60830. this._count = 0;
  60831. this._data = {};
  60832. }
  60833. /**
  60834. * This will clear this dictionary and copy the content from the 'source' one.
  60835. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60836. * @param source the dictionary to take the content from and copy to this dictionary
  60837. */
  60838. StringDictionary.prototype.copyFrom = function (source) {
  60839. var _this = this;
  60840. this.clear();
  60841. source.forEach(function (t, v) { return _this.add(t, v); });
  60842. };
  60843. /**
  60844. * Get a value based from its key
  60845. * @param key the given key to get the matching value from
  60846. * @return the value if found, otherwise undefined is returned
  60847. */
  60848. StringDictionary.prototype.get = function (key) {
  60849. var val = this._data[key];
  60850. if (val !== undefined) {
  60851. return val;
  60852. }
  60853. return undefined;
  60854. };
  60855. /**
  60856. * Get a value from its key or add it if it doesn't exist.
  60857. * This method will ensure you that a given key/data will be present in the dictionary.
  60858. * @param key the given key to get the matching value from
  60859. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60860. * The factory will only be invoked if there's no data for the given key.
  60861. * @return the value corresponding to the key.
  60862. */
  60863. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60864. var val = this.get(key);
  60865. if (val !== undefined) {
  60866. return val;
  60867. }
  60868. val = factory(key);
  60869. if (val) {
  60870. this.add(key, val);
  60871. }
  60872. return val;
  60873. };
  60874. /**
  60875. * Get a value from its key if present in the dictionary otherwise add it
  60876. * @param key the key to get the value from
  60877. * @param val if there's no such key/value pair in the dictionary add it with this value
  60878. * @return the value corresponding to the key
  60879. */
  60880. StringDictionary.prototype.getOrAdd = function (key, val) {
  60881. var curVal = this.get(key);
  60882. if (curVal !== undefined) {
  60883. return curVal;
  60884. }
  60885. this.add(key, val);
  60886. return val;
  60887. };
  60888. /**
  60889. * Check if there's a given key in the dictionary
  60890. * @param key the key to check for
  60891. * @return true if the key is present, false otherwise
  60892. */
  60893. StringDictionary.prototype.contains = function (key) {
  60894. return this._data[key] !== undefined;
  60895. };
  60896. /**
  60897. * Add a new key and its corresponding value
  60898. * @param key the key to add
  60899. * @param value the value corresponding to the key
  60900. * @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
  60901. */
  60902. StringDictionary.prototype.add = function (key, value) {
  60903. if (this._data[key] !== undefined) {
  60904. return false;
  60905. }
  60906. this._data[key] = value;
  60907. ++this._count;
  60908. return true;
  60909. };
  60910. StringDictionary.prototype.set = function (key, value) {
  60911. if (this._data[key] === undefined) {
  60912. return false;
  60913. }
  60914. this._data[key] = value;
  60915. return true;
  60916. };
  60917. /**
  60918. * Get the element of the given key and remove it from the dictionary
  60919. * @param key
  60920. */
  60921. StringDictionary.prototype.getAndRemove = function (key) {
  60922. var val = this.get(key);
  60923. if (val !== undefined) {
  60924. delete this._data[key];
  60925. --this._count;
  60926. return val;
  60927. }
  60928. return null;
  60929. };
  60930. /**
  60931. * Remove a key/value from the dictionary.
  60932. * @param key the key to remove
  60933. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60934. */
  60935. StringDictionary.prototype.remove = function (key) {
  60936. if (this.contains(key)) {
  60937. delete this._data[key];
  60938. --this._count;
  60939. return true;
  60940. }
  60941. return false;
  60942. };
  60943. /**
  60944. * Clear the whole content of the dictionary
  60945. */
  60946. StringDictionary.prototype.clear = function () {
  60947. this._data = {};
  60948. this._count = 0;
  60949. };
  60950. Object.defineProperty(StringDictionary.prototype, "count", {
  60951. get: function () {
  60952. return this._count;
  60953. },
  60954. enumerable: true,
  60955. configurable: true
  60956. });
  60957. /**
  60958. * Execute a callback on each key/val of the dictionary.
  60959. * Note that you can remove any element in this dictionary in the callback implementation
  60960. * @param callback the callback to execute on a given key/value pair
  60961. */
  60962. StringDictionary.prototype.forEach = function (callback) {
  60963. for (var cur in this._data) {
  60964. var val = this._data[cur];
  60965. callback(cur, val);
  60966. }
  60967. };
  60968. /**
  60969. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60970. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60971. * Note that you can remove any element in this dictionary in the callback implementation
  60972. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60973. */
  60974. StringDictionary.prototype.first = function (callback) {
  60975. for (var cur in this._data) {
  60976. var val = this._data[cur];
  60977. var res = callback(cur, val);
  60978. if (res) {
  60979. return res;
  60980. }
  60981. }
  60982. return null;
  60983. };
  60984. return StringDictionary;
  60985. }());
  60986. BABYLON.StringDictionary = StringDictionary;
  60987. })(BABYLON || (BABYLON = {}));
  60988. //# sourceMappingURL=babylon.stringDictionary.js.map
  60989. var BABYLON;
  60990. (function (BABYLON) {
  60991. var Tags = /** @class */ (function () {
  60992. function Tags() {
  60993. }
  60994. Tags.EnableFor = function (obj) {
  60995. obj._tags = obj._tags || {};
  60996. obj.hasTags = function () {
  60997. return Tags.HasTags(obj);
  60998. };
  60999. obj.addTags = function (tagsString) {
  61000. return Tags.AddTagsTo(obj, tagsString);
  61001. };
  61002. obj.removeTags = function (tagsString) {
  61003. return Tags.RemoveTagsFrom(obj, tagsString);
  61004. };
  61005. obj.matchesTagsQuery = function (tagsQuery) {
  61006. return Tags.MatchesQuery(obj, tagsQuery);
  61007. };
  61008. };
  61009. Tags.DisableFor = function (obj) {
  61010. delete obj._tags;
  61011. delete obj.hasTags;
  61012. delete obj.addTags;
  61013. delete obj.removeTags;
  61014. delete obj.matchesTagsQuery;
  61015. };
  61016. Tags.HasTags = function (obj) {
  61017. if (!obj._tags) {
  61018. return false;
  61019. }
  61020. return !BABYLON.Tools.IsEmpty(obj._tags);
  61021. };
  61022. Tags.GetTags = function (obj, asString) {
  61023. if (asString === void 0) { asString = true; }
  61024. if (!obj._tags) {
  61025. return null;
  61026. }
  61027. if (asString) {
  61028. var tagsArray = [];
  61029. for (var tag in obj._tags) {
  61030. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61031. tagsArray.push(tag);
  61032. }
  61033. }
  61034. return tagsArray.join(" ");
  61035. }
  61036. else {
  61037. return obj._tags;
  61038. }
  61039. };
  61040. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61041. // a tag cannot start with '||', '&&', and '!'
  61042. // it cannot contain whitespaces
  61043. Tags.AddTagsTo = function (obj, tagsString) {
  61044. if (!tagsString) {
  61045. return;
  61046. }
  61047. if (typeof tagsString !== "string") {
  61048. return;
  61049. }
  61050. var tags = tagsString.split(" ");
  61051. tags.forEach(function (tag, index, array) {
  61052. Tags._AddTagTo(obj, tag);
  61053. });
  61054. };
  61055. Tags._AddTagTo = function (obj, tag) {
  61056. tag = tag.trim();
  61057. if (tag === "" || tag === "true" || tag === "false") {
  61058. return;
  61059. }
  61060. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61061. return;
  61062. }
  61063. Tags.EnableFor(obj);
  61064. obj._tags[tag] = true;
  61065. };
  61066. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61067. if (!Tags.HasTags(obj)) {
  61068. return;
  61069. }
  61070. var tags = tagsString.split(" ");
  61071. for (var t in tags) {
  61072. Tags._RemoveTagFrom(obj, tags[t]);
  61073. }
  61074. };
  61075. Tags._RemoveTagFrom = function (obj, tag) {
  61076. delete obj._tags[tag];
  61077. };
  61078. Tags.MatchesQuery = function (obj, tagsQuery) {
  61079. if (tagsQuery === undefined) {
  61080. return true;
  61081. }
  61082. if (tagsQuery === "") {
  61083. return Tags.HasTags(obj);
  61084. }
  61085. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61086. };
  61087. return Tags;
  61088. }());
  61089. BABYLON.Tags = Tags;
  61090. })(BABYLON || (BABYLON = {}));
  61091. //# sourceMappingURL=babylon.tags.js.map
  61092. var BABYLON;
  61093. (function (BABYLON) {
  61094. var AndOrNotEvaluator = /** @class */ (function () {
  61095. function AndOrNotEvaluator() {
  61096. }
  61097. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61098. if (!query.match(/\([^\(\)]*\)/g)) {
  61099. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61100. }
  61101. else {
  61102. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61103. // remove parenthesis
  61104. r = r.slice(1, r.length - 1);
  61105. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61106. });
  61107. }
  61108. if (query === "true") {
  61109. return true;
  61110. }
  61111. if (query === "false") {
  61112. return false;
  61113. }
  61114. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61115. };
  61116. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61117. evaluateCallback = evaluateCallback || (function (r) {
  61118. return r === "true" ? true : false;
  61119. });
  61120. var result;
  61121. var or = parenthesisContent.split("||");
  61122. for (var i in or) {
  61123. if (or.hasOwnProperty(i)) {
  61124. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61125. var and = ori.split("&&");
  61126. if (and.length > 1) {
  61127. for (var j = 0; j < and.length; ++j) {
  61128. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61129. if (andj !== "true" && andj !== "false") {
  61130. if (andj[0] === "!") {
  61131. result = !evaluateCallback(andj.substring(1));
  61132. }
  61133. else {
  61134. result = evaluateCallback(andj);
  61135. }
  61136. }
  61137. else {
  61138. result = andj === "true" ? true : false;
  61139. }
  61140. if (!result) {
  61141. ori = "false";
  61142. break;
  61143. }
  61144. }
  61145. }
  61146. if (result || ori === "true") {
  61147. result = true;
  61148. break;
  61149. }
  61150. // result equals false (or undefined)
  61151. if (ori !== "true" && ori !== "false") {
  61152. if (ori[0] === "!") {
  61153. result = !evaluateCallback(ori.substring(1));
  61154. }
  61155. else {
  61156. result = evaluateCallback(ori);
  61157. }
  61158. }
  61159. else {
  61160. result = ori === "true" ? true : false;
  61161. }
  61162. }
  61163. }
  61164. // the whole parenthesis scope is replaced by 'true' or 'false'
  61165. return result ? "true" : "false";
  61166. };
  61167. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61168. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61169. // remove whitespaces
  61170. r = r.replace(/[\s]/g, function () { return ""; });
  61171. return r.length % 2 ? "!" : "";
  61172. });
  61173. booleanString = booleanString.trim();
  61174. if (booleanString === "!true") {
  61175. booleanString = "false";
  61176. }
  61177. else if (booleanString === "!false") {
  61178. booleanString = "true";
  61179. }
  61180. return booleanString;
  61181. };
  61182. return AndOrNotEvaluator;
  61183. }());
  61184. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61185. })(BABYLON || (BABYLON = {}));
  61186. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61187. var BABYLON;
  61188. (function (BABYLON) {
  61189. var Database = /** @class */ (function () {
  61190. function Database(urlToScene, callbackManifestChecked) {
  61191. // Handling various flavors of prefixed version of IndexedDB
  61192. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61193. this.callbackManifestChecked = callbackManifestChecked;
  61194. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61195. this.db = null;
  61196. this._enableSceneOffline = false;
  61197. this._enableTexturesOffline = false;
  61198. this.manifestVersionFound = 0;
  61199. this.mustUpdateRessources = false;
  61200. this.hasReachedQuota = false;
  61201. if (!Database.IDBStorageEnabled) {
  61202. this.callbackManifestChecked(true);
  61203. }
  61204. else {
  61205. this.checkManifestFile();
  61206. }
  61207. }
  61208. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61209. get: function () {
  61210. return this._enableSceneOffline;
  61211. },
  61212. enumerable: true,
  61213. configurable: true
  61214. });
  61215. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61216. get: function () {
  61217. return this._enableTexturesOffline;
  61218. },
  61219. enumerable: true,
  61220. configurable: true
  61221. });
  61222. Database.prototype.checkManifestFile = function () {
  61223. var _this = this;
  61224. var noManifestFile = function () {
  61225. _this._enableSceneOffline = false;
  61226. _this._enableTexturesOffline = false;
  61227. _this.callbackManifestChecked(false);
  61228. };
  61229. var timeStampUsed = false;
  61230. var manifestURL = this.currentSceneUrl + ".manifest";
  61231. var xhr = new XMLHttpRequest();
  61232. if (navigator.onLine) {
  61233. // Adding a timestamp to by-pass browsers' cache
  61234. timeStampUsed = true;
  61235. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61236. }
  61237. xhr.open("GET", manifestURL, true);
  61238. xhr.addEventListener("load", function () {
  61239. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61240. try {
  61241. var manifestFile = JSON.parse(xhr.response);
  61242. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61243. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61244. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61245. _this.manifestVersionFound = manifestFile.version;
  61246. }
  61247. if (_this.callbackManifestChecked) {
  61248. _this.callbackManifestChecked(true);
  61249. }
  61250. }
  61251. catch (ex) {
  61252. noManifestFile();
  61253. }
  61254. }
  61255. else {
  61256. noManifestFile();
  61257. }
  61258. }, false);
  61259. xhr.addEventListener("error", function (event) {
  61260. if (timeStampUsed) {
  61261. timeStampUsed = false;
  61262. // Let's retry without the timeStamp
  61263. // It could fail when coupled with HTML5 Offline API
  61264. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61265. xhr.open("GET", retryManifestURL, true);
  61266. xhr.send();
  61267. }
  61268. else {
  61269. noManifestFile();
  61270. }
  61271. }, false);
  61272. try {
  61273. xhr.send();
  61274. }
  61275. catch (ex) {
  61276. BABYLON.Tools.Error("Error on XHR send request.");
  61277. this.callbackManifestChecked(false);
  61278. }
  61279. };
  61280. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61281. var _this = this;
  61282. var handleError = function () {
  61283. _this.isSupported = false;
  61284. if (errorCallback)
  61285. errorCallback();
  61286. };
  61287. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61288. // Your browser doesn't support IndexedDB
  61289. this.isSupported = false;
  61290. if (errorCallback)
  61291. errorCallback();
  61292. }
  61293. else {
  61294. // If the DB hasn't been opened or created yet
  61295. if (!this.db) {
  61296. this.hasReachedQuota = false;
  61297. this.isSupported = true;
  61298. var request = this.idbFactory.open("babylonjs", 1);
  61299. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61300. request.onerror = function (event) {
  61301. handleError();
  61302. };
  61303. // executes when a version change transaction cannot complete due to other active transactions
  61304. request.onblocked = function (event) {
  61305. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61306. handleError();
  61307. };
  61308. // DB has been opened successfully
  61309. request.onsuccess = function (event) {
  61310. _this.db = request.result;
  61311. successCallback();
  61312. };
  61313. // Initialization of the DB. Creating Scenes & Textures stores
  61314. request.onupgradeneeded = function (event) {
  61315. _this.db = (event.target).result;
  61316. if (_this.db) {
  61317. try {
  61318. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61319. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61320. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61321. }
  61322. catch (ex) {
  61323. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61324. handleError();
  61325. }
  61326. }
  61327. };
  61328. }
  61329. else {
  61330. if (successCallback)
  61331. successCallback();
  61332. }
  61333. }
  61334. };
  61335. Database.prototype.loadImageFromDB = function (url, image) {
  61336. var _this = this;
  61337. var completeURL = Database.ReturnFullUrlLocation(url);
  61338. var saveAndLoadImage = function () {
  61339. if (!_this.hasReachedQuota && _this.db !== null) {
  61340. // the texture is not yet in the DB, let's try to save it
  61341. _this._saveImageIntoDBAsync(completeURL, image);
  61342. }
  61343. else {
  61344. image.src = url;
  61345. }
  61346. };
  61347. if (!this.mustUpdateRessources) {
  61348. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61349. }
  61350. else {
  61351. saveAndLoadImage();
  61352. }
  61353. };
  61354. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61355. if (this.isSupported && this.db !== null) {
  61356. var texture;
  61357. var transaction = this.db.transaction(["textures"]);
  61358. transaction.onabort = function (event) {
  61359. image.src = url;
  61360. };
  61361. transaction.oncomplete = function (event) {
  61362. var blobTextureURL;
  61363. if (texture) {
  61364. var URL = window.URL || window.webkitURL;
  61365. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61366. image.onerror = function () {
  61367. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61368. image.src = url;
  61369. };
  61370. image.src = blobTextureURL;
  61371. }
  61372. else {
  61373. notInDBCallback();
  61374. }
  61375. };
  61376. var getRequest = transaction.objectStore("textures").get(url);
  61377. getRequest.onsuccess = function (event) {
  61378. texture = (event.target).result;
  61379. };
  61380. getRequest.onerror = function (event) {
  61381. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61382. image.src = url;
  61383. };
  61384. }
  61385. else {
  61386. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61387. image.src = url;
  61388. }
  61389. };
  61390. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61391. var _this = this;
  61392. if (this.isSupported) {
  61393. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61394. var generateBlobUrl = function () {
  61395. var blobTextureURL;
  61396. if (blob) {
  61397. var URL = window.URL || window.webkitURL;
  61398. try {
  61399. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61400. }
  61401. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61402. catch (ex) {
  61403. blobTextureURL = URL.createObjectURL(blob);
  61404. }
  61405. }
  61406. if (blobTextureURL) {
  61407. image.src = blobTextureURL;
  61408. }
  61409. };
  61410. if (Database.IsUASupportingBlobStorage) {
  61411. var xhr = new XMLHttpRequest(), blob;
  61412. xhr.open("GET", url, true);
  61413. xhr.responseType = "blob";
  61414. xhr.addEventListener("load", function () {
  61415. if (xhr.status === 200 && _this.db) {
  61416. // Blob as response (XHR2)
  61417. blob = xhr.response;
  61418. var transaction = _this.db.transaction(["textures"], "readwrite");
  61419. // the transaction could abort because of a QuotaExceededError error
  61420. transaction.onabort = function (event) {
  61421. try {
  61422. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61423. var srcElement = (event.srcElement || event.target);
  61424. var error = srcElement.error;
  61425. if (error && error.name === "QuotaExceededError") {
  61426. _this.hasReachedQuota = true;
  61427. }
  61428. }
  61429. catch (ex) { }
  61430. generateBlobUrl();
  61431. };
  61432. transaction.oncomplete = function (event) {
  61433. generateBlobUrl();
  61434. };
  61435. var newTexture = { textureUrl: url, data: blob };
  61436. try {
  61437. // Put the blob into the dabase
  61438. var addRequest = transaction.objectStore("textures").put(newTexture);
  61439. addRequest.onsuccess = function (event) {
  61440. };
  61441. addRequest.onerror = function (event) {
  61442. generateBlobUrl();
  61443. };
  61444. }
  61445. catch (ex) {
  61446. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61447. if (ex.code === 25) {
  61448. Database.IsUASupportingBlobStorage = false;
  61449. }
  61450. image.src = url;
  61451. }
  61452. }
  61453. else {
  61454. image.src = url;
  61455. }
  61456. }, false);
  61457. xhr.addEventListener("error", function (event) {
  61458. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61459. image.src = url;
  61460. }, false);
  61461. xhr.send();
  61462. }
  61463. else {
  61464. image.src = url;
  61465. }
  61466. }
  61467. else {
  61468. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61469. image.src = url;
  61470. }
  61471. };
  61472. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61473. var _this = this;
  61474. var updateVersion = function () {
  61475. // the version is not yet in the DB or we need to update it
  61476. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61477. };
  61478. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61479. };
  61480. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61481. var _this = this;
  61482. if (this.isSupported && this.db) {
  61483. var version;
  61484. try {
  61485. var transaction = this.db.transaction(["versions"]);
  61486. transaction.oncomplete = function (event) {
  61487. if (version) {
  61488. // If the version in the JSON file is > than the version in DB
  61489. if (_this.manifestVersionFound > version.data) {
  61490. _this.mustUpdateRessources = true;
  61491. updateInDBCallback();
  61492. }
  61493. else {
  61494. callback(version.data);
  61495. }
  61496. }
  61497. else {
  61498. _this.mustUpdateRessources = true;
  61499. updateInDBCallback();
  61500. }
  61501. };
  61502. transaction.onabort = function (event) {
  61503. callback(-1);
  61504. };
  61505. var getRequest = transaction.objectStore("versions").get(url);
  61506. getRequest.onsuccess = function (event) {
  61507. version = (event.target).result;
  61508. };
  61509. getRequest.onerror = function (event) {
  61510. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61511. callback(-1);
  61512. };
  61513. }
  61514. catch (ex) {
  61515. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61516. callback(-1);
  61517. }
  61518. }
  61519. else {
  61520. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61521. callback(-1);
  61522. }
  61523. };
  61524. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61525. var _this = this;
  61526. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61527. try {
  61528. // Open a transaction to the database
  61529. var transaction = this.db.transaction(["versions"], "readwrite");
  61530. // the transaction could abort because of a QuotaExceededError error
  61531. transaction.onabort = function (event) {
  61532. try {
  61533. var error = event.srcElement['error'];
  61534. if (error && error.name === "QuotaExceededError") {
  61535. _this.hasReachedQuota = true;
  61536. }
  61537. }
  61538. catch (ex) { }
  61539. callback(-1);
  61540. };
  61541. transaction.oncomplete = function (event) {
  61542. callback(_this.manifestVersionFound);
  61543. };
  61544. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61545. // Put the scene into the database
  61546. var addRequest = transaction.objectStore("versions").put(newVersion);
  61547. addRequest.onsuccess = function (event) {
  61548. };
  61549. addRequest.onerror = function (event) {
  61550. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61551. };
  61552. }
  61553. catch (ex) {
  61554. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61555. callback(-1);
  61556. }
  61557. }
  61558. else {
  61559. callback(-1);
  61560. }
  61561. };
  61562. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61563. var _this = this;
  61564. var completeUrl = Database.ReturnFullUrlLocation(url);
  61565. var saveAndLoadFile = function () {
  61566. // the scene is not yet in the DB, let's try to save it
  61567. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61568. };
  61569. this._checkVersionFromDB(completeUrl, function (version) {
  61570. if (version !== -1) {
  61571. if (!_this.mustUpdateRessources) {
  61572. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61573. }
  61574. else {
  61575. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61576. }
  61577. }
  61578. else {
  61579. if (errorCallback) {
  61580. errorCallback();
  61581. }
  61582. }
  61583. });
  61584. };
  61585. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61586. if (this.isSupported && this.db) {
  61587. var targetStore;
  61588. if (url.indexOf(".babylon") !== -1) {
  61589. targetStore = "scenes";
  61590. }
  61591. else {
  61592. targetStore = "textures";
  61593. }
  61594. var file;
  61595. var transaction = this.db.transaction([targetStore]);
  61596. transaction.oncomplete = function (event) {
  61597. if (file) {
  61598. callback(file.data);
  61599. }
  61600. else {
  61601. notInDBCallback();
  61602. }
  61603. };
  61604. transaction.onabort = function (event) {
  61605. notInDBCallback();
  61606. };
  61607. var getRequest = transaction.objectStore(targetStore).get(url);
  61608. getRequest.onsuccess = function (event) {
  61609. file = (event.target).result;
  61610. };
  61611. getRequest.onerror = function (event) {
  61612. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61613. notInDBCallback();
  61614. };
  61615. }
  61616. else {
  61617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61618. callback();
  61619. }
  61620. };
  61621. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61622. var _this = this;
  61623. if (this.isSupported) {
  61624. var targetStore;
  61625. if (url.indexOf(".babylon") !== -1) {
  61626. targetStore = "scenes";
  61627. }
  61628. else {
  61629. targetStore = "textures";
  61630. }
  61631. // Create XHR
  61632. var xhr = new XMLHttpRequest();
  61633. var fileData;
  61634. xhr.open("GET", url, true);
  61635. if (useArrayBuffer) {
  61636. xhr.responseType = "arraybuffer";
  61637. }
  61638. if (progressCallback) {
  61639. xhr.onprogress = progressCallback;
  61640. }
  61641. xhr.addEventListener("load", function () {
  61642. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61643. // Blob as response (XHR2)
  61644. //fileData = xhr.responseText;
  61645. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61646. if (!_this.hasReachedQuota && _this.db) {
  61647. // Open a transaction to the database
  61648. var transaction = _this.db.transaction([targetStore], "readwrite");
  61649. // the transaction could abort because of a QuotaExceededError error
  61650. transaction.onabort = function (event) {
  61651. try {
  61652. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61653. var error = event.srcElement['error'];
  61654. if (error && error.name === "QuotaExceededError") {
  61655. _this.hasReachedQuota = true;
  61656. }
  61657. }
  61658. catch (ex) { }
  61659. callback(fileData);
  61660. };
  61661. transaction.oncomplete = function (event) {
  61662. callback(fileData);
  61663. };
  61664. var newFile;
  61665. if (targetStore === "scenes") {
  61666. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61667. }
  61668. else {
  61669. newFile = { textureUrl: url, data: fileData };
  61670. }
  61671. try {
  61672. // Put the scene into the database
  61673. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61674. addRequest.onsuccess = function (event) {
  61675. };
  61676. addRequest.onerror = function (event) {
  61677. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61678. };
  61679. }
  61680. catch (ex) {
  61681. callback(fileData);
  61682. }
  61683. }
  61684. else {
  61685. callback(fileData);
  61686. }
  61687. }
  61688. else {
  61689. callback();
  61690. }
  61691. }, false);
  61692. xhr.addEventListener("error", function (event) {
  61693. BABYLON.Tools.Error("error on XHR request.");
  61694. callback();
  61695. }, false);
  61696. xhr.send();
  61697. }
  61698. else {
  61699. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61700. callback();
  61701. }
  61702. };
  61703. Database.IsUASupportingBlobStorage = true;
  61704. Database.IDBStorageEnabled = true;
  61705. Database.parseURL = function (url) {
  61706. var a = document.createElement('a');
  61707. a.href = url;
  61708. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61709. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61710. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61711. return absLocation;
  61712. };
  61713. Database.ReturnFullUrlLocation = function (url) {
  61714. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61715. return (Database.parseURL(window.location.href) + url);
  61716. }
  61717. else {
  61718. return url;
  61719. }
  61720. };
  61721. return Database;
  61722. }());
  61723. BABYLON.Database = Database;
  61724. })(BABYLON || (BABYLON = {}));
  61725. //# sourceMappingURL=babylon.database.js.map
  61726. var BABYLON;
  61727. (function (BABYLON) {
  61728. var FresnelParameters = /** @class */ (function () {
  61729. function FresnelParameters() {
  61730. this._isEnabled = true;
  61731. this.leftColor = BABYLON.Color3.White();
  61732. this.rightColor = BABYLON.Color3.Black();
  61733. this.bias = 0;
  61734. this.power = 1;
  61735. }
  61736. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61737. get: function () {
  61738. return this._isEnabled;
  61739. },
  61740. set: function (value) {
  61741. if (this._isEnabled === value) {
  61742. return;
  61743. }
  61744. this._isEnabled = value;
  61745. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61746. },
  61747. enumerable: true,
  61748. configurable: true
  61749. });
  61750. FresnelParameters.prototype.clone = function () {
  61751. var newFresnelParameters = new FresnelParameters();
  61752. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61753. return newFresnelParameters;
  61754. };
  61755. FresnelParameters.prototype.serialize = function () {
  61756. var serializationObject = {};
  61757. serializationObject.isEnabled = this.isEnabled;
  61758. serializationObject.leftColor = this.leftColor;
  61759. serializationObject.rightColor = this.rightColor;
  61760. serializationObject.bias = this.bias;
  61761. serializationObject.power = this.power;
  61762. return serializationObject;
  61763. };
  61764. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61765. var fresnelParameters = new FresnelParameters();
  61766. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61767. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61768. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61769. fresnelParameters.bias = parsedFresnelParameters.bias;
  61770. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61771. return fresnelParameters;
  61772. };
  61773. return FresnelParameters;
  61774. }());
  61775. BABYLON.FresnelParameters = FresnelParameters;
  61776. })(BABYLON || (BABYLON = {}));
  61777. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61778. var BABYLON;
  61779. (function (BABYLON) {
  61780. var MultiMaterial = /** @class */ (function (_super) {
  61781. __extends(MultiMaterial, _super);
  61782. function MultiMaterial(name, scene) {
  61783. var _this = _super.call(this, name, scene, true) || this;
  61784. scene.multiMaterials.push(_this);
  61785. _this.subMaterials = new Array();
  61786. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61787. return _this;
  61788. }
  61789. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61790. get: function () {
  61791. return this._subMaterials;
  61792. },
  61793. set: function (value) {
  61794. this._subMaterials = value;
  61795. this._hookArray(value);
  61796. },
  61797. enumerable: true,
  61798. configurable: true
  61799. });
  61800. MultiMaterial.prototype._hookArray = function (array) {
  61801. var _this = this;
  61802. var oldPush = array.push;
  61803. array.push = function () {
  61804. var items = [];
  61805. for (var _i = 0; _i < arguments.length; _i++) {
  61806. items[_i] = arguments[_i];
  61807. }
  61808. var result = oldPush.apply(array, items);
  61809. _this._markAllSubMeshesAsTexturesDirty();
  61810. return result;
  61811. };
  61812. var oldSplice = array.splice;
  61813. array.splice = function (index, deleteCount) {
  61814. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61815. _this._markAllSubMeshesAsTexturesDirty();
  61816. return deleted;
  61817. };
  61818. };
  61819. // Properties
  61820. MultiMaterial.prototype.getSubMaterial = function (index) {
  61821. if (index < 0 || index >= this.subMaterials.length) {
  61822. return this.getScene().defaultMaterial;
  61823. }
  61824. return this.subMaterials[index];
  61825. };
  61826. MultiMaterial.prototype.getActiveTextures = function () {
  61827. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61828. if (subMaterial) {
  61829. return subMaterial.getActiveTextures();
  61830. }
  61831. else {
  61832. return [];
  61833. }
  61834. }));
  61835. var _a;
  61836. };
  61837. // Methods
  61838. MultiMaterial.prototype.getClassName = function () {
  61839. return "MultiMaterial";
  61840. };
  61841. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61842. for (var index = 0; index < this.subMaterials.length; index++) {
  61843. var subMaterial = this.subMaterials[index];
  61844. if (subMaterial) {
  61845. if (subMaterial.storeEffectOnSubMeshes) {
  61846. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61847. return false;
  61848. }
  61849. continue;
  61850. }
  61851. if (!subMaterial.isReady(mesh)) {
  61852. return false;
  61853. }
  61854. }
  61855. }
  61856. return true;
  61857. };
  61858. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61859. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61860. for (var index = 0; index < this.subMaterials.length; index++) {
  61861. var subMaterial = null;
  61862. var current = this.subMaterials[index];
  61863. if (cloneChildren && current) {
  61864. subMaterial = current.clone(name + "-" + current.name);
  61865. }
  61866. else {
  61867. subMaterial = this.subMaterials[index];
  61868. }
  61869. newMultiMaterial.subMaterials.push(subMaterial);
  61870. }
  61871. return newMultiMaterial;
  61872. };
  61873. MultiMaterial.prototype.serialize = function () {
  61874. var serializationObject = {};
  61875. serializationObject.name = this.name;
  61876. serializationObject.id = this.id;
  61877. if (BABYLON.Tags) {
  61878. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61879. }
  61880. serializationObject.materials = [];
  61881. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61882. var subMat = this.subMaterials[matIndex];
  61883. if (subMat) {
  61884. serializationObject.materials.push(subMat.id);
  61885. }
  61886. else {
  61887. serializationObject.materials.push(null);
  61888. }
  61889. }
  61890. return serializationObject;
  61891. };
  61892. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61893. var scene = this.getScene();
  61894. if (!scene) {
  61895. return;
  61896. }
  61897. var index = scene.multiMaterials.indexOf(this);
  61898. if (index >= 0) {
  61899. scene.multiMaterials.splice(index, 1);
  61900. }
  61901. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61902. };
  61903. return MultiMaterial;
  61904. }(BABYLON.Material));
  61905. BABYLON.MultiMaterial = MultiMaterial;
  61906. })(BABYLON || (BABYLON = {}));
  61907. //# sourceMappingURL=babylon.multiMaterial.js.map
  61908. var BABYLON;
  61909. (function (BABYLON) {
  61910. var FreeCameraTouchInput = /** @class */ (function () {
  61911. function FreeCameraTouchInput() {
  61912. this._offsetX = null;
  61913. this._offsetY = null;
  61914. this._pointerPressed = new Array();
  61915. this.touchAngularSensibility = 200000.0;
  61916. this.touchMoveSensibility = 250.0;
  61917. }
  61918. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61919. var _this = this;
  61920. var previousPosition = null;
  61921. if (this._pointerInput === undefined) {
  61922. this._onLostFocus = function (evt) {
  61923. _this._offsetX = null;
  61924. _this._offsetY = null;
  61925. };
  61926. this._pointerInput = function (p, s) {
  61927. var evt = p.event;
  61928. if (evt.pointerType === "mouse") {
  61929. return;
  61930. }
  61931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61932. if (!noPreventDefault) {
  61933. evt.preventDefault();
  61934. }
  61935. _this._pointerPressed.push(evt.pointerId);
  61936. if (_this._pointerPressed.length !== 1) {
  61937. return;
  61938. }
  61939. previousPosition = {
  61940. x: evt.clientX,
  61941. y: evt.clientY
  61942. };
  61943. }
  61944. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61945. if (!noPreventDefault) {
  61946. evt.preventDefault();
  61947. }
  61948. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61949. if (index === -1) {
  61950. return;
  61951. }
  61952. _this._pointerPressed.splice(index, 1);
  61953. if (index != 0) {
  61954. return;
  61955. }
  61956. previousPosition = null;
  61957. _this._offsetX = null;
  61958. _this._offsetY = null;
  61959. }
  61960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61961. if (!noPreventDefault) {
  61962. evt.preventDefault();
  61963. }
  61964. if (!previousPosition) {
  61965. return;
  61966. }
  61967. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61968. if (index != 0) {
  61969. return;
  61970. }
  61971. _this._offsetX = evt.clientX - previousPosition.x;
  61972. _this._offsetY = -(evt.clientY - previousPosition.y);
  61973. }
  61974. };
  61975. }
  61976. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61977. if (this._onLostFocus) {
  61978. element.addEventListener("blur", this._onLostFocus);
  61979. }
  61980. };
  61981. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61982. if (this._pointerInput && element) {
  61983. if (this._observer) {
  61984. this.camera.getScene().onPointerObservable.remove(this._observer);
  61985. this._observer = null;
  61986. }
  61987. if (this._onLostFocus) {
  61988. element.removeEventListener("blur", this._onLostFocus);
  61989. this._onLostFocus = null;
  61990. }
  61991. this._pointerPressed = [];
  61992. this._offsetX = null;
  61993. this._offsetY = null;
  61994. }
  61995. };
  61996. FreeCameraTouchInput.prototype.checkInputs = function () {
  61997. if (this._offsetX && this._offsetY) {
  61998. var camera = this.camera;
  61999. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62000. if (this._pointerPressed.length > 1) {
  62001. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62002. }
  62003. else {
  62004. var speed = camera._computeLocalCameraSpeed();
  62005. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62006. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62007. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62008. }
  62009. }
  62010. };
  62011. FreeCameraTouchInput.prototype.getClassName = function () {
  62012. return "FreeCameraTouchInput";
  62013. };
  62014. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62015. return "touch";
  62016. };
  62017. __decorate([
  62018. BABYLON.serialize()
  62019. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62020. __decorate([
  62021. BABYLON.serialize()
  62022. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62023. return FreeCameraTouchInput;
  62024. }());
  62025. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62026. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62027. })(BABYLON || (BABYLON = {}));
  62028. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62029. var BABYLON;
  62030. (function (BABYLON) {
  62031. // We're mainly based on the logic defined into the FreeCamera code
  62032. var TouchCamera = /** @class */ (function (_super) {
  62033. __extends(TouchCamera, _super);
  62034. //-- end properties for backward compatibility for inputs
  62035. function TouchCamera(name, position, scene) {
  62036. var _this = _super.call(this, name, position, scene) || this;
  62037. _this.inputs.addTouch();
  62038. _this._setupInputs();
  62039. return _this;
  62040. }
  62041. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62042. //-- Begin properties for backward compatibility for inputs
  62043. get: function () {
  62044. var touch = this.inputs.attached["touch"];
  62045. if (touch)
  62046. return touch.touchAngularSensibility;
  62047. return 0;
  62048. },
  62049. set: function (value) {
  62050. var touch = this.inputs.attached["touch"];
  62051. if (touch)
  62052. touch.touchAngularSensibility = value;
  62053. },
  62054. enumerable: true,
  62055. configurable: true
  62056. });
  62057. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62058. get: function () {
  62059. var touch = this.inputs.attached["touch"];
  62060. if (touch)
  62061. return touch.touchMoveSensibility;
  62062. return 0;
  62063. },
  62064. set: function (value) {
  62065. var touch = this.inputs.attached["touch"];
  62066. if (touch)
  62067. touch.touchMoveSensibility = value;
  62068. },
  62069. enumerable: true,
  62070. configurable: true
  62071. });
  62072. TouchCamera.prototype.getClassName = function () {
  62073. return "TouchCamera";
  62074. };
  62075. TouchCamera.prototype._setupInputs = function () {
  62076. var mouse = this.inputs.attached["mouse"];
  62077. if (mouse) {
  62078. mouse.touchEnabled = false;
  62079. }
  62080. };
  62081. return TouchCamera;
  62082. }(BABYLON.FreeCamera));
  62083. BABYLON.TouchCamera = TouchCamera;
  62084. })(BABYLON || (BABYLON = {}));
  62085. //# sourceMappingURL=babylon.touchCamera.js.map
  62086. var BABYLON;
  62087. (function (BABYLON) {
  62088. var ProceduralTexture = /** @class */ (function (_super) {
  62089. __extends(ProceduralTexture, _super);
  62090. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62091. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62092. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62093. if (isCube === void 0) { isCube = false; }
  62094. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62095. _this.isCube = isCube;
  62096. _this.isEnabled = true;
  62097. _this._currentRefreshId = -1;
  62098. _this._refreshRate = 1;
  62099. _this._vertexBuffers = {};
  62100. _this._uniforms = new Array();
  62101. _this._samplers = new Array();
  62102. _this._textures = {};
  62103. _this._floats = {};
  62104. _this._floatsArrays = {};
  62105. _this._colors3 = {};
  62106. _this._colors4 = {};
  62107. _this._vectors2 = {};
  62108. _this._vectors3 = {};
  62109. _this._matrices = {};
  62110. _this._fallbackTextureUsed = false;
  62111. scene._proceduralTextures.push(_this);
  62112. _this._engine = scene.getEngine();
  62113. _this.name = name;
  62114. _this.isRenderTarget = true;
  62115. _this._size = size;
  62116. _this._generateMipMaps = generateMipMaps;
  62117. _this.setFragment(fragment);
  62118. _this._fallbackTexture = fallbackTexture;
  62119. if (isCube) {
  62120. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62121. _this.setFloat("face", 0);
  62122. }
  62123. else {
  62124. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62125. }
  62126. // VBO
  62127. var vertices = [];
  62128. vertices.push(1, 1);
  62129. vertices.push(-1, 1);
  62130. vertices.push(-1, -1);
  62131. vertices.push(1, -1);
  62132. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62133. _this._createIndexBuffer();
  62134. return _this;
  62135. }
  62136. ProceduralTexture.prototype._createIndexBuffer = function () {
  62137. var engine = this._engine;
  62138. // Indices
  62139. var indices = [];
  62140. indices.push(0);
  62141. indices.push(1);
  62142. indices.push(2);
  62143. indices.push(0);
  62144. indices.push(2);
  62145. indices.push(3);
  62146. this._indexBuffer = engine.createIndexBuffer(indices);
  62147. };
  62148. ProceduralTexture.prototype._rebuild = function () {
  62149. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62150. if (vb) {
  62151. vb._rebuild();
  62152. }
  62153. this._createIndexBuffer();
  62154. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62155. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62156. }
  62157. };
  62158. ProceduralTexture.prototype.reset = function () {
  62159. if (this._effect === undefined) {
  62160. return;
  62161. }
  62162. var engine = this._engine;
  62163. engine._releaseEffect(this._effect);
  62164. };
  62165. ProceduralTexture.prototype.isReady = function () {
  62166. var _this = this;
  62167. var engine = this._engine;
  62168. var shaders;
  62169. if (!this._fragment) {
  62170. return false;
  62171. }
  62172. if (this._fallbackTextureUsed) {
  62173. return true;
  62174. }
  62175. if (this._fragment.fragmentElement !== undefined) {
  62176. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62177. }
  62178. else {
  62179. shaders = { vertex: "procedural", fragment: this._fragment };
  62180. }
  62181. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62182. _this.releaseInternalTexture();
  62183. if (_this._fallbackTexture) {
  62184. _this._texture = _this._fallbackTexture._texture;
  62185. if (_this._texture) {
  62186. _this._texture.incrementReferences();
  62187. }
  62188. }
  62189. _this._fallbackTextureUsed = true;
  62190. });
  62191. return this._effect.isReady();
  62192. };
  62193. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62194. this._currentRefreshId = -1;
  62195. };
  62196. ProceduralTexture.prototype.setFragment = function (fragment) {
  62197. this._fragment = fragment;
  62198. };
  62199. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62200. get: function () {
  62201. return this._refreshRate;
  62202. },
  62203. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62204. set: function (value) {
  62205. this._refreshRate = value;
  62206. this.resetRefreshCounter();
  62207. },
  62208. enumerable: true,
  62209. configurable: true
  62210. });
  62211. ProceduralTexture.prototype._shouldRender = function () {
  62212. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62213. return false;
  62214. }
  62215. if (this._fallbackTextureUsed) {
  62216. return false;
  62217. }
  62218. if (this._currentRefreshId === -1) {
  62219. this._currentRefreshId = 1;
  62220. return true;
  62221. }
  62222. if (this.refreshRate === this._currentRefreshId) {
  62223. this._currentRefreshId = 1;
  62224. return true;
  62225. }
  62226. this._currentRefreshId++;
  62227. return false;
  62228. };
  62229. ProceduralTexture.prototype.getRenderSize = function () {
  62230. return this._size;
  62231. };
  62232. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62233. if (this._fallbackTextureUsed) {
  62234. return;
  62235. }
  62236. this.releaseInternalTexture();
  62237. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62238. };
  62239. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62240. if (this._uniforms.indexOf(uniformName) === -1) {
  62241. this._uniforms.push(uniformName);
  62242. }
  62243. };
  62244. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62245. if (this._samplers.indexOf(name) === -1) {
  62246. this._samplers.push(name);
  62247. }
  62248. this._textures[name] = texture;
  62249. return this;
  62250. };
  62251. ProceduralTexture.prototype.setFloat = function (name, value) {
  62252. this._checkUniform(name);
  62253. this._floats[name] = value;
  62254. return this;
  62255. };
  62256. ProceduralTexture.prototype.setFloats = function (name, value) {
  62257. this._checkUniform(name);
  62258. this._floatsArrays[name] = value;
  62259. return this;
  62260. };
  62261. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62262. this._checkUniform(name);
  62263. this._colors3[name] = value;
  62264. return this;
  62265. };
  62266. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62267. this._checkUniform(name);
  62268. this._colors4[name] = value;
  62269. return this;
  62270. };
  62271. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62272. this._checkUniform(name);
  62273. this._vectors2[name] = value;
  62274. return this;
  62275. };
  62276. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62277. this._checkUniform(name);
  62278. this._vectors3[name] = value;
  62279. return this;
  62280. };
  62281. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62282. this._checkUniform(name);
  62283. this._matrices[name] = value;
  62284. return this;
  62285. };
  62286. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62287. var scene = this.getScene();
  62288. if (!scene) {
  62289. return;
  62290. }
  62291. var engine = this._engine;
  62292. // Render
  62293. engine.enableEffect(this._effect);
  62294. engine.setState(false);
  62295. // Texture
  62296. for (var name in this._textures) {
  62297. this._effect.setTexture(name, this._textures[name]);
  62298. }
  62299. // Float
  62300. for (name in this._floats) {
  62301. this._effect.setFloat(name, this._floats[name]);
  62302. }
  62303. // Floats
  62304. for (name in this._floatsArrays) {
  62305. this._effect.setArray(name, this._floatsArrays[name]);
  62306. }
  62307. // Color3
  62308. for (name in this._colors3) {
  62309. this._effect.setColor3(name, this._colors3[name]);
  62310. }
  62311. // Color4
  62312. for (name in this._colors4) {
  62313. var color = this._colors4[name];
  62314. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62315. }
  62316. // Vector2
  62317. for (name in this._vectors2) {
  62318. this._effect.setVector2(name, this._vectors2[name]);
  62319. }
  62320. // Vector3
  62321. for (name in this._vectors3) {
  62322. this._effect.setVector3(name, this._vectors3[name]);
  62323. }
  62324. // Matrix
  62325. for (name in this._matrices) {
  62326. this._effect.setMatrix(name, this._matrices[name]);
  62327. }
  62328. if (!this._texture) {
  62329. return;
  62330. }
  62331. if (this.isCube) {
  62332. for (var face = 0; face < 6; face++) {
  62333. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62334. // VBOs
  62335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62336. this._effect.setFloat("face", face);
  62337. // Clear
  62338. engine.clear(scene.clearColor, true, true, true);
  62339. // Draw order
  62340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62341. // Mipmaps
  62342. if (face === 5) {
  62343. engine.generateMipMapsForCubemap(this._texture);
  62344. }
  62345. }
  62346. }
  62347. else {
  62348. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62349. // VBOs
  62350. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62351. // Clear
  62352. engine.clear(scene.clearColor, true, true, true);
  62353. // Draw order
  62354. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62355. }
  62356. // Unbind
  62357. engine.unBindFramebuffer(this._texture, this.isCube);
  62358. if (this.onGenerated) {
  62359. this.onGenerated();
  62360. }
  62361. };
  62362. ProceduralTexture.prototype.clone = function () {
  62363. var textureSize = this.getSize();
  62364. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62365. // Base texture
  62366. newTexture.hasAlpha = this.hasAlpha;
  62367. newTexture.level = this.level;
  62368. // RenderTarget Texture
  62369. newTexture.coordinatesMode = this.coordinatesMode;
  62370. return newTexture;
  62371. };
  62372. ProceduralTexture.prototype.dispose = function () {
  62373. var scene = this.getScene();
  62374. if (!scene) {
  62375. return;
  62376. }
  62377. var index = scene._proceduralTextures.indexOf(this);
  62378. if (index >= 0) {
  62379. scene._proceduralTextures.splice(index, 1);
  62380. }
  62381. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62382. if (vertexBuffer) {
  62383. vertexBuffer.dispose();
  62384. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62385. }
  62386. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62387. this._indexBuffer = null;
  62388. }
  62389. _super.prototype.dispose.call(this);
  62390. };
  62391. return ProceduralTexture;
  62392. }(BABYLON.Texture));
  62393. BABYLON.ProceduralTexture = ProceduralTexture;
  62394. })(BABYLON || (BABYLON = {}));
  62395. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62396. var BABYLON;
  62397. (function (BABYLON) {
  62398. var CustomProceduralTexture = /** @class */ (function (_super) {
  62399. __extends(CustomProceduralTexture, _super);
  62400. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62401. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62402. _this._animate = true;
  62403. _this._time = 0;
  62404. _this._texturePath = texturePath;
  62405. //Try to load json
  62406. _this.loadJson(texturePath);
  62407. _this.refreshRate = 1;
  62408. return _this;
  62409. }
  62410. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62411. var _this = this;
  62412. var noConfigFile = function () {
  62413. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62414. try {
  62415. _this.setFragment(_this._texturePath);
  62416. }
  62417. catch (ex) {
  62418. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62419. }
  62420. };
  62421. var configFileUrl = jsonUrl + "/config.json";
  62422. var xhr = new XMLHttpRequest();
  62423. xhr.open("GET", configFileUrl, true);
  62424. xhr.addEventListener("load", function () {
  62425. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62426. try {
  62427. _this._config = JSON.parse(xhr.response);
  62428. _this.updateShaderUniforms();
  62429. _this.updateTextures();
  62430. _this.setFragment(_this._texturePath + "/custom");
  62431. _this._animate = _this._config.animate;
  62432. _this.refreshRate = _this._config.refreshrate;
  62433. }
  62434. catch (ex) {
  62435. noConfigFile();
  62436. }
  62437. }
  62438. else {
  62439. noConfigFile();
  62440. }
  62441. }, false);
  62442. xhr.addEventListener("error", function () {
  62443. noConfigFile();
  62444. }, false);
  62445. try {
  62446. xhr.send();
  62447. }
  62448. catch (ex) {
  62449. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62450. }
  62451. };
  62452. CustomProceduralTexture.prototype.isReady = function () {
  62453. if (!_super.prototype.isReady.call(this)) {
  62454. return false;
  62455. }
  62456. for (var name in this._textures) {
  62457. var texture = this._textures[name];
  62458. if (!texture.isReady()) {
  62459. return false;
  62460. }
  62461. }
  62462. return true;
  62463. };
  62464. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62465. var scene = this.getScene();
  62466. if (this._animate && scene) {
  62467. this._time += scene.getAnimationRatio() * 0.03;
  62468. this.updateShaderUniforms();
  62469. }
  62470. _super.prototype.render.call(this, useCameraPostProcess);
  62471. };
  62472. CustomProceduralTexture.prototype.updateTextures = function () {
  62473. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62474. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62475. }
  62476. };
  62477. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62478. if (this._config) {
  62479. for (var j = 0; j < this._config.uniforms.length; j++) {
  62480. var uniform = this._config.uniforms[j];
  62481. switch (uniform.type) {
  62482. case "float":
  62483. this.setFloat(uniform.name, uniform.value);
  62484. break;
  62485. case "color3":
  62486. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62487. break;
  62488. case "color4":
  62489. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62490. break;
  62491. case "vector2":
  62492. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62493. break;
  62494. case "vector3":
  62495. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62496. break;
  62497. }
  62498. }
  62499. }
  62500. this.setFloat("time", this._time);
  62501. };
  62502. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62503. get: function () {
  62504. return this._animate;
  62505. },
  62506. set: function (value) {
  62507. this._animate = value;
  62508. },
  62509. enumerable: true,
  62510. configurable: true
  62511. });
  62512. return CustomProceduralTexture;
  62513. }(BABYLON.ProceduralTexture));
  62514. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62515. })(BABYLON || (BABYLON = {}));
  62516. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62517. var BABYLON;
  62518. (function (BABYLON) {
  62519. var FreeCameraGamepadInput = /** @class */ (function () {
  62520. function FreeCameraGamepadInput() {
  62521. this.gamepadAngularSensibility = 200;
  62522. this.gamepadMoveSensibility = 40;
  62523. // private members
  62524. this._cameraTransform = BABYLON.Matrix.Identity();
  62525. this._deltaTransform = BABYLON.Vector3.Zero();
  62526. this._vector3 = BABYLON.Vector3.Zero();
  62527. this._vector2 = BABYLON.Vector2.Zero();
  62528. }
  62529. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62530. var _this = this;
  62531. var manager = this.camera.getScene().gamepadManager;
  62532. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62533. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62534. // prioritize XBOX gamepads.
  62535. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62536. _this.gamepad = gamepad;
  62537. }
  62538. }
  62539. });
  62540. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62541. if (_this.gamepad === gamepad) {
  62542. _this.gamepad = null;
  62543. }
  62544. });
  62545. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62546. };
  62547. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62548. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62549. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62550. this.gamepad = null;
  62551. };
  62552. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62553. if (this.gamepad && this.gamepad.leftStick) {
  62554. var camera = this.camera;
  62555. var LSValues = this.gamepad.leftStick;
  62556. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62557. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62558. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62559. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62560. var RSValues = this.gamepad.rightStick;
  62561. if (RSValues) {
  62562. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62563. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62564. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62565. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62566. }
  62567. else {
  62568. RSValues = { x: 0, y: 0 };
  62569. }
  62570. if (!camera.rotationQuaternion) {
  62571. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62572. }
  62573. else {
  62574. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62575. }
  62576. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62577. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62578. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62579. camera.cameraDirection.addInPlace(this._deltaTransform);
  62580. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62581. camera.cameraRotation.addInPlace(this._vector2);
  62582. }
  62583. };
  62584. FreeCameraGamepadInput.prototype.getClassName = function () {
  62585. return "FreeCameraGamepadInput";
  62586. };
  62587. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62588. return "gamepad";
  62589. };
  62590. __decorate([
  62591. BABYLON.serialize()
  62592. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62593. __decorate([
  62594. BABYLON.serialize()
  62595. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62596. return FreeCameraGamepadInput;
  62597. }());
  62598. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62599. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62600. })(BABYLON || (BABYLON = {}));
  62601. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62602. var BABYLON;
  62603. (function (BABYLON) {
  62604. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62605. function ArcRotateCameraGamepadInput() {
  62606. this.gamepadRotationSensibility = 80;
  62607. this.gamepadMoveSensibility = 40;
  62608. }
  62609. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62610. var _this = this;
  62611. var manager = this.camera.getScene().gamepadManager;
  62612. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62613. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62614. // prioritize XBOX gamepads.
  62615. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62616. _this.gamepad = gamepad;
  62617. }
  62618. }
  62619. });
  62620. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62621. if (_this.gamepad === gamepad) {
  62622. _this.gamepad = null;
  62623. }
  62624. });
  62625. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62626. };
  62627. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62628. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62629. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62630. this.gamepad = null;
  62631. };
  62632. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62633. if (this.gamepad) {
  62634. var camera = this.camera;
  62635. var RSValues = this.gamepad.rightStick;
  62636. if (RSValues) {
  62637. if (RSValues.x != 0) {
  62638. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62639. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62640. camera.inertialAlphaOffset += normalizedRX;
  62641. }
  62642. }
  62643. if (RSValues.y != 0) {
  62644. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62645. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62646. camera.inertialBetaOffset += normalizedRY;
  62647. }
  62648. }
  62649. }
  62650. var LSValues = this.gamepad.leftStick;
  62651. if (LSValues && LSValues.y != 0) {
  62652. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62653. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62654. this.camera.inertialRadiusOffset -= normalizedLY;
  62655. }
  62656. }
  62657. }
  62658. };
  62659. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62660. return "ArcRotateCameraGamepadInput";
  62661. };
  62662. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62663. return "gamepad";
  62664. };
  62665. __decorate([
  62666. BABYLON.serialize()
  62667. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62668. __decorate([
  62669. BABYLON.serialize()
  62670. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62671. return ArcRotateCameraGamepadInput;
  62672. }());
  62673. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62674. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62675. })(BABYLON || (BABYLON = {}));
  62676. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62677. var BABYLON;
  62678. (function (BABYLON) {
  62679. var GamepadManager = /** @class */ (function () {
  62680. function GamepadManager(_scene) {
  62681. var _this = this;
  62682. this._scene = _scene;
  62683. this._babylonGamepads = [];
  62684. this._oneGamepadConnected = false;
  62685. this._isMonitoring = false;
  62686. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62687. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62688. this._gamepadEventSupported = false;
  62689. }
  62690. else {
  62691. this._gamepadEventSupported = 'GamepadEvent' in window;
  62692. this._gamepadSupport = (navigator.getGamepads ||
  62693. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62694. }
  62695. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62696. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62697. for (var i in _this._babylonGamepads) {
  62698. var gamepad = _this._babylonGamepads[i];
  62699. if (gamepad && gamepad._isConnected) {
  62700. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62701. }
  62702. }
  62703. });
  62704. this._onGamepadConnectedEvent = function (evt) {
  62705. var gamepad = evt.gamepad;
  62706. if (gamepad.index in _this._babylonGamepads) {
  62707. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62708. return;
  62709. }
  62710. }
  62711. var newGamepad;
  62712. if (_this._babylonGamepads[gamepad.index]) {
  62713. newGamepad = _this._babylonGamepads[gamepad.index];
  62714. newGamepad.browserGamepad = gamepad;
  62715. newGamepad._isConnected = true;
  62716. }
  62717. else {
  62718. newGamepad = _this._addNewGamepad(gamepad);
  62719. }
  62720. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62721. _this._startMonitoringGamepads();
  62722. };
  62723. this._onGamepadDisconnectedEvent = function (evt) {
  62724. var gamepad = evt.gamepad;
  62725. // Remove the gamepad from the list of gamepads to monitor.
  62726. for (var i in _this._babylonGamepads) {
  62727. if (_this._babylonGamepads[i].index === gamepad.index) {
  62728. var disconnectedGamepad = _this._babylonGamepads[i];
  62729. disconnectedGamepad._isConnected = false;
  62730. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62731. break;
  62732. }
  62733. }
  62734. };
  62735. if (this._gamepadSupport) {
  62736. //first add already-connected gamepads
  62737. this._updateGamepadObjects();
  62738. if (this._babylonGamepads.length) {
  62739. this._startMonitoringGamepads();
  62740. }
  62741. // Checking if the gamepad connected event is supported (like in Firefox)
  62742. if (this._gamepadEventSupported) {
  62743. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62744. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62745. }
  62746. else {
  62747. this._startMonitoringGamepads();
  62748. }
  62749. }
  62750. }
  62751. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62752. get: function () {
  62753. return this._babylonGamepads;
  62754. },
  62755. enumerable: true,
  62756. configurable: true
  62757. });
  62758. GamepadManager.prototype.getGamepadByType = function (type) {
  62759. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62760. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62761. var gamepad = _a[_i];
  62762. if (gamepad && gamepad.type === type) {
  62763. return gamepad;
  62764. }
  62765. }
  62766. return null;
  62767. };
  62768. GamepadManager.prototype.dispose = function () {
  62769. if (this._gamepadEventSupported) {
  62770. if (this._onGamepadConnectedEvent) {
  62771. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62772. }
  62773. if (this._onGamepadDisconnectedEvent) {
  62774. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62775. }
  62776. this._onGamepadConnectedEvent = null;
  62777. this._onGamepadDisconnectedEvent = null;
  62778. }
  62779. this._babylonGamepads.forEach(function (gamepad) {
  62780. gamepad.dispose();
  62781. });
  62782. this.onGamepadConnectedObservable.clear();
  62783. this.onGamepadDisconnectedObservable.clear();
  62784. this._oneGamepadConnected = false;
  62785. this._stopMonitoringGamepads();
  62786. this._babylonGamepads = [];
  62787. };
  62788. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62789. if (!this._oneGamepadConnected) {
  62790. this._oneGamepadConnected = true;
  62791. }
  62792. var newGamepad;
  62793. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62794. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62795. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62796. }
  62797. else if (gamepad.pose) {
  62798. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62799. }
  62800. else {
  62801. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62802. }
  62803. this._babylonGamepads[newGamepad.index] = newGamepad;
  62804. return newGamepad;
  62805. };
  62806. GamepadManager.prototype._startMonitoringGamepads = function () {
  62807. if (!this._isMonitoring) {
  62808. this._isMonitoring = true;
  62809. //back-comp
  62810. if (!this._scene) {
  62811. this._checkGamepadsStatus();
  62812. }
  62813. }
  62814. };
  62815. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62816. this._isMonitoring = false;
  62817. };
  62818. GamepadManager.prototype._checkGamepadsStatus = function () {
  62819. var _this = this;
  62820. // Hack to be compatible Chrome
  62821. this._updateGamepadObjects();
  62822. for (var i in this._babylonGamepads) {
  62823. var gamepad = this._babylonGamepads[i];
  62824. if (!gamepad || !gamepad.isConnected) {
  62825. continue;
  62826. }
  62827. gamepad.update();
  62828. }
  62829. if (this._isMonitoring && !this._scene) {
  62830. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62831. }
  62832. };
  62833. // This function is called only on Chrome, which does not properly support
  62834. // connection/disconnection events and forces you to recopy again the gamepad object
  62835. GamepadManager.prototype._updateGamepadObjects = function () {
  62836. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62837. for (var i = 0; i < gamepads.length; i++) {
  62838. if (gamepads[i]) {
  62839. if (!this._babylonGamepads[gamepads[i].index]) {
  62840. var newGamepad = this._addNewGamepad(gamepads[i]);
  62841. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62842. }
  62843. else {
  62844. // Forced to copy again this object for Chrome for unknown reason
  62845. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62846. if (!this._babylonGamepads[i].isConnected) {
  62847. this._babylonGamepads[i]._isConnected = true;
  62848. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62849. }
  62850. }
  62851. }
  62852. }
  62853. };
  62854. return GamepadManager;
  62855. }());
  62856. BABYLON.GamepadManager = GamepadManager;
  62857. })(BABYLON || (BABYLON = {}));
  62858. //# sourceMappingURL=babylon.gamepadManager.js.map
  62859. var BABYLON;
  62860. (function (BABYLON) {
  62861. var StickValues = /** @class */ (function () {
  62862. function StickValues(x, y) {
  62863. this.x = x;
  62864. this.y = y;
  62865. }
  62866. return StickValues;
  62867. }());
  62868. BABYLON.StickValues = StickValues;
  62869. var Gamepad = /** @class */ (function () {
  62870. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62871. if (leftStickX === void 0) { leftStickX = 0; }
  62872. if (leftStickY === void 0) { leftStickY = 1; }
  62873. if (rightStickX === void 0) { rightStickX = 2; }
  62874. if (rightStickY === void 0) { rightStickY = 3; }
  62875. this.id = id;
  62876. this.index = index;
  62877. this.browserGamepad = browserGamepad;
  62878. this._isConnected = true;
  62879. this._invertLeftStickY = false;
  62880. this.type = Gamepad.GAMEPAD;
  62881. this._leftStickAxisX = leftStickX;
  62882. this._leftStickAxisY = leftStickY;
  62883. this._rightStickAxisX = rightStickX;
  62884. this._rightStickAxisY = rightStickY;
  62885. if (this.browserGamepad.axes.length >= 2) {
  62886. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62887. }
  62888. if (this.browserGamepad.axes.length >= 4) {
  62889. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62890. }
  62891. }
  62892. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62893. get: function () {
  62894. return this._isConnected;
  62895. },
  62896. enumerable: true,
  62897. configurable: true
  62898. });
  62899. Gamepad.prototype.onleftstickchanged = function (callback) {
  62900. this._onleftstickchanged = callback;
  62901. };
  62902. Gamepad.prototype.onrightstickchanged = function (callback) {
  62903. this._onrightstickchanged = callback;
  62904. };
  62905. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62906. get: function () {
  62907. return this._leftStick;
  62908. },
  62909. set: function (newValues) {
  62910. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62911. this._onleftstickchanged(newValues);
  62912. }
  62913. this._leftStick = newValues;
  62914. },
  62915. enumerable: true,
  62916. configurable: true
  62917. });
  62918. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62919. get: function () {
  62920. return this._rightStick;
  62921. },
  62922. set: function (newValues) {
  62923. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62924. this._onrightstickchanged(newValues);
  62925. }
  62926. this._rightStick = newValues;
  62927. },
  62928. enumerable: true,
  62929. configurable: true
  62930. });
  62931. Gamepad.prototype.update = function () {
  62932. if (this._leftStick) {
  62933. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62934. if (this._invertLeftStickY) {
  62935. this.leftStick.y *= -1;
  62936. }
  62937. }
  62938. if (this._rightStick) {
  62939. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62940. }
  62941. };
  62942. Gamepad.prototype.dispose = function () {
  62943. };
  62944. Gamepad.GAMEPAD = 0;
  62945. Gamepad.GENERIC = 1;
  62946. Gamepad.XBOX = 2;
  62947. Gamepad.POSE_ENABLED = 3;
  62948. return Gamepad;
  62949. }());
  62950. BABYLON.Gamepad = Gamepad;
  62951. var GenericPad = /** @class */ (function (_super) {
  62952. __extends(GenericPad, _super);
  62953. function GenericPad(id, index, browserGamepad) {
  62954. var _this = _super.call(this, id, index, browserGamepad) || this;
  62955. _this.onButtonDownObservable = new BABYLON.Observable();
  62956. _this.onButtonUpObservable = new BABYLON.Observable();
  62957. _this.type = Gamepad.GENERIC;
  62958. _this._buttons = new Array(browserGamepad.buttons.length);
  62959. return _this;
  62960. }
  62961. GenericPad.prototype.onbuttondown = function (callback) {
  62962. this._onbuttondown = callback;
  62963. };
  62964. GenericPad.prototype.onbuttonup = function (callback) {
  62965. this._onbuttonup = callback;
  62966. };
  62967. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62968. if (newValue !== currentValue) {
  62969. if (newValue === 1) {
  62970. if (this._onbuttondown) {
  62971. this._onbuttondown(buttonIndex);
  62972. }
  62973. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62974. }
  62975. if (newValue === 0) {
  62976. if (this._onbuttonup) {
  62977. this._onbuttonup(buttonIndex);
  62978. }
  62979. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62980. }
  62981. }
  62982. return newValue;
  62983. };
  62984. GenericPad.prototype.update = function () {
  62985. _super.prototype.update.call(this);
  62986. for (var index = 0; index < this._buttons.length; index++) {
  62987. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62988. }
  62989. };
  62990. GenericPad.prototype.dispose = function () {
  62991. _super.prototype.dispose.call(this);
  62992. this.onButtonDownObservable.clear();
  62993. this.onButtonUpObservable.clear();
  62994. };
  62995. return GenericPad;
  62996. }(Gamepad));
  62997. BABYLON.GenericPad = GenericPad;
  62998. })(BABYLON || (BABYLON = {}));
  62999. //# sourceMappingURL=babylon.gamepad.js.map
  63000. var BABYLON;
  63001. (function (BABYLON) {
  63002. var Xbox360Button;
  63003. (function (Xbox360Button) {
  63004. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63005. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63006. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63007. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63008. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63009. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63010. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63011. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63012. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63013. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63014. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63015. var Xbox360Dpad;
  63016. (function (Xbox360Dpad) {
  63017. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63018. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63019. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63020. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63021. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63022. var Xbox360Pad = /** @class */ (function (_super) {
  63023. __extends(Xbox360Pad, _super);
  63024. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63025. if (xboxOne === void 0) { xboxOne = false; }
  63026. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63027. _this._leftTrigger = 0;
  63028. _this._rightTrigger = 0;
  63029. _this.onButtonDownObservable = new BABYLON.Observable();
  63030. _this.onButtonUpObservable = new BABYLON.Observable();
  63031. _this.onPadDownObservable = new BABYLON.Observable();
  63032. _this.onPadUpObservable = new BABYLON.Observable();
  63033. _this._buttonA = 0;
  63034. _this._buttonB = 0;
  63035. _this._buttonX = 0;
  63036. _this._buttonY = 0;
  63037. _this._buttonBack = 0;
  63038. _this._buttonStart = 0;
  63039. _this._buttonLB = 0;
  63040. _this._buttonRB = 0;
  63041. _this._buttonLeftStick = 0;
  63042. _this._buttonRightStick = 0;
  63043. _this._dPadUp = 0;
  63044. _this._dPadDown = 0;
  63045. _this._dPadLeft = 0;
  63046. _this._dPadRight = 0;
  63047. _this._isXboxOnePad = false;
  63048. _this.type = BABYLON.Gamepad.XBOX;
  63049. _this._isXboxOnePad = xboxOne;
  63050. return _this;
  63051. }
  63052. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63053. this._onlefttriggerchanged = callback;
  63054. };
  63055. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63056. this._onrighttriggerchanged = callback;
  63057. };
  63058. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63059. get: function () {
  63060. return this._leftTrigger;
  63061. },
  63062. set: function (newValue) {
  63063. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63064. this._onlefttriggerchanged(newValue);
  63065. }
  63066. this._leftTrigger = newValue;
  63067. },
  63068. enumerable: true,
  63069. configurable: true
  63070. });
  63071. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63072. get: function () {
  63073. return this._rightTrigger;
  63074. },
  63075. set: function (newValue) {
  63076. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63077. this._onrighttriggerchanged(newValue);
  63078. }
  63079. this._rightTrigger = newValue;
  63080. },
  63081. enumerable: true,
  63082. configurable: true
  63083. });
  63084. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63085. this._onbuttondown = callback;
  63086. };
  63087. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63088. this._onbuttonup = callback;
  63089. };
  63090. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63091. this._ondpaddown = callback;
  63092. };
  63093. Xbox360Pad.prototype.ondpadup = function (callback) {
  63094. this._ondpadup = callback;
  63095. };
  63096. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63097. if (newValue !== currentValue) {
  63098. if (newValue === 1) {
  63099. if (this._onbuttondown) {
  63100. this._onbuttondown(buttonType);
  63101. }
  63102. this.onButtonDownObservable.notifyObservers(buttonType);
  63103. }
  63104. if (newValue === 0) {
  63105. if (this._onbuttonup) {
  63106. this._onbuttonup(buttonType);
  63107. }
  63108. this.onButtonUpObservable.notifyObservers(buttonType);
  63109. }
  63110. }
  63111. return newValue;
  63112. };
  63113. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63114. if (newValue !== currentValue) {
  63115. if (newValue === 1) {
  63116. if (this._ondpaddown) {
  63117. this._ondpaddown(buttonType);
  63118. }
  63119. this.onPadDownObservable.notifyObservers(buttonType);
  63120. }
  63121. if (newValue === 0) {
  63122. if (this._ondpadup) {
  63123. this._ondpadup(buttonType);
  63124. }
  63125. this.onPadUpObservable.notifyObservers(buttonType);
  63126. }
  63127. }
  63128. return newValue;
  63129. };
  63130. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63131. get: function () {
  63132. return this._buttonA;
  63133. },
  63134. set: function (value) {
  63135. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63136. },
  63137. enumerable: true,
  63138. configurable: true
  63139. });
  63140. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63141. get: function () {
  63142. return this._buttonB;
  63143. },
  63144. set: function (value) {
  63145. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63146. },
  63147. enumerable: true,
  63148. configurable: true
  63149. });
  63150. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63151. get: function () {
  63152. return this._buttonX;
  63153. },
  63154. set: function (value) {
  63155. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63156. },
  63157. enumerable: true,
  63158. configurable: true
  63159. });
  63160. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63161. get: function () {
  63162. return this._buttonY;
  63163. },
  63164. set: function (value) {
  63165. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63166. },
  63167. enumerable: true,
  63168. configurable: true
  63169. });
  63170. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63171. get: function () {
  63172. return this._buttonStart;
  63173. },
  63174. set: function (value) {
  63175. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63176. },
  63177. enumerable: true,
  63178. configurable: true
  63179. });
  63180. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63181. get: function () {
  63182. return this._buttonBack;
  63183. },
  63184. set: function (value) {
  63185. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63191. get: function () {
  63192. return this._buttonLB;
  63193. },
  63194. set: function (value) {
  63195. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63196. },
  63197. enumerable: true,
  63198. configurable: true
  63199. });
  63200. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63201. get: function () {
  63202. return this._buttonRB;
  63203. },
  63204. set: function (value) {
  63205. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63206. },
  63207. enumerable: true,
  63208. configurable: true
  63209. });
  63210. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63211. get: function () {
  63212. return this._buttonLeftStick;
  63213. },
  63214. set: function (value) {
  63215. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63216. },
  63217. enumerable: true,
  63218. configurable: true
  63219. });
  63220. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63221. get: function () {
  63222. return this._buttonRightStick;
  63223. },
  63224. set: function (value) {
  63225. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63226. },
  63227. enumerable: true,
  63228. configurable: true
  63229. });
  63230. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63231. get: function () {
  63232. return this._dPadUp;
  63233. },
  63234. set: function (value) {
  63235. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63236. },
  63237. enumerable: true,
  63238. configurable: true
  63239. });
  63240. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63241. get: function () {
  63242. return this._dPadDown;
  63243. },
  63244. set: function (value) {
  63245. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63246. },
  63247. enumerable: true,
  63248. configurable: true
  63249. });
  63250. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63251. get: function () {
  63252. return this._dPadLeft;
  63253. },
  63254. set: function (value) {
  63255. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63256. },
  63257. enumerable: true,
  63258. configurable: true
  63259. });
  63260. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63261. get: function () {
  63262. return this._dPadRight;
  63263. },
  63264. set: function (value) {
  63265. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63266. },
  63267. enumerable: true,
  63268. configurable: true
  63269. });
  63270. Xbox360Pad.prototype.update = function () {
  63271. _super.prototype.update.call(this);
  63272. if (this._isXboxOnePad) {
  63273. this.buttonA = this.browserGamepad.buttons[0].value;
  63274. this.buttonB = this.browserGamepad.buttons[1].value;
  63275. this.buttonX = this.browserGamepad.buttons[2].value;
  63276. this.buttonY = this.browserGamepad.buttons[3].value;
  63277. this.buttonLB = this.browserGamepad.buttons[4].value;
  63278. this.buttonRB = this.browserGamepad.buttons[5].value;
  63279. this.leftTrigger = this.browserGamepad.axes[2];
  63280. this.rightTrigger = this.browserGamepad.axes[5];
  63281. this.buttonBack = this.browserGamepad.buttons[9].value;
  63282. this.buttonStart = this.browserGamepad.buttons[8].value;
  63283. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63284. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63285. this.dPadUp = this.browserGamepad.buttons[11].value;
  63286. this.dPadDown = this.browserGamepad.buttons[12].value;
  63287. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63288. this.dPadRight = this.browserGamepad.buttons[14].value;
  63289. }
  63290. else {
  63291. this.buttonA = this.browserGamepad.buttons[0].value;
  63292. this.buttonB = this.browserGamepad.buttons[1].value;
  63293. this.buttonX = this.browserGamepad.buttons[2].value;
  63294. this.buttonY = this.browserGamepad.buttons[3].value;
  63295. this.buttonLB = this.browserGamepad.buttons[4].value;
  63296. this.buttonRB = this.browserGamepad.buttons[5].value;
  63297. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63298. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63299. this.buttonBack = this.browserGamepad.buttons[8].value;
  63300. this.buttonStart = this.browserGamepad.buttons[9].value;
  63301. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63302. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63303. this.dPadUp = this.browserGamepad.buttons[12].value;
  63304. this.dPadDown = this.browserGamepad.buttons[13].value;
  63305. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63306. this.dPadRight = this.browserGamepad.buttons[15].value;
  63307. }
  63308. };
  63309. Xbox360Pad.prototype.dispose = function () {
  63310. _super.prototype.dispose.call(this);
  63311. this.onButtonDownObservable.clear();
  63312. this.onButtonUpObservable.clear();
  63313. this.onPadDownObservable.clear();
  63314. this.onPadUpObservable.clear();
  63315. };
  63316. return Xbox360Pad;
  63317. }(BABYLON.Gamepad));
  63318. BABYLON.Xbox360Pad = Xbox360Pad;
  63319. })(BABYLON || (BABYLON = {}));
  63320. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63321. var BABYLON;
  63322. (function (BABYLON) {
  63323. var PoseEnabledControllerType;
  63324. (function (PoseEnabledControllerType) {
  63325. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63326. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63327. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63328. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63329. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63330. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63331. var PoseEnabledControllerHelper = /** @class */ (function () {
  63332. function PoseEnabledControllerHelper() {
  63333. }
  63334. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63335. // Oculus Touch
  63336. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63337. return new BABYLON.OculusTouchController(vrGamepad);
  63338. }
  63339. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63340. return new BABYLON.WindowsMotionController(vrGamepad);
  63341. }
  63342. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63343. return new BABYLON.ViveController(vrGamepad);
  63344. }
  63345. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63346. return new BABYLON.GearVRController(vrGamepad);
  63347. }
  63348. else {
  63349. return new BABYLON.GenericController(vrGamepad);
  63350. }
  63351. };
  63352. return PoseEnabledControllerHelper;
  63353. }());
  63354. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63355. var PoseEnabledController = /** @class */ (function (_super) {
  63356. __extends(PoseEnabledController, _super);
  63357. function PoseEnabledController(browserGamepad) {
  63358. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63359. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63360. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63361. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63362. // Represents device position and rotation in babylon space
  63363. _this.devicePosition = BABYLON.Vector3.Zero();
  63364. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63365. _this.deviceScaleFactor = 1;
  63366. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63367. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63368. _this._workingMatrix = BABYLON.Matrix.Identity();
  63369. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63370. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63371. _this.position = BABYLON.Vector3.Zero();
  63372. _this.rotationQuaternion = new BABYLON.Quaternion();
  63373. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63374. _this._calculatedRotation = new BABYLON.Quaternion();
  63375. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63376. return _this;
  63377. }
  63378. PoseEnabledController.prototype.update = function () {
  63379. _super.prototype.update.call(this);
  63380. var pose = this.browserGamepad.pose;
  63381. this.updateFromDevice(pose);
  63382. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63383. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63384. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63385. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63386. if (this._mesh) {
  63387. this._mesh.position.copyFrom(this.devicePosition);
  63388. if (this._mesh.rotationQuaternion) {
  63389. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63390. }
  63391. }
  63392. };
  63393. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63394. if (poseData) {
  63395. this.rawPose = poseData;
  63396. if (poseData.position) {
  63397. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63398. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63399. this._deviceRoomPosition.z *= -1;
  63400. }
  63401. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63402. this._calculatedPosition.addInPlace(this.position);
  63403. }
  63404. var pose = this.rawPose;
  63405. if (poseData.orientation && pose.orientation) {
  63406. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63407. if (this._mesh) {
  63408. if (this._mesh.getScene().useRightHandedSystem) {
  63409. this._deviceRoomRotationQuaternion.z *= -1;
  63410. this._deviceRoomRotationQuaternion.w *= -1;
  63411. }
  63412. else {
  63413. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63414. }
  63415. }
  63416. // if the camera is set, rotate to the camera's rotation
  63417. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63418. }
  63419. }
  63420. };
  63421. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63422. if (this._mesh) {
  63423. this._mesh.parent = null;
  63424. }
  63425. this._mesh = mesh;
  63426. if (this._poseControlledCamera) {
  63427. this._mesh.parent = this._poseControlledCamera;
  63428. }
  63429. if (!this._mesh.rotationQuaternion) {
  63430. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63431. }
  63432. };
  63433. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63434. this._poseControlledCamera = camera;
  63435. if (this._mesh) {
  63436. this._mesh.parent = this._poseControlledCamera;
  63437. }
  63438. };
  63439. PoseEnabledController.prototype.dispose = function () {
  63440. if (this._mesh) {
  63441. this._mesh.dispose();
  63442. }
  63443. this._mesh = null;
  63444. _super.prototype.dispose.call(this);
  63445. };
  63446. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63447. get: function () {
  63448. return this._mesh;
  63449. },
  63450. enumerable: true,
  63451. configurable: true
  63452. });
  63453. PoseEnabledController.prototype.getForwardRay = function (length) {
  63454. if (length === void 0) { length = 100; }
  63455. if (!this.mesh) {
  63456. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63457. }
  63458. var m = this.mesh.getWorldMatrix();
  63459. var origin = m.getTranslation();
  63460. var forward = new BABYLON.Vector3(0, 0, -1);
  63461. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63462. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63463. return new BABYLON.Ray(origin, direction, length);
  63464. };
  63465. return PoseEnabledController;
  63466. }(BABYLON.Gamepad));
  63467. BABYLON.PoseEnabledController = PoseEnabledController;
  63468. })(BABYLON || (BABYLON = {}));
  63469. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63470. var BABYLON;
  63471. (function (BABYLON) {
  63472. var WebVRController = /** @class */ (function (_super) {
  63473. __extends(WebVRController, _super);
  63474. function WebVRController(vrGamepad) {
  63475. var _this = _super.call(this, vrGamepad) || this;
  63476. // Observables
  63477. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63478. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63479. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63480. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63481. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63482. _this.pad = { x: 0, y: 0 };
  63483. // avoid GC, store state in a tmp object
  63484. _this._changes = {
  63485. pressChanged: false,
  63486. touchChanged: false,
  63487. valueChanged: false,
  63488. changed: false
  63489. };
  63490. _this._buttons = new Array(vrGamepad.buttons.length);
  63491. _this.hand = vrGamepad.hand;
  63492. return _this;
  63493. }
  63494. WebVRController.prototype.onButtonStateChange = function (callback) {
  63495. this._onButtonStateChange = callback;
  63496. };
  63497. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63498. get: function () {
  63499. return this._defaultModel;
  63500. },
  63501. enumerable: true,
  63502. configurable: true
  63503. });
  63504. WebVRController.prototype.update = function () {
  63505. _super.prototype.update.call(this);
  63506. for (var index = 0; index < this._buttons.length; index++) {
  63507. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63508. }
  63509. ;
  63510. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63511. this.pad.x = this.leftStick.x;
  63512. this.pad.y = this.leftStick.y;
  63513. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63514. }
  63515. };
  63516. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63517. if (!newState) {
  63518. newState = {
  63519. pressed: false,
  63520. touched: false,
  63521. value: 0
  63522. };
  63523. }
  63524. if (!currentState) {
  63525. this._buttons[buttonIndex] = {
  63526. pressed: newState.pressed,
  63527. touched: newState.touched,
  63528. value: newState.value
  63529. };
  63530. return;
  63531. }
  63532. this._checkChanges(newState, currentState);
  63533. if (this._changes.changed) {
  63534. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63535. this.handleButtonChange(buttonIndex, newState, this._changes);
  63536. }
  63537. this._buttons[buttonIndex].pressed = newState.pressed;
  63538. this._buttons[buttonIndex].touched = newState.touched;
  63539. // oculus triggers are never 0, thou not touched.
  63540. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63541. };
  63542. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63543. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63544. this._changes.touchChanged = newState.touched !== currentState.touched;
  63545. this._changes.valueChanged = newState.value !== currentState.value;
  63546. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63547. return this._changes;
  63548. };
  63549. WebVRController.prototype.dispose = function () {
  63550. _super.prototype.dispose.call(this);
  63551. this.onTriggerStateChangedObservable.clear();
  63552. this.onMainButtonStateChangedObservable.clear();
  63553. this.onSecondaryButtonStateChangedObservable.clear();
  63554. this.onPadStateChangedObservable.clear();
  63555. this.onPadValuesChangedObservable.clear();
  63556. };
  63557. return WebVRController;
  63558. }(BABYLON.PoseEnabledController));
  63559. BABYLON.WebVRController = WebVRController;
  63560. })(BABYLON || (BABYLON = {}));
  63561. //# sourceMappingURL=babylon.webVRController.js.map
  63562. var BABYLON;
  63563. (function (BABYLON) {
  63564. var OculusTouchController = /** @class */ (function (_super) {
  63565. __extends(OculusTouchController, _super);
  63566. function OculusTouchController(vrGamepad) {
  63567. var _this = _super.call(this, vrGamepad) || this;
  63568. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63569. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63570. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63571. return _this;
  63572. }
  63573. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63574. var _this = this;
  63575. var meshName;
  63576. // Hand
  63577. if (this.hand === 'left') {
  63578. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63579. }
  63580. else {
  63581. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63582. }
  63583. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63584. /*
  63585. Parent Mesh name: oculus_touch_left
  63586. - body
  63587. - trigger
  63588. - thumbstick
  63589. - grip
  63590. - button_y
  63591. - button_x
  63592. - button_enter
  63593. */
  63594. _this._defaultModel = newMeshes[1];
  63595. _this.attachToMesh(_this._defaultModel);
  63596. if (meshLoaded) {
  63597. meshLoaded(_this._defaultModel);
  63598. }
  63599. });
  63600. };
  63601. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63602. // helper getters for left and right hand.
  63603. get: function () {
  63604. if (this.hand === 'right') {
  63605. return this.onMainButtonStateChangedObservable;
  63606. }
  63607. else {
  63608. throw new Error('No A button on left hand');
  63609. }
  63610. },
  63611. enumerable: true,
  63612. configurable: true
  63613. });
  63614. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63615. get: function () {
  63616. if (this.hand === 'right') {
  63617. return this.onSecondaryButtonStateChangedObservable;
  63618. }
  63619. else {
  63620. throw new Error('No B button on left hand');
  63621. }
  63622. },
  63623. enumerable: true,
  63624. configurable: true
  63625. });
  63626. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63627. get: function () {
  63628. if (this.hand === 'left') {
  63629. return this.onMainButtonStateChangedObservable;
  63630. }
  63631. else {
  63632. throw new Error('No X button on right hand');
  63633. }
  63634. },
  63635. enumerable: true,
  63636. configurable: true
  63637. });
  63638. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63639. get: function () {
  63640. if (this.hand === 'left') {
  63641. return this.onSecondaryButtonStateChangedObservable;
  63642. }
  63643. else {
  63644. throw new Error('No Y button on right hand');
  63645. }
  63646. },
  63647. enumerable: true,
  63648. configurable: true
  63649. });
  63650. /*
  63651. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63652. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63653. 2) secondary trigger (same)
  63654. 3) A (right) X (left), touch, pressed = value
  63655. 4) B / Y
  63656. 5) thumb rest
  63657. */
  63658. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63659. var notifyObject = state; //{ state: state, changes: changes };
  63660. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63661. switch (buttonIdx) {
  63662. case 0:
  63663. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63664. return;
  63665. case 1:// index trigger
  63666. if (this._defaultModel) {
  63667. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63668. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63669. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63670. }
  63671. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63672. return;
  63673. case 2:// secondary trigger
  63674. if (this._defaultModel) {
  63675. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63676. }
  63677. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63678. return;
  63679. case 3:
  63680. if (this._defaultModel) {
  63681. if (notifyObject.pressed) {
  63682. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63683. }
  63684. else {
  63685. (this._defaultModel.getChildren()[1]).position.y = 0;
  63686. }
  63687. }
  63688. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63689. return;
  63690. case 4:
  63691. if (this._defaultModel) {
  63692. if (notifyObject.pressed) {
  63693. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63694. }
  63695. else {
  63696. (this._defaultModel.getChildren()[2]).position.y = 0;
  63697. }
  63698. }
  63699. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63700. return;
  63701. case 5:
  63702. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63703. return;
  63704. }
  63705. };
  63706. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63707. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63708. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63709. return OculusTouchController;
  63710. }(BABYLON.WebVRController));
  63711. BABYLON.OculusTouchController = OculusTouchController;
  63712. })(BABYLON || (BABYLON = {}));
  63713. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63714. var BABYLON;
  63715. (function (BABYLON) {
  63716. var ViveController = /** @class */ (function (_super) {
  63717. __extends(ViveController, _super);
  63718. function ViveController(vrGamepad) {
  63719. var _this = _super.call(this, vrGamepad) || this;
  63720. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63721. _this._invertLeftStickY = true;
  63722. return _this;
  63723. }
  63724. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63725. var _this = this;
  63726. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63727. /*
  63728. Parent Mesh name: ViveWand
  63729. - body
  63730. - r_gripper
  63731. - l_gripper
  63732. - menu_button
  63733. - system_button
  63734. - trackpad
  63735. - trigger
  63736. - LED
  63737. */
  63738. _this._defaultModel = newMeshes[1];
  63739. _this.attachToMesh(_this._defaultModel);
  63740. if (meshLoaded) {
  63741. meshLoaded(_this._defaultModel);
  63742. }
  63743. });
  63744. };
  63745. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63746. get: function () {
  63747. return this.onMainButtonStateChangedObservable;
  63748. },
  63749. enumerable: true,
  63750. configurable: true
  63751. });
  63752. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63753. get: function () {
  63754. return this.onMainButtonStateChangedObservable;
  63755. },
  63756. enumerable: true,
  63757. configurable: true
  63758. });
  63759. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63760. get: function () {
  63761. return this.onSecondaryButtonStateChangedObservable;
  63762. },
  63763. enumerable: true,
  63764. configurable: true
  63765. });
  63766. /**
  63767. * Vive mapping:
  63768. * 0: touchpad
  63769. * 1: trigger
  63770. * 2: left AND right buttons
  63771. * 3: menu button
  63772. */
  63773. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63774. var notifyObject = state; //{ state: state, changes: changes };
  63775. switch (buttonIdx) {
  63776. case 0:
  63777. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63778. return;
  63779. case 1:// index trigger
  63780. if (this._defaultModel) {
  63781. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63782. }
  63783. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63784. return;
  63785. case 2:// left AND right button
  63786. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63787. return;
  63788. case 3:
  63789. if (this._defaultModel) {
  63790. if (notifyObject.pressed) {
  63791. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63792. }
  63793. else {
  63794. (this._defaultModel.getChildren()[2]).position.y = 0;
  63795. }
  63796. }
  63797. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63798. return;
  63799. }
  63800. };
  63801. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63802. ViveController.MODEL_FILENAME = 'wand.babylon';
  63803. return ViveController;
  63804. }(BABYLON.WebVRController));
  63805. BABYLON.ViveController = ViveController;
  63806. })(BABYLON || (BABYLON = {}));
  63807. //# sourceMappingURL=babylon.viveController.js.map
  63808. var BABYLON;
  63809. (function (BABYLON) {
  63810. var GenericController = /** @class */ (function (_super) {
  63811. __extends(GenericController, _super);
  63812. function GenericController(vrGamepad) {
  63813. return _super.call(this, vrGamepad) || this;
  63814. }
  63815. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63816. var _this = this;
  63817. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63818. _this._defaultModel = newMeshes[1];
  63819. _this.attachToMesh(_this._defaultModel);
  63820. if (meshLoaded) {
  63821. meshLoaded(_this._defaultModel);
  63822. }
  63823. });
  63824. };
  63825. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63826. console.log("Button id: " + buttonIdx + "state: ");
  63827. console.dir(state);
  63828. };
  63829. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63830. GenericController.MODEL_FILENAME = 'generic.babylon';
  63831. return GenericController;
  63832. }(BABYLON.WebVRController));
  63833. BABYLON.GenericController = GenericController;
  63834. })(BABYLON || (BABYLON = {}));
  63835. //# sourceMappingURL=babylon.genericController.js.map
  63836. var BABYLON;
  63837. (function (BABYLON) {
  63838. var LoadedMeshInfo = /** @class */ (function () {
  63839. function LoadedMeshInfo() {
  63840. this.buttonMeshes = {};
  63841. this.axisMeshes = {};
  63842. }
  63843. return LoadedMeshInfo;
  63844. }());
  63845. var WindowsMotionController = /** @class */ (function (_super) {
  63846. __extends(WindowsMotionController, _super);
  63847. function WindowsMotionController(vrGamepad) {
  63848. var _this = _super.call(this, vrGamepad) || this;
  63849. _this._mapping = {
  63850. // Semantic button names
  63851. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63852. // A mapping of the button name to glTF model node name
  63853. // that should be transformed by button value.
  63854. buttonMeshNames: {
  63855. 'trigger': 'SELECT',
  63856. 'menu': 'MENU',
  63857. 'grip': 'GRASP',
  63858. 'thumbstick': 'THUMBSTICK_PRESS',
  63859. 'trackpad': 'TOUCHPAD_PRESS'
  63860. },
  63861. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63862. buttonObservableNames: {
  63863. 'trigger': 'onTriggerStateChangedObservable',
  63864. 'menu': 'onSecondaryButtonStateChangedObservable',
  63865. 'grip': 'onMainButtonStateChangedObservable',
  63866. 'thumbstick': 'onPadStateChangedObservable',
  63867. 'trackpad': 'onTrackpadChangedObservable'
  63868. },
  63869. // A mapping of the axis name to glTF model node name
  63870. // that should be transformed by axis value.
  63871. // This array mirrors the browserGamepad.axes array, such that
  63872. // the mesh corresponding to axis 0 is in this array index 0.
  63873. axisMeshNames: [
  63874. 'THUMBSTICK_X',
  63875. 'THUMBSTICK_Y',
  63876. 'TOUCHPAD_TOUCH_X',
  63877. 'TOUCHPAD_TOUCH_Y'
  63878. ],
  63879. pointingPoseMeshName: 'POINTING_POSE'
  63880. };
  63881. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63882. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63883. _this.trackpad = { x: 0, y: 0 };
  63884. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63885. _this._loadedMeshInfo = null;
  63886. return _this;
  63887. }
  63888. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63889. get: function () {
  63890. return this.onTriggerStateChangedObservable;
  63891. },
  63892. enumerable: true,
  63893. configurable: true
  63894. });
  63895. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63896. get: function () {
  63897. return this.onSecondaryButtonStateChangedObservable;
  63898. },
  63899. enumerable: true,
  63900. configurable: true
  63901. });
  63902. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63903. get: function () {
  63904. return this.onMainButtonStateChangedObservable;
  63905. },
  63906. enumerable: true,
  63907. configurable: true
  63908. });
  63909. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63910. get: function () {
  63911. return this.onPadStateChangedObservable;
  63912. },
  63913. enumerable: true,
  63914. configurable: true
  63915. });
  63916. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63917. get: function () {
  63918. return this.onTrackpadChangedObservable;
  63919. },
  63920. enumerable: true,
  63921. configurable: true
  63922. });
  63923. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63924. get: function () {
  63925. return this.onTrackpadValuesChangedObservable;
  63926. },
  63927. enumerable: true,
  63928. configurable: true
  63929. });
  63930. /**
  63931. * Called once per frame by the engine.
  63932. */
  63933. WindowsMotionController.prototype.update = function () {
  63934. _super.prototype.update.call(this);
  63935. // Only need to animate axes if there is a loaded mesh
  63936. if (this._loadedMeshInfo) {
  63937. if (this.browserGamepad.axes) {
  63938. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63939. this.trackpad.x = this.browserGamepad["axes"][2];
  63940. this.trackpad.y = this.browserGamepad["axes"][3];
  63941. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63942. }
  63943. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63944. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63945. }
  63946. }
  63947. }
  63948. };
  63949. /**
  63950. * Called once for each button that changed state since the last frame
  63951. * @param buttonIdx Which button index changed
  63952. * @param state New state of the button
  63953. * @param changes Which properties on the state changed since last frame
  63954. */
  63955. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63956. var buttonName = this._mapping.buttons[buttonIdx];
  63957. if (!buttonName) {
  63958. return;
  63959. }
  63960. // Only emit events for buttons that we know how to map from index to name
  63961. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63962. if (observable) {
  63963. observable.notifyObservers(state);
  63964. }
  63965. this.lerpButtonTransform(buttonName, state.value);
  63966. };
  63967. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63968. // If there is no loaded mesh, there is nothing to transform.
  63969. if (!this._loadedMeshInfo) {
  63970. return;
  63971. }
  63972. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63973. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63974. return;
  63975. }
  63976. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63977. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63978. };
  63979. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63980. if (!this._loadedMeshInfo) {
  63981. return;
  63982. }
  63983. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63984. if (!meshInfo) {
  63985. return;
  63986. }
  63987. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63988. return;
  63989. }
  63990. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63991. var lerpValue = axisValue * 0.5 + 0.5;
  63992. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63993. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63994. };
  63995. /**
  63996. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63997. * @param scene scene in which to add meshes
  63998. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63999. */
  64000. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64001. var _this = this;
  64002. if (forceDefault === void 0) { forceDefault = false; }
  64003. var path;
  64004. var filename;
  64005. // Checking if GLB loader is present
  64006. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64007. // Determine the device specific folder based on the ID suffix
  64008. var device = 'default';
  64009. if (this.id && !forceDefault) {
  64010. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64011. device = ((match && match[0]) || device);
  64012. }
  64013. // Hand
  64014. if (this.hand === 'left') {
  64015. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64016. }
  64017. else {
  64018. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64019. }
  64020. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64021. }
  64022. else {
  64023. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64024. path = BABYLON.GenericController.MODEL_BASE_URL;
  64025. filename = BABYLON.GenericController.MODEL_FILENAME;
  64026. }
  64027. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64028. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64029. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64030. if (!_this._loadedMeshInfo) {
  64031. return;
  64032. }
  64033. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64034. _this.attachToMesh(_this._defaultModel);
  64035. if (meshLoaded) {
  64036. meshLoaded(_this._defaultModel);
  64037. }
  64038. }, null, function (scene, message) {
  64039. BABYLON.Tools.Log(message);
  64040. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64041. if (!forceDefault) {
  64042. _this.initControllerMesh(scene, meshLoaded, true);
  64043. }
  64044. });
  64045. };
  64046. /**
  64047. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64048. * can be transformed by button presses and axes values, based on this._mapping.
  64049. *
  64050. * @param scene scene in which the meshes exist
  64051. * @param meshes list of meshes that make up the controller model to process
  64052. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64053. */
  64054. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64055. var loadedMeshInfo = null;
  64056. // Create a new mesh to contain the glTF hierarchy
  64057. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64058. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64059. var childMesh = null;
  64060. for (var i = 0; i < meshes.length; i++) {
  64061. var mesh = meshes[i];
  64062. if (!mesh.parent) {
  64063. // Exclude controller meshes from picking results
  64064. mesh.isPickable = false;
  64065. // Handle root node, attach to the new parentMesh
  64066. childMesh = mesh;
  64067. break;
  64068. }
  64069. }
  64070. if (childMesh) {
  64071. childMesh.setParent(parentMesh);
  64072. // Create our mesh info. Note that this method will always return non-null.
  64073. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64074. }
  64075. else {
  64076. BABYLON.Tools.Warn('Could not find root node in model file.');
  64077. }
  64078. return loadedMeshInfo;
  64079. };
  64080. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64081. var loadedMeshInfo = new LoadedMeshInfo();
  64082. var i;
  64083. loadedMeshInfo.rootNode = rootNode;
  64084. // Reset the caches
  64085. loadedMeshInfo.buttonMeshes = {};
  64086. loadedMeshInfo.axisMeshes = {};
  64087. // Button Meshes
  64088. for (i = 0; i < this._mapping.buttons.length; i++) {
  64089. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64090. if (!buttonMeshName) {
  64091. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64092. continue;
  64093. }
  64094. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64095. if (!buttonMesh) {
  64096. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64097. continue;
  64098. }
  64099. var buttonMeshInfo = {
  64100. index: i,
  64101. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64102. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64103. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64104. };
  64105. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64106. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64107. }
  64108. else {
  64109. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64110. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64111. '(VALUE: ' + !!buttonMeshInfo.value +
  64112. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64113. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64114. ')');
  64115. }
  64116. }
  64117. // Axis Meshes
  64118. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64119. var axisMeshName = this._mapping.axisMeshNames[i];
  64120. if (!axisMeshName) {
  64121. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64122. continue;
  64123. }
  64124. var axisMesh = getChildByName(rootNode, axisMeshName);
  64125. if (!axisMesh) {
  64126. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64127. continue;
  64128. }
  64129. var axisMeshInfo = {
  64130. index: i,
  64131. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64132. min: getImmediateChildByName(axisMesh, 'MIN'),
  64133. max: getImmediateChildByName(axisMesh, 'MAX')
  64134. };
  64135. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64136. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64137. }
  64138. else {
  64139. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64140. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64141. '(VALUE: ' + !!axisMeshInfo.value +
  64142. ', MIN: ' + !!axisMeshInfo.min +
  64143. ', MAX:' + !!axisMeshInfo.max +
  64144. ')');
  64145. }
  64146. }
  64147. // Pointing Ray
  64148. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64149. if (!loadedMeshInfo.pointingPoseNode) {
  64150. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64151. }
  64152. return loadedMeshInfo;
  64153. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64154. function getChildByName(node, name) {
  64155. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64156. }
  64157. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64158. function getImmediateChildByName(node, name) {
  64159. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64160. }
  64161. };
  64162. WindowsMotionController.prototype.getForwardRay = function (length) {
  64163. if (length === void 0) { length = 100; }
  64164. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64165. return _super.prototype.getForwardRay.call(this, length);
  64166. }
  64167. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64168. var origin = m.getTranslation();
  64169. var forward = new BABYLON.Vector3(0, 0, -1);
  64170. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64171. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64172. return new BABYLON.Ray(origin, direction, length);
  64173. };
  64174. WindowsMotionController.prototype.dispose = function () {
  64175. _super.prototype.dispose.call(this);
  64176. this.onTrackpadChangedObservable.clear();
  64177. };
  64178. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64179. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64180. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64181. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64182. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64183. return WindowsMotionController;
  64184. }(BABYLON.WebVRController));
  64185. BABYLON.WindowsMotionController = WindowsMotionController;
  64186. })(BABYLON || (BABYLON = {}));
  64187. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64188. var BABYLON;
  64189. (function (BABYLON) {
  64190. var GearVRController = /** @class */ (function (_super) {
  64191. __extends(GearVRController, _super);
  64192. function GearVRController(vrGamepad) {
  64193. var _this = _super.call(this, vrGamepad) || this;
  64194. _this._buttonIndexToObservableNameMap = [
  64195. 'onTrackpadChangedObservable',
  64196. 'onTriggerStateChangedObservable' // Trigger
  64197. ];
  64198. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64199. return _this;
  64200. }
  64201. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64202. var _this = this;
  64203. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64204. _this._defaultModel = newMeshes[1];
  64205. _this.attachToMesh(_this._defaultModel);
  64206. if (meshLoaded) {
  64207. meshLoaded(_this._defaultModel);
  64208. }
  64209. });
  64210. };
  64211. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64212. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64213. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64214. // Only emit events for buttons that we know how to map from index to observable
  64215. var observable = this[observableName];
  64216. if (observable) {
  64217. observable.notifyObservers(state);
  64218. }
  64219. }
  64220. };
  64221. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64222. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64223. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64224. return GearVRController;
  64225. }(BABYLON.WebVRController));
  64226. BABYLON.GearVRController = GearVRController;
  64227. })(BABYLON || (BABYLON = {}));
  64228. //# sourceMappingURL=babylon.gearVRController.js.map
  64229. var BABYLON;
  64230. (function (BABYLON) {
  64231. var FollowCamera = /** @class */ (function (_super) {
  64232. __extends(FollowCamera, _super);
  64233. function FollowCamera(name, position, scene, lockedTarget) {
  64234. if (lockedTarget === void 0) { lockedTarget = null; }
  64235. var _this = _super.call(this, name, position, scene) || this;
  64236. _this.radius = 12;
  64237. _this.rotationOffset = 0;
  64238. _this.heightOffset = 4;
  64239. _this.cameraAcceleration = 0.05;
  64240. _this.maxCameraSpeed = 20;
  64241. _this.lockedTarget = lockedTarget;
  64242. return _this;
  64243. }
  64244. FollowCamera.prototype.getRadians = function (degrees) {
  64245. return degrees * Math.PI / 180;
  64246. };
  64247. FollowCamera.prototype.follow = function (cameraTarget) {
  64248. if (!cameraTarget)
  64249. return;
  64250. var yRotation;
  64251. if (cameraTarget.rotationQuaternion) {
  64252. var rotMatrix = new BABYLON.Matrix();
  64253. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64254. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64255. }
  64256. else {
  64257. yRotation = cameraTarget.rotation.y;
  64258. }
  64259. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64260. var targetPosition = cameraTarget.getAbsolutePosition();
  64261. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64262. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64263. var dx = targetX - this.position.x;
  64264. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64265. var dz = (targetZ) - this.position.z;
  64266. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64267. var vy = dy * this.cameraAcceleration;
  64268. var vz = dz * this.cameraAcceleration * 2;
  64269. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64270. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64271. }
  64272. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64273. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64274. }
  64275. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64276. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64277. }
  64278. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64279. this.setTarget(targetPosition);
  64280. };
  64281. FollowCamera.prototype._checkInputs = function () {
  64282. _super.prototype._checkInputs.call(this);
  64283. if (this.lockedTarget) {
  64284. this.follow(this.lockedTarget);
  64285. }
  64286. };
  64287. FollowCamera.prototype.getClassName = function () {
  64288. return "FollowCamera";
  64289. };
  64290. __decorate([
  64291. BABYLON.serialize()
  64292. ], FollowCamera.prototype, "radius", void 0);
  64293. __decorate([
  64294. BABYLON.serialize()
  64295. ], FollowCamera.prototype, "rotationOffset", void 0);
  64296. __decorate([
  64297. BABYLON.serialize()
  64298. ], FollowCamera.prototype, "heightOffset", void 0);
  64299. __decorate([
  64300. BABYLON.serialize()
  64301. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64302. __decorate([
  64303. BABYLON.serialize()
  64304. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64305. __decorate([
  64306. BABYLON.serializeAsMeshReference("lockedTargetId")
  64307. ], FollowCamera.prototype, "lockedTarget", void 0);
  64308. return FollowCamera;
  64309. }(BABYLON.TargetCamera));
  64310. BABYLON.FollowCamera = FollowCamera;
  64311. var ArcFollowCamera = /** @class */ (function (_super) {
  64312. __extends(ArcFollowCamera, _super);
  64313. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64314. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64315. _this.alpha = alpha;
  64316. _this.beta = beta;
  64317. _this.radius = radius;
  64318. _this.target = target;
  64319. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64320. _this.follow();
  64321. return _this;
  64322. }
  64323. ArcFollowCamera.prototype.follow = function () {
  64324. if (!this.target) {
  64325. return;
  64326. }
  64327. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64328. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64329. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64330. var targetPosition = this.target.getAbsolutePosition();
  64331. this.position = targetPosition.add(this._cartesianCoordinates);
  64332. this.setTarget(targetPosition);
  64333. };
  64334. ArcFollowCamera.prototype._checkInputs = function () {
  64335. _super.prototype._checkInputs.call(this);
  64336. this.follow();
  64337. };
  64338. ArcFollowCamera.prototype.getClassName = function () {
  64339. return "ArcFollowCamera";
  64340. };
  64341. return ArcFollowCamera;
  64342. }(BABYLON.TargetCamera));
  64343. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64344. })(BABYLON || (BABYLON = {}));
  64345. //# sourceMappingURL=babylon.followCamera.js.map
  64346. var BABYLON;
  64347. (function (BABYLON) {
  64348. // We're mainly based on the logic defined into the FreeCamera code
  64349. var UniversalCamera = /** @class */ (function (_super) {
  64350. __extends(UniversalCamera, _super);
  64351. //-- end properties for backward compatibility for inputs
  64352. function UniversalCamera(name, position, scene) {
  64353. var _this = _super.call(this, name, position, scene) || this;
  64354. _this.inputs.addGamepad();
  64355. return _this;
  64356. }
  64357. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64358. //-- Begin properties for backward compatibility for inputs
  64359. get: function () {
  64360. var gamepad = this.inputs.attached["gamepad"];
  64361. if (gamepad)
  64362. return gamepad.gamepadAngularSensibility;
  64363. return 0;
  64364. },
  64365. set: function (value) {
  64366. var gamepad = this.inputs.attached["gamepad"];
  64367. if (gamepad)
  64368. gamepad.gamepadAngularSensibility = value;
  64369. },
  64370. enumerable: true,
  64371. configurable: true
  64372. });
  64373. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64374. get: function () {
  64375. var gamepad = this.inputs.attached["gamepad"];
  64376. if (gamepad)
  64377. return gamepad.gamepadMoveSensibility;
  64378. return 0;
  64379. },
  64380. set: function (value) {
  64381. var gamepad = this.inputs.attached["gamepad"];
  64382. if (gamepad)
  64383. gamepad.gamepadMoveSensibility = value;
  64384. },
  64385. enumerable: true,
  64386. configurable: true
  64387. });
  64388. UniversalCamera.prototype.getClassName = function () {
  64389. return "UniversalCamera";
  64390. };
  64391. return UniversalCamera;
  64392. }(BABYLON.TouchCamera));
  64393. BABYLON.UniversalCamera = UniversalCamera;
  64394. })(BABYLON || (BABYLON = {}));
  64395. //# sourceMappingURL=babylon.universalCamera.js.map
  64396. var BABYLON;
  64397. (function (BABYLON) {
  64398. // We're mainly based on the logic defined into the FreeCamera code
  64399. var GamepadCamera = /** @class */ (function (_super) {
  64400. __extends(GamepadCamera, _super);
  64401. //-- end properties for backward compatibility for inputs
  64402. function GamepadCamera(name, position, scene) {
  64403. return _super.call(this, name, position, scene) || this;
  64404. }
  64405. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64406. //-- Begin properties for backward compatibility for inputs
  64407. get: function () {
  64408. var gamepad = this.inputs.attached["gamepad"];
  64409. if (gamepad)
  64410. return gamepad.gamepadAngularSensibility;
  64411. return 0;
  64412. },
  64413. set: function (value) {
  64414. var gamepad = this.inputs.attached["gamepad"];
  64415. if (gamepad)
  64416. gamepad.gamepadAngularSensibility = value;
  64417. },
  64418. enumerable: true,
  64419. configurable: true
  64420. });
  64421. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64422. get: function () {
  64423. var gamepad = this.inputs.attached["gamepad"];
  64424. if (gamepad)
  64425. return gamepad.gamepadMoveSensibility;
  64426. return 0;
  64427. },
  64428. set: function (value) {
  64429. var gamepad = this.inputs.attached["gamepad"];
  64430. if (gamepad)
  64431. gamepad.gamepadMoveSensibility = value;
  64432. },
  64433. enumerable: true,
  64434. configurable: true
  64435. });
  64436. GamepadCamera.prototype.getClassName = function () {
  64437. return "GamepadCamera";
  64438. };
  64439. return GamepadCamera;
  64440. }(BABYLON.UniversalCamera));
  64441. BABYLON.GamepadCamera = GamepadCamera;
  64442. })(BABYLON || (BABYLON = {}));
  64443. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64444. var BABYLON;
  64445. (function (BABYLON) {
  64446. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64447. function PostProcessRenderPipelineManager() {
  64448. this._renderPipelines = {};
  64449. }
  64450. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64451. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64452. };
  64453. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64454. if (unique === void 0) { unique = false; }
  64455. var renderPipeline = this._renderPipelines[renderPipelineName];
  64456. if (!renderPipeline) {
  64457. return;
  64458. }
  64459. renderPipeline._attachCameras(cameras, unique);
  64460. };
  64461. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64462. var renderPipeline = this._renderPipelines[renderPipelineName];
  64463. if (!renderPipeline) {
  64464. return;
  64465. }
  64466. renderPipeline._detachCameras(cameras);
  64467. };
  64468. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64469. var renderPipeline = this._renderPipelines[renderPipelineName];
  64470. if (!renderPipeline) {
  64471. return;
  64472. }
  64473. renderPipeline._enableEffect(renderEffectName, cameras);
  64474. };
  64475. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64476. var renderPipeline = this._renderPipelines[renderPipelineName];
  64477. if (!renderPipeline) {
  64478. return;
  64479. }
  64480. renderPipeline._disableEffect(renderEffectName, cameras);
  64481. };
  64482. PostProcessRenderPipelineManager.prototype.update = function () {
  64483. for (var renderPipelineName in this._renderPipelines) {
  64484. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64485. var pipeline = this._renderPipelines[renderPipelineName];
  64486. if (!pipeline.isSupported) {
  64487. pipeline.dispose();
  64488. delete this._renderPipelines[renderPipelineName];
  64489. }
  64490. else {
  64491. pipeline._update();
  64492. }
  64493. }
  64494. }
  64495. };
  64496. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64497. for (var renderPipelineName in this._renderPipelines) {
  64498. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64499. var pipeline = this._renderPipelines[renderPipelineName];
  64500. pipeline._rebuild();
  64501. }
  64502. }
  64503. };
  64504. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64505. for (var renderPipelineName in this._renderPipelines) {
  64506. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64507. var pipeline = this._renderPipelines[renderPipelineName];
  64508. pipeline.dispose();
  64509. }
  64510. }
  64511. };
  64512. return PostProcessRenderPipelineManager;
  64513. }());
  64514. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64515. })(BABYLON || (BABYLON = {}));
  64516. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64517. var BABYLON;
  64518. (function (BABYLON) {
  64519. /**
  64520. * This represents a set of one or more post processes in Babylon.
  64521. * A post process can be used to apply a shader to a texture after it is rendered.
  64522. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64523. */
  64524. var PostProcessRenderEffect = /** @class */ (function () {
  64525. /**
  64526. * Instantiates a post process render effect.
  64527. * A post process can be used to apply a shader to a texture after it is rendered.
  64528. * @param engine The engine the effect is tied to
  64529. * @param name The name of the effect
  64530. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64531. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64532. */
  64533. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64534. this._name = name;
  64535. this._singleInstance = singleInstance || true;
  64536. this._getPostProcesses = getPostProcesses;
  64537. this._cameras = {};
  64538. this._indicesForCamera = {};
  64539. this._postProcesses = {};
  64540. }
  64541. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64542. /**
  64543. * Checks if all the post processes in the effect are supported.
  64544. */
  64545. get: function () {
  64546. for (var index in this._postProcesses) {
  64547. for (var ppIndex in this._postProcesses[index]) {
  64548. if (!this._postProcesses[index][ppIndex].isSupported) {
  64549. return false;
  64550. }
  64551. }
  64552. }
  64553. return true;
  64554. },
  64555. enumerable: true,
  64556. configurable: true
  64557. });
  64558. /**
  64559. * Updates the current state of the effect
  64560. */
  64561. PostProcessRenderEffect.prototype._update = function () {
  64562. };
  64563. /**
  64564. * Attaches the effect on cameras
  64565. * @param cameras The camera to attach to.
  64566. */
  64567. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64568. var _this = this;
  64569. var cameraKey;
  64570. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64571. if (!cams) {
  64572. return;
  64573. }
  64574. for (var i = 0; i < cams.length; i++) {
  64575. var camera = cams[i];
  64576. var cameraName = camera.name;
  64577. if (this._singleInstance) {
  64578. cameraKey = 0;
  64579. }
  64580. else {
  64581. cameraKey = cameraName;
  64582. }
  64583. if (!this._postProcesses[cameraKey]) {
  64584. var postProcess = this._getPostProcesses();
  64585. if (postProcess) {
  64586. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64587. }
  64588. }
  64589. if (!this._indicesForCamera[cameraName]) {
  64590. this._indicesForCamera[cameraName] = [];
  64591. }
  64592. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64593. var index = camera.attachPostProcess(postProcess);
  64594. _this._indicesForCamera[cameraName].push(index);
  64595. });
  64596. if (!this._cameras[cameraName]) {
  64597. this._cameras[cameraName] = camera;
  64598. }
  64599. }
  64600. };
  64601. /**
  64602. * Detatches the effect on cameras
  64603. * @param cameras The camera to detatch from.
  64604. */
  64605. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64606. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64607. if (!cams) {
  64608. return;
  64609. }
  64610. for (var i = 0; i < cams.length; i++) {
  64611. var camera = cams[i];
  64612. var cameraName = camera.name;
  64613. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64614. camera.detachPostProcess(postProcess);
  64615. });
  64616. if (this._cameras[cameraName]) {
  64617. //this._indicesForCamera.splice(index, 1);
  64618. this._cameras[cameraName] = null;
  64619. }
  64620. }
  64621. };
  64622. /**
  64623. * Enables the effect on given cameras
  64624. * @param cameras The camera to enable.
  64625. */
  64626. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64627. var _this = this;
  64628. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64629. if (!cams) {
  64630. return;
  64631. }
  64632. for (var i = 0; i < cams.length; i++) {
  64633. var camera = cams[i];
  64634. var cameraName = camera.name;
  64635. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64636. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64637. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64638. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64639. });
  64640. }
  64641. }
  64642. }
  64643. };
  64644. /**
  64645. * Disables the effect on the given cameras
  64646. * @param cameras The camera to disable.
  64647. */
  64648. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64649. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64650. if (!cams) {
  64651. return;
  64652. }
  64653. for (var i = 0; i < cams.length; i++) {
  64654. var camera = cams[i];
  64655. var cameraName = camera.name;
  64656. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64657. camera.detachPostProcess(postProcess);
  64658. });
  64659. }
  64660. };
  64661. /**
  64662. * Gets a list of the post processes contained in the effect.
  64663. * @param camera The camera to get the post processes on.
  64664. * @returns The list of the post processes in the effect.
  64665. */
  64666. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64667. if (this._singleInstance) {
  64668. return this._postProcesses[0];
  64669. }
  64670. else {
  64671. if (!camera) {
  64672. return null;
  64673. }
  64674. return this._postProcesses[camera.name];
  64675. }
  64676. };
  64677. return PostProcessRenderEffect;
  64678. }());
  64679. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64680. })(BABYLON || (BABYLON = {}));
  64681. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64682. var BABYLON;
  64683. (function (BABYLON) {
  64684. var PostProcessRenderPipeline = /** @class */ (function () {
  64685. function PostProcessRenderPipeline(engine, name) {
  64686. this._name = name;
  64687. this._renderEffects = {};
  64688. this._renderEffectsForIsolatedPass = new Array();
  64689. this._cameras = [];
  64690. }
  64691. PostProcessRenderPipeline.prototype.getClassName = function () {
  64692. return "PostProcessRenderPipeline";
  64693. };
  64694. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64695. get: function () {
  64696. for (var renderEffectName in this._renderEffects) {
  64697. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64698. if (!this._renderEffects[renderEffectName].isSupported) {
  64699. return false;
  64700. }
  64701. }
  64702. }
  64703. return true;
  64704. },
  64705. enumerable: true,
  64706. configurable: true
  64707. });
  64708. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64709. this._renderEffects[renderEffect._name] = renderEffect;
  64710. };
  64711. // private
  64712. PostProcessRenderPipeline.prototype._rebuild = function () {
  64713. };
  64714. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64715. var renderEffects = this._renderEffects[renderEffectName];
  64716. if (!renderEffects) {
  64717. return;
  64718. }
  64719. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64720. };
  64721. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64722. var renderEffects = this._renderEffects[renderEffectName];
  64723. if (!renderEffects) {
  64724. return;
  64725. }
  64726. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64727. };
  64728. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64729. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64730. if (!cams) {
  64731. return;
  64732. }
  64733. var indicesToDelete = [];
  64734. var i;
  64735. for (i = 0; i < cams.length; i++) {
  64736. var camera = cams[i];
  64737. var cameraName = camera.name;
  64738. if (this._cameras.indexOf(camera) === -1) {
  64739. this._cameras[cameraName] = camera;
  64740. }
  64741. else if (unique) {
  64742. indicesToDelete.push(i);
  64743. }
  64744. }
  64745. for (i = 0; i < indicesToDelete.length; i++) {
  64746. cameras.splice(indicesToDelete[i], 1);
  64747. }
  64748. for (var renderEffectName in this._renderEffects) {
  64749. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64750. this._renderEffects[renderEffectName]._attachCameras(cams);
  64751. }
  64752. }
  64753. };
  64754. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64755. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64756. if (!cams) {
  64757. return;
  64758. }
  64759. for (var renderEffectName in this._renderEffects) {
  64760. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64761. this._renderEffects[renderEffectName]._detachCameras(cams);
  64762. }
  64763. }
  64764. for (var i = 0; i < cams.length; i++) {
  64765. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64766. }
  64767. };
  64768. PostProcessRenderPipeline.prototype._update = function () {
  64769. for (var renderEffectName in this._renderEffects) {
  64770. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64771. this._renderEffects[renderEffectName]._update();
  64772. }
  64773. }
  64774. for (var i = 0; i < this._cameras.length; i++) {
  64775. var cameraName = this._cameras[i].name;
  64776. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64777. this._renderEffectsForIsolatedPass[cameraName]._update();
  64778. }
  64779. }
  64780. };
  64781. PostProcessRenderPipeline.prototype._reset = function () {
  64782. this._renderEffects = {};
  64783. this._renderEffectsForIsolatedPass = new Array();
  64784. };
  64785. PostProcessRenderPipeline.prototype.dispose = function () {
  64786. // Must be implemented by children
  64787. };
  64788. __decorate([
  64789. BABYLON.serialize()
  64790. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64791. return PostProcessRenderPipeline;
  64792. }());
  64793. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64794. })(BABYLON || (BABYLON = {}));
  64795. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64796. var BABYLON;
  64797. (function (BABYLON) {
  64798. var DepthRenderer = /** @class */ (function () {
  64799. function DepthRenderer(scene, type) {
  64800. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64801. var _this = this;
  64802. this._scene = scene;
  64803. var engine = scene.getEngine();
  64804. // Render target
  64805. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64806. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64807. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64808. this._depthMap.refreshRate = 1;
  64809. this._depthMap.renderParticles = false;
  64810. this._depthMap.renderList = null;
  64811. // set default depth value to 1.0 (far away)
  64812. this._depthMap.onClearObservable.add(function (engine) {
  64813. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64814. });
  64815. // Custom render function
  64816. var renderSubMesh = function (subMesh) {
  64817. var mesh = subMesh.getRenderingMesh();
  64818. var scene = _this._scene;
  64819. var engine = scene.getEngine();
  64820. var material = subMesh.getMaterial();
  64821. if (!material) {
  64822. return;
  64823. }
  64824. // Culling and reverse (right handed system)
  64825. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64826. // Managing instances
  64827. var batch = mesh._getInstancesRenderList(subMesh._id);
  64828. if (batch.mustReturn) {
  64829. return;
  64830. }
  64831. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64832. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64833. engine.enableEffect(_this._effect);
  64834. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64835. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64836. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64837. // Alpha test
  64838. if (material && material.needAlphaTesting()) {
  64839. var alphaTexture = material.getAlphaTestTexture();
  64840. if (alphaTexture) {
  64841. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64842. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64843. }
  64844. }
  64845. // Bones
  64846. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64847. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64848. }
  64849. // Draw
  64850. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64851. }
  64852. };
  64853. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64854. var index;
  64855. if (depthOnlySubMeshes.length) {
  64856. engine.setColorWrite(false);
  64857. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64858. renderSubMesh(depthOnlySubMeshes.data[index]);
  64859. }
  64860. engine.setColorWrite(true);
  64861. }
  64862. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64863. renderSubMesh(opaqueSubMeshes.data[index]);
  64864. }
  64865. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64866. renderSubMesh(alphaTestSubMeshes.data[index]);
  64867. }
  64868. };
  64869. }
  64870. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64871. var material = subMesh.getMaterial();
  64872. if (material.disableDepthWrite) {
  64873. return false;
  64874. }
  64875. var defines = [];
  64876. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64877. var mesh = subMesh.getMesh();
  64878. // Alpha test
  64879. if (material && material.needAlphaTesting()) {
  64880. defines.push("#define ALPHATEST");
  64881. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64882. attribs.push(BABYLON.VertexBuffer.UVKind);
  64883. defines.push("#define UV1");
  64884. }
  64885. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64886. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64887. defines.push("#define UV2");
  64888. }
  64889. }
  64890. // Bones
  64891. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64894. if (mesh.numBoneInfluencers > 4) {
  64895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64897. }
  64898. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64899. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64900. }
  64901. else {
  64902. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64903. }
  64904. // Instances
  64905. if (useInstances) {
  64906. defines.push("#define INSTANCES");
  64907. attribs.push("world0");
  64908. attribs.push("world1");
  64909. attribs.push("world2");
  64910. attribs.push("world3");
  64911. }
  64912. // Get correct effect
  64913. var join = defines.join("\n");
  64914. if (this._cachedDefines !== join) {
  64915. this._cachedDefines = join;
  64916. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64917. }
  64918. return this._effect.isReady();
  64919. };
  64920. DepthRenderer.prototype.getDepthMap = function () {
  64921. return this._depthMap;
  64922. };
  64923. // Methods
  64924. DepthRenderer.prototype.dispose = function () {
  64925. this._depthMap.dispose();
  64926. };
  64927. return DepthRenderer;
  64928. }());
  64929. BABYLON.DepthRenderer = DepthRenderer;
  64930. })(BABYLON || (BABYLON = {}));
  64931. //# sourceMappingURL=babylon.depthRenderer.js.map
  64932. var BABYLON;
  64933. (function (BABYLON) {
  64934. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64935. __extends(SSAORenderingPipeline, _super);
  64936. /**
  64937. * @constructor
  64938. * @param {string} name - The rendering pipeline name
  64939. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64940. * @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 }
  64941. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64942. */
  64943. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64944. var _this = _super.call(this, scene.getEngine(), name) || this;
  64945. // Members
  64946. /**
  64947. * The PassPostProcess id in the pipeline that contains the original scene color
  64948. * @type {string}
  64949. */
  64950. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64951. /**
  64952. * The SSAO PostProcess id in the pipeline
  64953. * @type {string}
  64954. */
  64955. _this.SSAORenderEffect = "SSAORenderEffect";
  64956. /**
  64957. * The horizontal blur PostProcess id in the pipeline
  64958. * @type {string}
  64959. */
  64960. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64961. /**
  64962. * The vertical blur PostProcess id in the pipeline
  64963. * @type {string}
  64964. */
  64965. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64966. /**
  64967. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64968. * @type {string}
  64969. */
  64970. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64971. /**
  64972. * The output strength of the SSAO post-process. Default value is 1.0.
  64973. * @type {number}
  64974. */
  64975. _this.totalStrength = 1.0;
  64976. /**
  64977. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64978. * @type {number}
  64979. */
  64980. _this.radius = 0.0001;
  64981. /**
  64982. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64983. * Must not be equal to fallOff and superior to fallOff.
  64984. * Default value is 0.975
  64985. * @type {number}
  64986. */
  64987. _this.area = 0.0075;
  64988. /**
  64989. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64990. * Must not be equal to area and inferior to area.
  64991. * Default value is 0.0
  64992. * @type {number}
  64993. */
  64994. _this.fallOff = 0.000001;
  64995. /**
  64996. * The base color of the SSAO post-process
  64997. * The final result is "base + ssao" between [0, 1]
  64998. * @type {number}
  64999. */
  65000. _this.base = 0.5;
  65001. _this._firstUpdate = true;
  65002. _this._scene = scene;
  65003. // Set up assets
  65004. _this._createRandomTexture();
  65005. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65006. var ssaoRatio = ratio.ssaoRatio || ratio;
  65007. var combineRatio = ratio.combineRatio || ratio;
  65008. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65009. _this._createSSAOPostProcess(ssaoRatio);
  65010. _this._createBlurPostProcess(ssaoRatio);
  65011. _this._createSSAOCombinePostProcess(combineRatio);
  65012. // Set up pipeline
  65013. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65014. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65015. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65016. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65017. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65018. // Finish
  65019. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65020. if (cameras)
  65021. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65022. return _this;
  65023. }
  65024. // Public Methods
  65025. /**
  65026. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65027. */
  65028. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65029. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65030. for (var i = 0; i < this._scene.cameras.length; i++) {
  65031. var camera = this._scene.cameras[i];
  65032. this._originalColorPostProcess.dispose(camera);
  65033. this._ssaoPostProcess.dispose(camera);
  65034. this._blurHPostProcess.dispose(camera);
  65035. this._blurVPostProcess.dispose(camera);
  65036. this._ssaoCombinePostProcess.dispose(camera);
  65037. }
  65038. this._randomTexture.dispose();
  65039. if (disableDepthRender)
  65040. this._scene.disableDepthRenderer();
  65041. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65042. _super.prototype.dispose.call(this);
  65043. };
  65044. // Private Methods
  65045. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65046. var _this = this;
  65047. var size = 16;
  65048. 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);
  65049. 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);
  65050. this._blurHPostProcess.onActivateObservable.add(function () {
  65051. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65052. _this._blurHPostProcess.kernel = size * dw;
  65053. });
  65054. this._blurVPostProcess.onActivateObservable.add(function () {
  65055. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65056. _this._blurVPostProcess.kernel = size * dw;
  65057. });
  65058. };
  65059. SSAORenderingPipeline.prototype._rebuild = function () {
  65060. this._firstUpdate = true;
  65061. _super.prototype._rebuild.call(this);
  65062. };
  65063. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65064. var _this = this;
  65065. var numSamples = 16;
  65066. var sampleSphere = [
  65067. 0.5381, 0.1856, -0.4319,
  65068. 0.1379, 0.2486, 0.4430,
  65069. 0.3371, 0.5679, -0.0057,
  65070. -0.6999, -0.0451, -0.0019,
  65071. 0.0689, -0.1598, -0.8547,
  65072. 0.0560, 0.0069, -0.1843,
  65073. -0.0146, 0.1402, 0.0762,
  65074. 0.0100, -0.1924, -0.0344,
  65075. -0.3577, -0.5301, -0.4358,
  65076. -0.3169, 0.1063, 0.0158,
  65077. 0.0103, -0.5869, 0.0046,
  65078. -0.0897, -0.4940, 0.3287,
  65079. 0.7119, -0.0154, -0.0918,
  65080. -0.0533, 0.0596, -0.5411,
  65081. 0.0352, -0.0631, 0.5460,
  65082. -0.4776, 0.2847, -0.0271
  65083. ];
  65084. var samplesFactor = 1.0 / numSamples;
  65085. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65086. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65087. "area", "fallOff", "base", "range", "viewport"
  65088. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65089. this._ssaoPostProcess.onApply = function (effect) {
  65090. if (_this._firstUpdate) {
  65091. effect.setArray3("sampleSphere", sampleSphere);
  65092. effect.setFloat("samplesFactor", samplesFactor);
  65093. effect.setFloat("randTextureTiles", 4.0);
  65094. }
  65095. effect.setFloat("totalStrength", _this.totalStrength);
  65096. effect.setFloat("radius", _this.radius);
  65097. effect.setFloat("area", _this.area);
  65098. effect.setFloat("fallOff", _this.fallOff);
  65099. effect.setFloat("base", _this.base);
  65100. effect.setTexture("textureSampler", _this._depthTexture);
  65101. effect.setTexture("randomSampler", _this._randomTexture);
  65102. };
  65103. };
  65104. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65105. var _this = this;
  65106. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65107. this._ssaoCombinePostProcess.onApply = function (effect) {
  65108. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65109. };
  65110. };
  65111. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65112. var size = 512;
  65113. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65114. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65115. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65116. var context = this._randomTexture.getContext();
  65117. var rand = function (min, max) {
  65118. return Math.random() * (max - min) + min;
  65119. };
  65120. var randVector = BABYLON.Vector3.Zero();
  65121. for (var x = 0; x < size; x++) {
  65122. for (var y = 0; y < size; y++) {
  65123. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65124. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65125. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65126. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65127. context.fillRect(x, y, 1, 1);
  65128. }
  65129. }
  65130. this._randomTexture.update(false);
  65131. };
  65132. __decorate([
  65133. BABYLON.serialize()
  65134. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65135. __decorate([
  65136. BABYLON.serialize()
  65137. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65138. __decorate([
  65139. BABYLON.serialize()
  65140. ], SSAORenderingPipeline.prototype, "area", void 0);
  65141. __decorate([
  65142. BABYLON.serialize()
  65143. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65144. __decorate([
  65145. BABYLON.serialize()
  65146. ], SSAORenderingPipeline.prototype, "base", void 0);
  65147. return SSAORenderingPipeline;
  65148. }(BABYLON.PostProcessRenderPipeline));
  65149. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65150. })(BABYLON || (BABYLON = {}));
  65151. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65152. var BABYLON;
  65153. (function (BABYLON) {
  65154. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65155. __extends(SSAO2RenderingPipeline, _super);
  65156. /**
  65157. * @constructor
  65158. * @param {string} name - The rendering pipeline name
  65159. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65160. * @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 }
  65161. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65162. */
  65163. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65164. var _this = _super.call(this, scene.getEngine(), name) || this;
  65165. // Members
  65166. /**
  65167. * The PassPostProcess id in the pipeline that contains the original scene color
  65168. * @type {string}
  65169. */
  65170. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65171. /**
  65172. * The SSAO PostProcess id in the pipeline
  65173. * @type {string}
  65174. */
  65175. _this.SSAORenderEffect = "SSAORenderEffect";
  65176. /**
  65177. * The horizontal blur PostProcess id in the pipeline
  65178. * @type {string}
  65179. */
  65180. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65181. /**
  65182. * The vertical blur PostProcess id in the pipeline
  65183. * @type {string}
  65184. */
  65185. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65186. /**
  65187. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65188. * @type {string}
  65189. */
  65190. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65191. /**
  65192. * The output strength of the SSAO post-process. Default value is 1.0.
  65193. * @type {number}
  65194. */
  65195. _this.totalStrength = 1.0;
  65196. /**
  65197. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65198. * @type {number}
  65199. */
  65200. _this.maxZ = 100.0;
  65201. /**
  65202. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65203. * @type {number}
  65204. */
  65205. _this.minZAspect = 0.2;
  65206. /**
  65207. * Number of samples used for the SSAO calculations. Default value is 8
  65208. * @type {number}
  65209. */
  65210. _this._samples = 8;
  65211. /**
  65212. * Are we using bilateral blur ?
  65213. * @type {boolean}
  65214. */
  65215. _this._expensiveBlur = true;
  65216. /**
  65217. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65218. * @type {number}
  65219. */
  65220. _this.radius = 2.0;
  65221. /**
  65222. * The base color of the SSAO post-process
  65223. * The final result is "base + ssao" between [0, 1]
  65224. * @type {number}
  65225. */
  65226. _this.base = 0.1;
  65227. _this._firstUpdate = true;
  65228. _this._scene = scene;
  65229. if (!_this.isSupported) {
  65230. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65231. return _this;
  65232. }
  65233. var ssaoRatio = ratio.ssaoRatio || ratio;
  65234. var blurRatio = ratio.blurRatio || ratio;
  65235. // Set up assets
  65236. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65237. _this._createRandomTexture();
  65238. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65239. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65240. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65241. _this._createSSAOPostProcess(1.0);
  65242. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65243. _this._createSSAOCombinePostProcess(blurRatio);
  65244. // Set up pipeline
  65245. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65246. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65247. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65248. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65249. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65250. // Finish
  65251. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65252. if (cameras)
  65253. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65254. return _this;
  65255. }
  65256. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65257. get: function () {
  65258. return this._samples;
  65259. },
  65260. set: function (n) {
  65261. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65262. this._samples = n;
  65263. this._sampleSphere = this._generateHemisphere();
  65264. this._firstUpdate = true;
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65270. get: function () {
  65271. return this._expensiveBlur;
  65272. },
  65273. set: function (b) {
  65274. 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"]);
  65275. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65276. this._expensiveBlur = b;
  65277. this._firstUpdate = true;
  65278. },
  65279. enumerable: true,
  65280. configurable: true
  65281. });
  65282. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65283. /**
  65284. * Support test.
  65285. * @type {boolean}
  65286. */
  65287. get: function () {
  65288. var engine = BABYLON.Engine.LastCreatedEngine;
  65289. if (!engine) {
  65290. return false;
  65291. }
  65292. return engine.getCaps().drawBuffersExtension;
  65293. },
  65294. enumerable: true,
  65295. configurable: true
  65296. });
  65297. // Public Methods
  65298. /**
  65299. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65300. */
  65301. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65302. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65303. for (var i = 0; i < this._scene.cameras.length; i++) {
  65304. var camera = this._scene.cameras[i];
  65305. this._originalColorPostProcess.dispose(camera);
  65306. this._ssaoPostProcess.dispose(camera);
  65307. this._blurHPostProcess.dispose(camera);
  65308. this._blurVPostProcess.dispose(camera);
  65309. this._ssaoCombinePostProcess.dispose(camera);
  65310. }
  65311. this._randomTexture.dispose();
  65312. if (disableGeometryBufferRenderer)
  65313. this._scene.disableGeometryBufferRenderer();
  65314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65315. _super.prototype.dispose.call(this);
  65316. };
  65317. // Private Methods
  65318. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65319. var _this = this;
  65320. this._samplerOffsets = [];
  65321. var expensive = this.expensiveBlur;
  65322. for (var i = -8; i < 8; i++) {
  65323. this._samplerOffsets.push(i * 2 + 0.5);
  65324. }
  65325. 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");
  65326. this._blurHPostProcess.onApply = function (effect) {
  65327. if (!_this._scene.activeCamera) {
  65328. return;
  65329. }
  65330. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65331. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65332. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65333. effect.setFloat("radius", _this.radius);
  65334. effect.setTexture("depthSampler", _this._depthTexture);
  65335. if (_this._firstUpdate) {
  65336. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65337. }
  65338. };
  65339. 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");
  65340. this._blurVPostProcess.onApply = function (effect) {
  65341. if (!_this._scene.activeCamera) {
  65342. return;
  65343. }
  65344. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65345. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65346. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65347. effect.setFloat("radius", _this.radius);
  65348. effect.setTexture("depthSampler", _this._depthTexture);
  65349. if (_this._firstUpdate) {
  65350. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65351. _this._firstUpdate = false;
  65352. }
  65353. };
  65354. };
  65355. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65356. this._firstUpdate = true;
  65357. _super.prototype._rebuild.call(this);
  65358. };
  65359. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65360. var numSamples = this.samples;
  65361. var result = [];
  65362. var vector, scale;
  65363. var rand = function (min, max) {
  65364. return Math.random() * (max - min) + min;
  65365. };
  65366. var i = 0;
  65367. while (i < numSamples) {
  65368. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65369. vector.normalize();
  65370. scale = i / numSamples;
  65371. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65372. vector.scaleInPlace(scale);
  65373. result.push(vector.x, vector.y, vector.z);
  65374. i++;
  65375. }
  65376. return result;
  65377. };
  65378. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65379. var _this = this;
  65380. var numSamples = this.samples;
  65381. this._sampleSphere = this._generateHemisphere();
  65382. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65383. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65384. "base", "range", "projection", "near", "far", "texelSize",
  65385. "xViewport", "yViewport", "maxZ", "minZAspect"
  65386. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65387. this._ssaoPostProcess.onApply = function (effect) {
  65388. if (_this._firstUpdate) {
  65389. effect.setArray3("sampleSphere", _this._sampleSphere);
  65390. effect.setFloat("randTextureTiles", 4.0);
  65391. }
  65392. if (!_this._scene.activeCamera) {
  65393. return;
  65394. }
  65395. effect.setFloat("samplesFactor", 1 / _this.samples);
  65396. effect.setFloat("totalStrength", _this.totalStrength);
  65397. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65398. effect.setFloat("radius", _this.radius);
  65399. effect.setFloat("maxZ", _this.maxZ);
  65400. effect.setFloat("minZAspect", _this.minZAspect);
  65401. effect.setFloat("base", _this.base);
  65402. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65403. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65404. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65405. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65406. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65407. effect.setTexture("textureSampler", _this._depthTexture);
  65408. effect.setTexture("normalSampler", _this._normalTexture);
  65409. effect.setTexture("randomSampler", _this._randomTexture);
  65410. };
  65411. };
  65412. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65413. var _this = this;
  65414. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65415. this._ssaoCombinePostProcess.onApply = function (effect) {
  65416. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65417. };
  65418. };
  65419. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65420. var size = 512;
  65421. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65422. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65423. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65424. var context = this._randomTexture.getContext();
  65425. var rand = function (min, max) {
  65426. return Math.random() * (max - min) + min;
  65427. };
  65428. var randVector = BABYLON.Vector3.Zero();
  65429. for (var x = 0; x < size; x++) {
  65430. for (var y = 0; y < size; y++) {
  65431. randVector.x = rand(0.0, 1.0);
  65432. randVector.y = rand(0.0, 1.0);
  65433. randVector.z = 0.0;
  65434. randVector.normalize();
  65435. randVector.scaleInPlace(255);
  65436. randVector.x = Math.floor(randVector.x);
  65437. randVector.y = Math.floor(randVector.y);
  65438. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65439. context.fillRect(x, y, 1, 1);
  65440. }
  65441. }
  65442. this._randomTexture.update(false);
  65443. };
  65444. __decorate([
  65445. BABYLON.serialize()
  65446. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65447. __decorate([
  65448. BABYLON.serialize()
  65449. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65450. __decorate([
  65451. BABYLON.serialize()
  65452. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65453. __decorate([
  65454. BABYLON.serialize("samples")
  65455. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65456. __decorate([
  65457. BABYLON.serialize("expensiveBlur")
  65458. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65459. __decorate([
  65460. BABYLON.serialize()
  65461. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65462. __decorate([
  65463. BABYLON.serialize()
  65464. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65465. return SSAO2RenderingPipeline;
  65466. }(BABYLON.PostProcessRenderPipeline));
  65467. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65468. })(BABYLON || (BABYLON = {}));
  65469. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65470. // BABYLON.JS Chromatic Aberration GLSL Shader
  65471. // Author: Olivier Guyot
  65472. // Separates very slightly R, G and B colors on the edges of the screen
  65473. // Inspired by Francois Tarlier & Martins Upitis
  65474. var BABYLON;
  65475. (function (BABYLON) {
  65476. var LensRenderingPipeline = /** @class */ (function (_super) {
  65477. __extends(LensRenderingPipeline, _super);
  65478. /**
  65479. * @constructor
  65480. *
  65481. * Effect parameters are as follow:
  65482. * {
  65483. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65484. * edge_blur: number; // from 0 to x (1 for realism)
  65485. * distortion: number; // from 0 to x (1 for realism)
  65486. * grain_amount: number; // from 0 to 1
  65487. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65488. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65489. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65490. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65491. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65492. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65493. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65494. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65495. * }
  65496. * Note: if an effect parameter is unset, effect is disabled
  65497. *
  65498. * @param {string} name - The rendering pipeline name
  65499. * @param {object} parameters - An object containing all parameters (see above)
  65500. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65501. * @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)
  65502. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65503. */
  65504. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65505. if (ratio === void 0) { ratio = 1.0; }
  65506. var _this = _super.call(this, scene.getEngine(), name) || this;
  65507. // Lens effects can be of the following:
  65508. // - chromatic aberration (slight shift of RGB colors)
  65509. // - blur on the edge of the lens
  65510. // - lens distortion
  65511. // - depth-of-field blur & highlights enhancing
  65512. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65513. // - grain effect (noise or custom texture)
  65514. // Two additional texture samplers are needed:
  65515. // - depth map (for depth-of-field)
  65516. // - grain texture
  65517. /**
  65518. * The chromatic aberration PostProcess id in the pipeline
  65519. * @type {string}
  65520. */
  65521. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65522. /**
  65523. * The highlights enhancing PostProcess id in the pipeline
  65524. * @type {string}
  65525. */
  65526. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65527. /**
  65528. * The depth-of-field PostProcess id in the pipeline
  65529. * @type {string}
  65530. */
  65531. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65532. _this._scene = scene;
  65533. // Fetch texture samplers
  65534. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65535. if (parameters.grain_texture) {
  65536. _this._grainTexture = parameters.grain_texture;
  65537. }
  65538. else {
  65539. _this._createGrainTexture();
  65540. }
  65541. // save parameters
  65542. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65543. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65544. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65545. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65546. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65547. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65548. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65549. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65550. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65551. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65552. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65553. // Create effects
  65554. _this._createChromaticAberrationPostProcess(ratio);
  65555. _this._createHighlightsPostProcess(ratio);
  65556. _this._createDepthOfFieldPostProcess(ratio / 4);
  65557. // Set up pipeline
  65558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65561. if (_this._highlightsGain === -1) {
  65562. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65563. }
  65564. // Finish
  65565. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65566. if (cameras) {
  65567. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65568. }
  65569. return _this;
  65570. }
  65571. // public methods (self explanatory)
  65572. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65573. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65574. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65575. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65576. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65577. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65578. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65579. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65580. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65581. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65582. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65583. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65584. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65585. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65586. };
  65587. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65588. this._highlightsPostProcess.updateEffect();
  65589. };
  65590. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65591. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65592. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65593. this._highlightsGain = amount;
  65594. };
  65595. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65596. if (this._highlightsGain === -1) {
  65597. this._highlightsGain = 1.0;
  65598. }
  65599. this._highlightsThreshold = amount;
  65600. };
  65601. LensRenderingPipeline.prototype.disableHighlights = function () {
  65602. this._highlightsGain = -1;
  65603. };
  65604. /**
  65605. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65606. */
  65607. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65608. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65609. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65610. this._chromaticAberrationPostProcess = null;
  65611. this._highlightsPostProcess = null;
  65612. this._depthOfFieldPostProcess = null;
  65613. this._grainTexture.dispose();
  65614. if (disableDepthRender)
  65615. this._scene.disableDepthRenderer();
  65616. };
  65617. // colors shifting and distortion
  65618. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65619. var _this = this;
  65620. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65621. [], // samplers
  65622. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65623. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65624. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65625. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65626. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65627. };
  65628. };
  65629. // highlights enhancing
  65630. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65631. var _this = this;
  65632. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65633. [], // samplers
  65634. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65635. this._highlightsPostProcess.onApply = function (effect) {
  65636. effect.setFloat('gain', _this._highlightsGain);
  65637. effect.setFloat('threshold', _this._highlightsThreshold);
  65638. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65639. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65640. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65641. };
  65642. };
  65643. // colors shifting and distortion
  65644. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65645. var _this = this;
  65646. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65647. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65648. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65649. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65650. this._depthOfFieldPostProcess.onApply = function (effect) {
  65651. effect.setTexture("depthSampler", _this._depthTexture);
  65652. effect.setTexture("grainSampler", _this._grainTexture);
  65653. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65654. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65655. effect.setFloat('grain_amount', _this._grainAmount);
  65656. effect.setBool('blur_noise', _this._blurNoise);
  65657. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65658. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65659. effect.setFloat('distortion', _this._distortion);
  65660. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65661. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65662. effect.setFloat('aperture', _this._dofAperture);
  65663. effect.setFloat('darken', _this._dofDarken);
  65664. effect.setFloat('edge_blur', _this._edgeBlur);
  65665. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65666. if (_this._scene.activeCamera) {
  65667. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65668. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65669. }
  65670. };
  65671. };
  65672. // creates a black and white random noise texture, 512x512
  65673. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65674. var size = 512;
  65675. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65676. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65677. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65678. var context = this._grainTexture.getContext();
  65679. var rand = function (min, max) {
  65680. return Math.random() * (max - min) + min;
  65681. };
  65682. var value;
  65683. for (var x = 0; x < size; x++) {
  65684. for (var y = 0; y < size; y++) {
  65685. value = Math.floor(rand(0.42, 0.58) * 255);
  65686. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65687. context.fillRect(x, y, 1, 1);
  65688. }
  65689. }
  65690. this._grainTexture.update(false);
  65691. };
  65692. return LensRenderingPipeline;
  65693. }(BABYLON.PostProcessRenderPipeline));
  65694. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65695. })(BABYLON || (BABYLON = {}));
  65696. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65697. var BABYLON;
  65698. (function (BABYLON) {
  65699. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65700. __extends(StandardRenderingPipeline, _super);
  65701. /**
  65702. * @constructor
  65703. * @param {string} name - The rendering pipeline name
  65704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65705. * @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)
  65706. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65708. */
  65709. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65710. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65711. var _this = _super.call(this, scene.getEngine(), name) || this;
  65712. _this.downSampleX4PostProcess = null;
  65713. _this.brightPassPostProcess = null;
  65714. _this.blurHPostProcesses = [];
  65715. _this.blurVPostProcesses = [];
  65716. _this.textureAdderPostProcess = null;
  65717. _this.volumetricLightPostProcess = null;
  65718. _this.volumetricLightSmoothXPostProcess = null;
  65719. _this.volumetricLightSmoothYPostProcess = null;
  65720. _this.volumetricLightMergePostProces = null;
  65721. _this.volumetricLightFinalPostProcess = null;
  65722. _this.luminancePostProcess = null;
  65723. _this.luminanceDownSamplePostProcesses = [];
  65724. _this.hdrPostProcess = null;
  65725. _this.textureAdderFinalPostProcess = null;
  65726. _this.lensFlareFinalPostProcess = null;
  65727. _this.hdrFinalPostProcess = null;
  65728. _this.lensFlarePostProcess = null;
  65729. _this.lensFlareComposePostProcess = null;
  65730. _this.motionBlurPostProcess = null;
  65731. _this.depthOfFieldPostProcess = null;
  65732. // Values
  65733. _this.brightThreshold = 1.0;
  65734. _this.blurWidth = 512.0;
  65735. _this.horizontalBlur = false;
  65736. _this.exposure = 1.0;
  65737. _this.lensTexture = null;
  65738. _this.volumetricLightCoefficient = 0.2;
  65739. _this.volumetricLightPower = 4.0;
  65740. _this.volumetricLightBlurScale = 64.0;
  65741. _this.sourceLight = null;
  65742. _this.hdrMinimumLuminance = 1.0;
  65743. _this.hdrDecreaseRate = 0.5;
  65744. _this.hdrIncreaseRate = 0.5;
  65745. _this.lensColorTexture = null;
  65746. _this.lensFlareStrength = 20.0;
  65747. _this.lensFlareGhostDispersal = 1.4;
  65748. _this.lensFlareHaloWidth = 0.7;
  65749. _this.lensFlareDistortionStrength = 16.0;
  65750. _this.lensStarTexture = null;
  65751. _this.lensFlareDirtTexture = null;
  65752. _this.depthOfFieldDistance = 10.0;
  65753. _this.depthOfFieldBlurWidth = 64.0;
  65754. _this.motionStrength = 1.0;
  65755. // IAnimatable
  65756. _this.animations = [];
  65757. _this._currentDepthOfFieldSource = null;
  65758. _this._hdrCurrentLuminance = 1.0;
  65759. // Getters and setters
  65760. _this._bloomEnabled = true;
  65761. _this._depthOfFieldEnabled = false;
  65762. _this._vlsEnabled = false;
  65763. _this._lensFlareEnabled = false;
  65764. _this._hdrEnabled = false;
  65765. _this._motionBlurEnabled = false;
  65766. _this._motionBlurSamples = 64.0;
  65767. _this._volumetricLightStepsCount = 50.0;
  65768. _this._cameras = cameras || [];
  65769. // Initialize
  65770. _this._scene = scene;
  65771. _this._basePostProcess = originalPostProcess;
  65772. _this._ratio = ratio;
  65773. // Misc
  65774. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65775. // Finish
  65776. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65777. _this._buildPipeline();
  65778. return _this;
  65779. }
  65780. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65781. get: function () {
  65782. return this._bloomEnabled;
  65783. },
  65784. set: function (enabled) {
  65785. if (this._bloomEnabled === enabled) {
  65786. return;
  65787. }
  65788. this._bloomEnabled = enabled;
  65789. this._buildPipeline();
  65790. },
  65791. enumerable: true,
  65792. configurable: true
  65793. });
  65794. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65795. get: function () {
  65796. return this._depthOfFieldEnabled;
  65797. },
  65798. set: function (enabled) {
  65799. if (this._depthOfFieldEnabled === enabled) {
  65800. return;
  65801. }
  65802. this._depthOfFieldEnabled = enabled;
  65803. this._buildPipeline();
  65804. },
  65805. enumerable: true,
  65806. configurable: true
  65807. });
  65808. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65809. get: function () {
  65810. return this._lensFlareEnabled;
  65811. },
  65812. set: function (enabled) {
  65813. if (this._lensFlareEnabled === enabled) {
  65814. return;
  65815. }
  65816. this._lensFlareEnabled = enabled;
  65817. this._buildPipeline();
  65818. },
  65819. enumerable: true,
  65820. configurable: true
  65821. });
  65822. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65823. get: function () {
  65824. return this._hdrEnabled;
  65825. },
  65826. set: function (enabled) {
  65827. if (this._hdrEnabled === enabled) {
  65828. return;
  65829. }
  65830. this._hdrEnabled = enabled;
  65831. this._buildPipeline();
  65832. },
  65833. enumerable: true,
  65834. configurable: true
  65835. });
  65836. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65837. get: function () {
  65838. return this._vlsEnabled;
  65839. },
  65840. set: function (enabled) {
  65841. if (this._vlsEnabled === enabled) {
  65842. return;
  65843. }
  65844. if (enabled) {
  65845. var geometry = this._scene.enableGeometryBufferRenderer();
  65846. if (!geometry) {
  65847. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65848. return;
  65849. }
  65850. }
  65851. this._vlsEnabled = enabled;
  65852. this._buildPipeline();
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65858. get: function () {
  65859. return this._motionBlurEnabled;
  65860. },
  65861. set: function (enabled) {
  65862. if (this._motionBlurEnabled === enabled) {
  65863. return;
  65864. }
  65865. this._motionBlurEnabled = enabled;
  65866. this._buildPipeline();
  65867. },
  65868. enumerable: true,
  65869. configurable: true
  65870. });
  65871. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65872. get: function () {
  65873. return this._volumetricLightStepsCount;
  65874. },
  65875. set: function (count) {
  65876. if (this.volumetricLightPostProcess) {
  65877. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65878. }
  65879. this._volumetricLightStepsCount = count;
  65880. },
  65881. enumerable: true,
  65882. configurable: true
  65883. });
  65884. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65885. get: function () {
  65886. return this._motionBlurSamples;
  65887. },
  65888. set: function (samples) {
  65889. if (this.motionBlurPostProcess) {
  65890. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65891. }
  65892. this._motionBlurSamples = samples;
  65893. },
  65894. enumerable: true,
  65895. configurable: true
  65896. });
  65897. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65898. var _this = this;
  65899. var ratio = this._ratio;
  65900. var scene = this._scene;
  65901. this._disposePostProcesses();
  65902. this._reset();
  65903. // Create pass post-process
  65904. if (!this._basePostProcess) {
  65905. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65906. this.originalPostProcess.onApply = function (effect) {
  65907. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65908. };
  65909. }
  65910. else {
  65911. this.originalPostProcess = this._basePostProcess;
  65912. }
  65913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65914. this._currentDepthOfFieldSource = this.originalPostProcess;
  65915. if (this._vlsEnabled) {
  65916. // Create volumetric light
  65917. this._createVolumetricLightPostProcess(scene, ratio);
  65918. // Create volumetric light final post-process
  65919. 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);
  65920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65921. }
  65922. if (this._bloomEnabled) {
  65923. // Create down sample X4 post-process
  65924. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65925. // Create bright pass post-process
  65926. this._createBrightPassPostProcess(scene, ratio / 2);
  65927. // Create gaussian blur post-processes (down sampling blurs)
  65928. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65929. // Create texture adder post-process
  65930. this._createTextureAdderPostProcess(scene, ratio);
  65931. // Create depth-of-field source post-process
  65932. 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);
  65933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65934. }
  65935. if (this._lensFlareEnabled) {
  65936. // Create lens flare post-process
  65937. this._createLensFlarePostProcess(scene, ratio);
  65938. // Create depth-of-field source post-process post lens-flare and disable it now
  65939. 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);
  65940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65941. }
  65942. if (this._hdrEnabled) {
  65943. // Create luminance
  65944. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65945. // Create HDR
  65946. this._createHdrPostProcess(scene, ratio);
  65947. // Create depth-of-field source post-process post hdr and disable it now
  65948. 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);
  65949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65950. }
  65951. if (this._depthOfFieldEnabled) {
  65952. // Create gaussian blur used by depth-of-field
  65953. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65954. // Create depth-of-field post-process
  65955. this._createDepthOfFieldPostProcess(scene, ratio);
  65956. }
  65957. if (this._motionBlurEnabled) {
  65958. // Create motion blur post-process
  65959. this._createMotionBlurPostProcess(scene, ratio);
  65960. }
  65961. if (this._cameras !== null) {
  65962. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65963. }
  65964. };
  65965. // Down Sample X4 Post-Processs
  65966. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65967. var _this = this;
  65968. var downSampleX4Offsets = new Array(32);
  65969. 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);
  65970. this.downSampleX4PostProcess.onApply = function (effect) {
  65971. var id = 0;
  65972. var width = _this.downSampleX4PostProcess.width;
  65973. var height = _this.downSampleX4PostProcess.height;
  65974. for (var i = -2; i < 2; i++) {
  65975. for (var j = -2; j < 2; j++) {
  65976. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65977. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65978. id += 2;
  65979. }
  65980. }
  65981. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65982. };
  65983. // Add to pipeline
  65984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65985. };
  65986. // Brightpass Post-Process
  65987. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65988. var _this = this;
  65989. var brightOffsets = new Array(8);
  65990. 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);
  65991. this.brightPassPostProcess.onApply = function (effect) {
  65992. var sU = (1.0 / _this.brightPassPostProcess.width);
  65993. var sV = (1.0 / _this.brightPassPostProcess.height);
  65994. brightOffsets[0] = -0.5 * sU;
  65995. brightOffsets[1] = 0.5 * sV;
  65996. brightOffsets[2] = 0.5 * sU;
  65997. brightOffsets[3] = 0.5 * sV;
  65998. brightOffsets[4] = -0.5 * sU;
  65999. brightOffsets[5] = -0.5 * sV;
  66000. brightOffsets[6] = 0.5 * sU;
  66001. brightOffsets[7] = -0.5 * sV;
  66002. effect.setArray2("dsOffsets", brightOffsets);
  66003. effect.setFloat("brightThreshold", _this.brightThreshold);
  66004. };
  66005. // Add to pipeline
  66006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66007. };
  66008. // Create blur H&V post-processes
  66009. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66010. var _this = this;
  66011. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66012. var engine = scene.getEngine();
  66013. 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);
  66014. 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);
  66015. blurX.onActivateObservable.add(function () {
  66016. var dw = blurX.width / engine.getRenderWidth();
  66017. blurX.kernel = _this[blurWidthKey] * dw;
  66018. });
  66019. blurY.onActivateObservable.add(function () {
  66020. var dw = blurY.height / engine.getRenderHeight();
  66021. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66022. });
  66023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66025. this.blurHPostProcesses.push(blurX);
  66026. this.blurVPostProcesses.push(blurY);
  66027. };
  66028. // Create texture adder post-process
  66029. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66030. var _this = this;
  66031. 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);
  66032. this.textureAdderPostProcess.onApply = function (effect) {
  66033. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66034. effect.setTexture("lensSampler", _this.lensTexture);
  66035. effect.setFloat("exposure", _this.exposure);
  66036. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66037. };
  66038. // Add to pipeline
  66039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66040. };
  66041. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66042. var _this = this;
  66043. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66044. geometryRenderer.enablePosition = true;
  66045. var geometry = geometryRenderer.getGBuffer();
  66046. // Base post-process
  66047. 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));
  66048. var depthValues = BABYLON.Vector2.Zero();
  66049. this.volumetricLightPostProcess.onApply = function (effect) {
  66050. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66051. var generator = _this.sourceLight.getShadowGenerator();
  66052. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66053. effect.setTexture("positionSampler", geometry.textures[2]);
  66054. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66055. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66056. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66057. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66058. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66059. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66060. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66061. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66062. effect.setVector2("depthValues", depthValues);
  66063. }
  66064. };
  66065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66066. // Smooth
  66067. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66068. // Merge
  66069. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66070. this.volumetricLightMergePostProces.onApply = function (effect) {
  66071. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66072. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66073. };
  66074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66075. };
  66076. // Create luminance
  66077. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66078. var _this = this;
  66079. // Create luminance
  66080. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66081. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66082. var offsets = [];
  66083. this.luminancePostProcess.onApply = function (effect) {
  66084. var sU = (1.0 / _this.luminancePostProcess.width);
  66085. var sV = (1.0 / _this.luminancePostProcess.height);
  66086. offsets[0] = -0.5 * sU;
  66087. offsets[1] = 0.5 * sV;
  66088. offsets[2] = 0.5 * sU;
  66089. offsets[3] = 0.5 * sV;
  66090. offsets[4] = -0.5 * sU;
  66091. offsets[5] = -0.5 * sV;
  66092. offsets[6] = 0.5 * sU;
  66093. offsets[7] = -0.5 * sV;
  66094. effect.setArray2("lumOffsets", offsets);
  66095. };
  66096. // Add to pipeline
  66097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66098. // Create down sample luminance
  66099. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66100. var size = Math.pow(3, i);
  66101. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66102. if (i === 0) {
  66103. defines += "#define FINAL_DOWN_SAMPLER";
  66104. }
  66105. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66106. this.luminanceDownSamplePostProcesses.push(postProcess);
  66107. }
  66108. // Create callbacks and add effects
  66109. var lastLuminance = this.luminancePostProcess;
  66110. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66111. var downSampleOffsets = new Array(18);
  66112. pp.onApply = function (effect) {
  66113. if (!lastLuminance) {
  66114. return;
  66115. }
  66116. var id = 0;
  66117. for (var x = -1; x < 2; x++) {
  66118. for (var y = -1; y < 2; y++) {
  66119. downSampleOffsets[id] = x / lastLuminance.width;
  66120. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66121. id += 2;
  66122. }
  66123. }
  66124. effect.setArray2("dsOffsets", downSampleOffsets);
  66125. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66126. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66127. lastLuminance = _this.luminancePostProcess;
  66128. }
  66129. else {
  66130. lastLuminance = pp;
  66131. }
  66132. };
  66133. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66134. pp.onAfterRender = function (effect) {
  66135. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66136. 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);
  66137. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66138. };
  66139. }
  66140. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66141. });
  66142. };
  66143. // Create HDR post-process
  66144. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66145. var _this = this;
  66146. 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);
  66147. var outputLiminance = 1;
  66148. var time = 0;
  66149. var lastTime = 0;
  66150. this.hdrPostProcess.onApply = function (effect) {
  66151. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66152. time += scene.getEngine().getDeltaTime();
  66153. if (outputLiminance < 0) {
  66154. outputLiminance = _this._hdrCurrentLuminance;
  66155. }
  66156. else {
  66157. var dt = (lastTime - time) / 1000.0;
  66158. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66159. outputLiminance += _this.hdrDecreaseRate * dt;
  66160. }
  66161. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66162. outputLiminance -= _this.hdrIncreaseRate * dt;
  66163. }
  66164. else {
  66165. outputLiminance = _this._hdrCurrentLuminance;
  66166. }
  66167. }
  66168. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66169. effect.setFloat("averageLuminance", outputLiminance);
  66170. lastTime = time;
  66171. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66172. };
  66173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66174. };
  66175. // Create lens flare post-process
  66176. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66177. var _this = this;
  66178. 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);
  66179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66180. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66181. 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);
  66182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66183. var resolution = new BABYLON.Vector2(0, 0);
  66184. // Lens flare
  66185. this.lensFlarePostProcess.onApply = function (effect) {
  66186. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66187. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66188. effect.setFloat("strength", _this.lensFlareStrength);
  66189. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66190. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66191. // Shift
  66192. resolution.x = _this.lensFlarePostProcess.width;
  66193. resolution.y = _this.lensFlarePostProcess.height;
  66194. effect.setVector2("resolution", resolution);
  66195. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66196. };
  66197. // Compose
  66198. 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);
  66199. 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);
  66200. this.lensFlareComposePostProcess.onApply = function (effect) {
  66201. if (!_this._scene.activeCamera) {
  66202. return;
  66203. }
  66204. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66205. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66206. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66207. // Lens start rotation matrix
  66208. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66209. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66210. 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));
  66211. camRot *= 4.0;
  66212. 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);
  66213. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66214. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66215. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66216. };
  66217. };
  66218. // Create depth-of-field post-process
  66219. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66220. var _this = this;
  66221. 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);
  66222. this.depthOfFieldPostProcess.onApply = function (effect) {
  66223. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66224. effect.setTexture("depthSampler", _this._getDepthTexture());
  66225. effect.setFloat("distance", _this.depthOfFieldDistance);
  66226. };
  66227. // Add to pipeline
  66228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66229. };
  66230. // Create motion blur post-process
  66231. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66232. var _this = this;
  66233. 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);
  66234. var motionScale = 0;
  66235. var prevViewProjection = BABYLON.Matrix.Identity();
  66236. var invViewProjection = BABYLON.Matrix.Identity();
  66237. var viewProjection = BABYLON.Matrix.Identity();
  66238. var screenSize = BABYLON.Vector2.Zero();
  66239. this.motionBlurPostProcess.onApply = function (effect) {
  66240. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66241. viewProjection.invertToRef(invViewProjection);
  66242. effect.setMatrix("inverseViewProjection", invViewProjection);
  66243. effect.setMatrix("prevViewProjection", prevViewProjection);
  66244. prevViewProjection = viewProjection;
  66245. screenSize.x = _this.motionBlurPostProcess.width;
  66246. screenSize.y = _this.motionBlurPostProcess.height;
  66247. effect.setVector2("screenSize", screenSize);
  66248. motionScale = scene.getEngine().getFps() / 60.0;
  66249. effect.setFloat("motionScale", motionScale);
  66250. effect.setFloat("motionStrength", _this.motionStrength);
  66251. effect.setTexture("depthSampler", _this._getDepthTexture());
  66252. };
  66253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66254. };
  66255. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66256. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66257. var renderer = this._scene.enableGeometryBufferRenderer();
  66258. return renderer.getGBuffer().textures[0];
  66259. }
  66260. return this._scene.enableDepthRenderer().getDepthMap();
  66261. };
  66262. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66263. for (var i = 0; i < this._cameras.length; i++) {
  66264. var camera = this._cameras[i];
  66265. if (this.originalPostProcess) {
  66266. this.originalPostProcess.dispose(camera);
  66267. }
  66268. if (this.downSampleX4PostProcess) {
  66269. this.downSampleX4PostProcess.dispose(camera);
  66270. }
  66271. if (this.brightPassPostProcess) {
  66272. this.brightPassPostProcess.dispose(camera);
  66273. }
  66274. if (this.textureAdderPostProcess) {
  66275. this.textureAdderPostProcess.dispose(camera);
  66276. }
  66277. if (this.textureAdderFinalPostProcess) {
  66278. this.textureAdderFinalPostProcess.dispose(camera);
  66279. }
  66280. if (this.volumetricLightPostProcess) {
  66281. this.volumetricLightPostProcess.dispose(camera);
  66282. }
  66283. if (this.volumetricLightSmoothXPostProcess) {
  66284. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66285. }
  66286. if (this.volumetricLightSmoothYPostProcess) {
  66287. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66288. }
  66289. if (this.volumetricLightMergePostProces) {
  66290. this.volumetricLightMergePostProces.dispose(camera);
  66291. }
  66292. if (this.volumetricLightFinalPostProcess) {
  66293. this.volumetricLightFinalPostProcess.dispose(camera);
  66294. }
  66295. if (this.lensFlarePostProcess) {
  66296. this.lensFlarePostProcess.dispose(camera);
  66297. }
  66298. if (this.lensFlareComposePostProcess) {
  66299. this.lensFlareComposePostProcess.dispose(camera);
  66300. }
  66301. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66302. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66303. }
  66304. if (this.luminancePostProcess) {
  66305. this.luminancePostProcess.dispose(camera);
  66306. }
  66307. if (this.hdrPostProcess) {
  66308. this.hdrPostProcess.dispose(camera);
  66309. }
  66310. if (this.hdrFinalPostProcess) {
  66311. this.hdrFinalPostProcess.dispose(camera);
  66312. }
  66313. if (this.depthOfFieldPostProcess) {
  66314. this.depthOfFieldPostProcess.dispose(camera);
  66315. }
  66316. if (this.motionBlurPostProcess) {
  66317. this.motionBlurPostProcess.dispose(camera);
  66318. }
  66319. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66320. this.blurHPostProcesses[j].dispose(camera);
  66321. }
  66322. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66323. this.blurVPostProcesses[j].dispose(camera);
  66324. }
  66325. }
  66326. this.originalPostProcess = null;
  66327. this.downSampleX4PostProcess = null;
  66328. this.brightPassPostProcess = null;
  66329. this.textureAdderPostProcess = null;
  66330. this.textureAdderFinalPostProcess = null;
  66331. this.volumetricLightPostProcess = null;
  66332. this.volumetricLightSmoothXPostProcess = null;
  66333. this.volumetricLightSmoothYPostProcess = null;
  66334. this.volumetricLightMergePostProces = null;
  66335. this.volumetricLightFinalPostProcess = null;
  66336. this.lensFlarePostProcess = null;
  66337. this.lensFlareComposePostProcess = null;
  66338. this.luminancePostProcess = null;
  66339. this.hdrPostProcess = null;
  66340. this.hdrFinalPostProcess = null;
  66341. this.depthOfFieldPostProcess = null;
  66342. this.motionBlurPostProcess = null;
  66343. this.luminanceDownSamplePostProcesses = [];
  66344. this.blurHPostProcesses = [];
  66345. this.blurVPostProcesses = [];
  66346. };
  66347. // Dispose
  66348. StandardRenderingPipeline.prototype.dispose = function () {
  66349. this._disposePostProcesses();
  66350. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66351. _super.prototype.dispose.call(this);
  66352. };
  66353. // Serialize rendering pipeline
  66354. StandardRenderingPipeline.prototype.serialize = function () {
  66355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66356. serializationObject.customType = "StandardRenderingPipeline";
  66357. return serializationObject;
  66358. };
  66359. /**
  66360. * Static members
  66361. */
  66362. // Parse serialized pipeline
  66363. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66364. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66365. };
  66366. // Luminance steps
  66367. StandardRenderingPipeline.LuminanceSteps = 6;
  66368. __decorate([
  66369. BABYLON.serialize()
  66370. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66371. __decorate([
  66372. BABYLON.serialize()
  66373. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66374. __decorate([
  66375. BABYLON.serialize()
  66376. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66377. __decorate([
  66378. BABYLON.serialize()
  66379. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66380. __decorate([
  66381. BABYLON.serializeAsTexture("lensTexture")
  66382. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66383. __decorate([
  66384. BABYLON.serialize()
  66385. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66386. __decorate([
  66387. BABYLON.serialize()
  66388. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66389. __decorate([
  66390. BABYLON.serialize()
  66391. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66392. __decorate([
  66393. BABYLON.serialize()
  66394. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66395. __decorate([
  66396. BABYLON.serialize()
  66397. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66398. __decorate([
  66399. BABYLON.serialize()
  66400. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66401. __decorate([
  66402. BABYLON.serializeAsTexture("lensColorTexture")
  66403. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66404. __decorate([
  66405. BABYLON.serialize()
  66406. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66407. __decorate([
  66408. BABYLON.serialize()
  66409. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66410. __decorate([
  66411. BABYLON.serialize()
  66412. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66413. __decorate([
  66414. BABYLON.serialize()
  66415. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66416. __decorate([
  66417. BABYLON.serializeAsTexture("lensStarTexture")
  66418. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66419. __decorate([
  66420. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66421. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66422. __decorate([
  66423. BABYLON.serialize()
  66424. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66425. __decorate([
  66426. BABYLON.serialize()
  66427. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66428. __decorate([
  66429. BABYLON.serialize()
  66430. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66431. __decorate([
  66432. BABYLON.serialize()
  66433. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66434. __decorate([
  66435. BABYLON.serialize()
  66436. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66437. __decorate([
  66438. BABYLON.serialize()
  66439. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66440. __decorate([
  66441. BABYLON.serialize()
  66442. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66443. __decorate([
  66444. BABYLON.serialize()
  66445. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66446. __decorate([
  66447. BABYLON.serialize()
  66448. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66449. __decorate([
  66450. BABYLON.serialize()
  66451. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66452. __decorate([
  66453. BABYLON.serialize()
  66454. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66455. __decorate([
  66456. BABYLON.serialize()
  66457. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66458. return StandardRenderingPipeline;
  66459. }(BABYLON.PostProcessRenderPipeline));
  66460. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66461. })(BABYLON || (BABYLON = {}));
  66462. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66463. var BABYLON;
  66464. (function (BABYLON) {
  66465. var FxaaPostProcess = /** @class */ (function (_super) {
  66466. __extends(FxaaPostProcess, _super);
  66467. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66468. if (camera === void 0) { camera = null; }
  66469. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66470. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66471. _this.onApplyObservable.add(function (effect) {
  66472. var texelSize = _this.texelSize;
  66473. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66474. });
  66475. return _this;
  66476. }
  66477. return FxaaPostProcess;
  66478. }(BABYLON.PostProcess));
  66479. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66480. })(BABYLON || (BABYLON = {}));
  66481. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66482. var BABYLON;
  66483. (function (BABYLON) {
  66484. /**
  66485. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66486. */
  66487. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66488. __extends(CircleOfConfusionPostProcess, _super);
  66489. /**
  66490. * Creates a new instance of @see CircleOfConfusionPostProcess
  66491. * @param name The name of the effect.
  66492. * @param scene The scene the effect belongs to.
  66493. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66494. * @param options The required width/height ratio to downsize to before computing the render pass.
  66495. * @param camera The camera to apply the render pass to.
  66496. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66497. * @param engine The engine which the post process will be applied. (default: current engine)
  66498. * @param reusable If the post process can be reused on the same frame. (default: false)
  66499. * @param textureType Type of textures used when performing the post process. (default: 0)
  66500. */
  66501. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66502. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66503. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66504. /**
  66505. * 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.
  66506. */
  66507. _this.lensSize = 50;
  66508. /**
  66509. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66510. */
  66511. _this.fStop = 1.4;
  66512. /**
  66513. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66514. */
  66515. _this.focusDistance = 2000;
  66516. /**
  66517. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66518. */
  66519. _this.focalLength = 50;
  66520. _this.onApplyObservable.add(function (effect) {
  66521. effect.setTexture("depthSampler", depthTexture);
  66522. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66523. var aperture = _this.lensSize / _this.fStop;
  66524. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66525. effect.setFloat('focusDistance', _this.focusDistance);
  66526. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66527. if (scene.activeCamera) {
  66528. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66529. }
  66530. });
  66531. return _this;
  66532. }
  66533. return CircleOfConfusionPostProcess;
  66534. }(BABYLON.PostProcess));
  66535. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66536. })(BABYLON || (BABYLON = {}));
  66537. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66538. var BABYLON;
  66539. (function (BABYLON) {
  66540. /**
  66541. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66542. */
  66543. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66544. __extends(DepthOfFieldMergePostProcess, _super);
  66545. /**
  66546. * Creates a new instance of @see CircleOfConfusionPostProcess
  66547. * @param name The name of the effect.
  66548. * @param original The non-blurred image to be modified
  66549. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66550. * @param blurSteps Incrimental bluring post processes.
  66551. * @param options The required width/height ratio to downsize to before computing the render pass.
  66552. * @param camera The camera to apply the render pass to.
  66553. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66554. * @param engine The engine which the post process will be applied. (default: current engine)
  66555. * @param reusable If the post process can be reused on the same frame. (default: false)
  66556. * @param textureType Type of textures used when performing the post process. (default: 0)
  66557. */
  66558. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66559. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66560. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66561. _this.onApplyObservable.add(function (effect) {
  66562. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66563. effect.setTextureFromPostProcess("originalSampler", original);
  66564. blurSteps.forEach(function (step, index) {
  66565. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66566. });
  66567. });
  66568. return _this;
  66569. }
  66570. return DepthOfFieldMergePostProcess;
  66571. }(BABYLON.PostProcess));
  66572. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66573. })(BABYLON || (BABYLON = {}));
  66574. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66575. var BABYLON;
  66576. (function (BABYLON) {
  66577. /**
  66578. * Specifies the level of max blur that should be applied when using the depth of field effect
  66579. */
  66580. var DepthOfFieldEffectBlurLevel;
  66581. (function (DepthOfFieldEffectBlurLevel) {
  66582. /**
  66583. * Subtle blur
  66584. */
  66585. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66586. /**
  66587. * Medium blur
  66588. */
  66589. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66590. /**
  66591. * Large blur
  66592. */
  66593. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66594. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66595. ;
  66596. /**
  66597. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66598. */
  66599. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66600. __extends(DepthOfFieldEffect, _super);
  66601. /**
  66602. * Creates a new instance of @see DepthOfFieldEffect
  66603. * @param scene The scene the effect belongs to.
  66604. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66605. */
  66606. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66607. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66608. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66609. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66610. // Enable and get current depth map
  66611. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66612. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66613. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66614. // Capture circle of confusion texture
  66615. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66616. _this._depthOfFieldPass.autoClear = false;
  66617. // 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)
  66618. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66619. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66620. _this._depthOfFieldBlurY = [];
  66621. _this._depthOfFieldBlurX = [];
  66622. var blurCount = 1;
  66623. var kernelSize = 15;
  66624. switch (blurLevel) {
  66625. case DepthOfFieldEffectBlurLevel.High: {
  66626. blurCount = 3;
  66627. kernelSize = 51;
  66628. break;
  66629. }
  66630. case DepthOfFieldEffectBlurLevel.Medium: {
  66631. blurCount = 2;
  66632. kernelSize = 31;
  66633. break;
  66634. }
  66635. default: {
  66636. kernelSize = 15;
  66637. blurCount = 1;
  66638. break;
  66639. }
  66640. }
  66641. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66642. for (var i = 0; i < blurCount; i++) {
  66643. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66644. blurY.autoClear = false;
  66645. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66646. blurX.autoClear = false;
  66647. _this._depthOfFieldBlurY.push(blurY);
  66648. _this._depthOfFieldBlurX.push(blurX);
  66649. }
  66650. // Merge blurred images with original image based on circleOfConfusion
  66651. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66652. _this._depthOfFieldMerge.autoClear = false;
  66653. // Set all post processes on the effect.
  66654. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66655. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66656. effects.push(_this._depthOfFieldBlurY[i]);
  66657. effects.push(_this._depthOfFieldBlurX[i]);
  66658. }
  66659. effects.push(_this._depthOfFieldMerge);
  66660. return effects;
  66661. }, true) || this;
  66662. return _this;
  66663. }
  66664. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66665. get: function () {
  66666. return this._circleOfConfusion.focalLength;
  66667. },
  66668. /**
  66669. * The focal the length of the camera used in the effect
  66670. */
  66671. set: function (value) {
  66672. this._circleOfConfusion.focalLength = value;
  66673. },
  66674. enumerable: true,
  66675. configurable: true
  66676. });
  66677. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66678. get: function () {
  66679. return this._circleOfConfusion.fStop;
  66680. },
  66681. /**
  66682. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66683. */
  66684. set: function (value) {
  66685. this._circleOfConfusion.fStop = value;
  66686. },
  66687. enumerable: true,
  66688. configurable: true
  66689. });
  66690. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66691. get: function () {
  66692. return this._circleOfConfusion.focusDistance;
  66693. },
  66694. /**
  66695. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66696. */
  66697. set: function (value) {
  66698. this._circleOfConfusion.focusDistance = value;
  66699. },
  66700. enumerable: true,
  66701. configurable: true
  66702. });
  66703. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66704. get: function () {
  66705. return this._circleOfConfusion.lensSize;
  66706. },
  66707. /**
  66708. * 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.
  66709. */
  66710. set: function (value) {
  66711. this._circleOfConfusion.lensSize = value;
  66712. },
  66713. enumerable: true,
  66714. configurable: true
  66715. });
  66716. /**
  66717. * Disposes each of the internal effects for a given camera.
  66718. * @param camera The camera to dispose the effect on.
  66719. */
  66720. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66721. this._depthOfFieldPass.dispose(camera);
  66722. this._circleOfConfusion.dispose(camera);
  66723. this._depthOfFieldBlurX.forEach(function (element) {
  66724. element.dispose(camera);
  66725. });
  66726. this._depthOfFieldBlurY.forEach(function (element) {
  66727. element.dispose(camera);
  66728. });
  66729. this._depthOfFieldMerge.dispose(camera);
  66730. };
  66731. return DepthOfFieldEffect;
  66732. }(BABYLON.PostProcessRenderEffect));
  66733. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66734. })(BABYLON || (BABYLON = {}));
  66735. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66736. var BABYLON;
  66737. (function (BABYLON) {
  66738. /**
  66739. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66740. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66741. */
  66742. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66743. __extends(DefaultRenderingPipeline, _super);
  66744. /**
  66745. * @constructor
  66746. * @param {string} name - The rendering pipeline name
  66747. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66748. * @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)
  66749. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66750. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66751. */
  66752. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66753. if (automaticBuild === void 0) { automaticBuild = true; }
  66754. var _this = _super.call(this, scene.getEngine(), name) || this;
  66755. /**
  66756. * ID of the pass post process used for bloom,
  66757. */
  66758. _this.PassPostProcessId = "PassPostProcessEffect";
  66759. /**
  66760. * ID of the highlight post process used for bloom,
  66761. */
  66762. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66763. /**
  66764. * ID of the blurX post process used for bloom,
  66765. */
  66766. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66767. /**
  66768. * ID of the blurY post process used for bloom,
  66769. */
  66770. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66771. /**
  66772. * ID of the copy back post process used for bloom,
  66773. */
  66774. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66775. /**
  66776. * ID of the image processing post process;
  66777. */
  66778. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66779. /**
  66780. * ID of the Fast Approximate Anti-Aliasing post process;
  66781. */
  66782. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66783. /**
  66784. * ID of the final merge post process;
  66785. */
  66786. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66787. /**
  66788. * Animations which can be used to tweak settings over a period of time
  66789. */
  66790. _this.animations = [];
  66791. // Values
  66792. _this._bloomEnabled = false;
  66793. _this._depthOfFieldEnabled = false;
  66794. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66795. _this._fxaaEnabled = false;
  66796. _this._imageProcessingEnabled = true;
  66797. _this._bloomScale = 0.6;
  66798. _this._buildAllowed = true;
  66799. /**
  66800. * Specifies the size of the bloom blur kernel, relative to the final output size
  66801. */
  66802. _this.bloomKernel = 64;
  66803. /**
  66804. * Specifies the weight of the bloom in the final rendering
  66805. */
  66806. _this._bloomWeight = 0.15;
  66807. _this._cameras = cameras || [];
  66808. _this._buildAllowed = automaticBuild;
  66809. // Initialize
  66810. _this._scene = scene;
  66811. var caps = _this._scene.getEngine().getCaps();
  66812. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66813. // Misc
  66814. if (_this._hdr) {
  66815. if (caps.textureHalfFloatRender) {
  66816. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66817. }
  66818. else if (caps.textureFloatRender) {
  66819. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66820. }
  66821. }
  66822. else {
  66823. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66824. }
  66825. // Attach
  66826. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66827. _this._buildPipeline();
  66828. return _this;
  66829. }
  66830. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66831. get: function () {
  66832. return this._bloomWeight;
  66833. },
  66834. /**
  66835. * The strength of the bloom.
  66836. */
  66837. set: function (value) {
  66838. if (this._bloomWeight === value) {
  66839. return;
  66840. }
  66841. this._bloomWeight = value;
  66842. if (this._hdr && this.copyBack) {
  66843. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66844. }
  66845. },
  66846. enumerable: true,
  66847. configurable: true
  66848. });
  66849. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66850. get: function () {
  66851. return this._bloomScale;
  66852. },
  66853. /**
  66854. * The scale of the bloom, lower value will provide better performance.
  66855. */
  66856. set: function (value) {
  66857. if (this._bloomScale === value) {
  66858. return;
  66859. }
  66860. this._bloomScale = value;
  66861. this._buildPipeline();
  66862. },
  66863. enumerable: true,
  66864. configurable: true
  66865. });
  66866. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66867. get: function () {
  66868. return this._bloomEnabled;
  66869. },
  66870. /**
  66871. * Enable or disable the bloom from the pipeline
  66872. */
  66873. set: function (enabled) {
  66874. if (this._bloomEnabled === enabled) {
  66875. return;
  66876. }
  66877. this._bloomEnabled = enabled;
  66878. this._buildPipeline();
  66879. },
  66880. enumerable: true,
  66881. configurable: true
  66882. });
  66883. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66884. /**
  66885. * If the depth of field is enabled.
  66886. */
  66887. get: function () {
  66888. return this._depthOfFieldEnabled;
  66889. },
  66890. set: function (enabled) {
  66891. if (this._depthOfFieldEnabled === enabled) {
  66892. return;
  66893. }
  66894. this._depthOfFieldEnabled = enabled;
  66895. this._buildPipeline();
  66896. },
  66897. enumerable: true,
  66898. configurable: true
  66899. });
  66900. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66901. /**
  66902. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66903. */
  66904. get: function () {
  66905. return this._depthOfFieldBlurLevel;
  66906. },
  66907. set: function (value) {
  66908. if (this._depthOfFieldBlurLevel === value) {
  66909. return;
  66910. }
  66911. this._depthOfFieldBlurLevel = value;
  66912. this._buildPipeline();
  66913. },
  66914. enumerable: true,
  66915. configurable: true
  66916. });
  66917. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66918. get: function () {
  66919. return this._fxaaEnabled;
  66920. },
  66921. /**
  66922. * If the anti aliasing is enabled.
  66923. */
  66924. set: function (enabled) {
  66925. if (this._fxaaEnabled === enabled) {
  66926. return;
  66927. }
  66928. this._fxaaEnabled = enabled;
  66929. this._buildPipeline();
  66930. },
  66931. enumerable: true,
  66932. configurable: true
  66933. });
  66934. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66935. get: function () {
  66936. return this._imageProcessingEnabled;
  66937. },
  66938. /**
  66939. * If image processing is enabled.
  66940. */
  66941. set: function (enabled) {
  66942. if (this._imageProcessingEnabled === enabled) {
  66943. return;
  66944. }
  66945. this._imageProcessingEnabled = enabled;
  66946. this._buildPipeline();
  66947. },
  66948. enumerable: true,
  66949. configurable: true
  66950. });
  66951. /**
  66952. * Force the compilation of the entire pipeline.
  66953. */
  66954. DefaultRenderingPipeline.prototype.prepare = function () {
  66955. var previousState = this._buildAllowed;
  66956. this._buildAllowed = true;
  66957. this._buildPipeline();
  66958. this._buildAllowed = previousState;
  66959. };
  66960. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66961. var _this = this;
  66962. if (!this._buildAllowed) {
  66963. return;
  66964. }
  66965. var engine = this._scene.getEngine();
  66966. this._disposePostProcesses();
  66967. this._reset();
  66968. if (this.depthOfFieldEnabled) {
  66969. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66970. this.addEffect(this.depthOfField);
  66971. }
  66972. if (this.bloomEnabled) {
  66973. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66974. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66975. if (!this._hdr) {
  66976. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66977. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66978. this.highlights.autoClear = false;
  66979. this.highlights.alwaysForcePOT = true;
  66980. }
  66981. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66982. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66983. this.blurX.alwaysForcePOT = true;
  66984. this.blurX.autoClear = false;
  66985. this.blurX.onActivateObservable.add(function () {
  66986. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66987. _this.blurX.kernel = _this.bloomKernel * dw;
  66988. });
  66989. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66990. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66991. this.blurY.alwaysForcePOT = true;
  66992. this.blurY.autoClear = false;
  66993. this.blurY.onActivateObservable.add(function () {
  66994. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66995. _this.blurY.kernel = _this.bloomKernel * dh;
  66996. });
  66997. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66998. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66999. this.copyBack.alwaysForcePOT = true;
  67000. if (this._hdr) {
  67001. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67002. var w = this.bloomWeight;
  67003. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67004. }
  67005. else {
  67006. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67007. }
  67008. this.copyBack.autoClear = false;
  67009. }
  67010. if (this._imageProcessingEnabled) {
  67011. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67012. if (this._hdr) {
  67013. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67014. }
  67015. else {
  67016. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67017. }
  67018. }
  67019. if (this.fxaaEnabled) {
  67020. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67021. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67022. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67023. }
  67024. else if (this._hdr && this.imageProcessing) {
  67025. this.finalMerge = this.imageProcessing;
  67026. }
  67027. else {
  67028. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67029. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67030. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67031. }
  67032. if (this.bloomEnabled) {
  67033. if (this._hdr) {
  67034. this.copyBack.shareOutputWith(this.blurX);
  67035. if (this.imageProcessing) {
  67036. this.imageProcessing.shareOutputWith(this.pass);
  67037. this.imageProcessing.autoClear = false;
  67038. }
  67039. else if (this.fxaa) {
  67040. this.fxaa.shareOutputWith(this.pass);
  67041. }
  67042. else {
  67043. this.finalMerge.shareOutputWith(this.pass);
  67044. }
  67045. }
  67046. else {
  67047. if (this.fxaa) {
  67048. this.fxaa.shareOutputWith(this.pass);
  67049. }
  67050. else {
  67051. this.finalMerge.shareOutputWith(this.pass);
  67052. }
  67053. }
  67054. }
  67055. if (this._cameras !== null) {
  67056. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67057. }
  67058. };
  67059. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67060. for (var i = 0; i < this._cameras.length; i++) {
  67061. var camera = this._cameras[i];
  67062. if (this.pass) {
  67063. this.pass.dispose(camera);
  67064. }
  67065. if (this.highlights) {
  67066. this.highlights.dispose(camera);
  67067. }
  67068. if (this.blurX) {
  67069. this.blurX.dispose(camera);
  67070. }
  67071. if (this.blurY) {
  67072. this.blurY.dispose(camera);
  67073. }
  67074. if (this.copyBack) {
  67075. this.copyBack.dispose(camera);
  67076. }
  67077. if (this.imageProcessing) {
  67078. this.imageProcessing.dispose(camera);
  67079. }
  67080. if (this.fxaa) {
  67081. this.fxaa.dispose(camera);
  67082. }
  67083. if (this.finalMerge) {
  67084. this.finalMerge.dispose(camera);
  67085. }
  67086. if (this.depthOfField) {
  67087. this.depthOfField.disposeEffects(camera);
  67088. }
  67089. }
  67090. this.pass = null;
  67091. this.highlights = null;
  67092. this.blurX = null;
  67093. this.blurY = null;
  67094. this.copyBack = null;
  67095. this.imageProcessing = null;
  67096. this.fxaa = null;
  67097. this.finalMerge = null;
  67098. this.depthOfField = null;
  67099. };
  67100. /**
  67101. * Dispose of the pipeline and stop all post processes
  67102. */
  67103. DefaultRenderingPipeline.prototype.dispose = function () {
  67104. this._disposePostProcesses();
  67105. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67106. _super.prototype.dispose.call(this);
  67107. };
  67108. /**
  67109. * Serialize the rendering pipeline (Used when exporting)
  67110. * @returns the serialized object
  67111. */
  67112. DefaultRenderingPipeline.prototype.serialize = function () {
  67113. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67114. serializationObject.customType = "DefaultRenderingPipeline";
  67115. return serializationObject;
  67116. };
  67117. /**
  67118. * Parse the serialized pipeline
  67119. * @param source Source pipeline.
  67120. * @param scene The scene to load the pipeline to.
  67121. * @param rootUrl The URL of the serialized pipeline.
  67122. * @returns An instantiated pipeline from the serialized object.
  67123. */
  67124. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67125. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67126. };
  67127. __decorate([
  67128. BABYLON.serialize()
  67129. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67130. __decorate([
  67131. BABYLON.serialize()
  67132. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67133. __decorate([
  67134. BABYLON.serialize()
  67135. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67136. __decorate([
  67137. BABYLON.serialize()
  67138. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67139. __decorate([
  67140. BABYLON.serialize()
  67141. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67142. __decorate([
  67143. BABYLON.serialize()
  67144. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67145. __decorate([
  67146. BABYLON.serialize()
  67147. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67148. __decorate([
  67149. BABYLON.serialize()
  67150. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67151. __decorate([
  67152. BABYLON.serialize()
  67153. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67154. __decorate([
  67155. BABYLON.serialize()
  67156. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67157. return DefaultRenderingPipeline;
  67158. }(BABYLON.PostProcessRenderPipeline));
  67159. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67160. })(BABYLON || (BABYLON = {}));
  67161. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67162. var BABYLON;
  67163. (function (BABYLON) {
  67164. /**
  67165. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67166. */
  67167. var GeometryBufferRenderer = /** @class */ (function () {
  67168. /**
  67169. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67170. * @param scene The scene the buffer belongs to
  67171. * @param ratio How big is the buffer related to the main canvas.
  67172. */
  67173. function GeometryBufferRenderer(scene, ratio) {
  67174. if (ratio === void 0) { ratio = 1; }
  67175. this._enablePosition = false;
  67176. this._scene = scene;
  67177. this._ratio = ratio;
  67178. // Render target
  67179. this._createRenderTargets();
  67180. }
  67181. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67182. /**
  67183. * Set the render list (meshes to be rendered) used in the G buffer.
  67184. */
  67185. set: function (meshes) {
  67186. this._multiRenderTarget.renderList = meshes;
  67187. },
  67188. enumerable: true,
  67189. configurable: true
  67190. });
  67191. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67192. /**
  67193. * Gets wether or not G buffer are supported by the running hardware.
  67194. * This requires draw buffer supports
  67195. */
  67196. get: function () {
  67197. return this._multiRenderTarget.isSupported;
  67198. },
  67199. enumerable: true,
  67200. configurable: true
  67201. });
  67202. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67203. /**
  67204. * Gets wether or not position are enabled for the G buffer.
  67205. */
  67206. get: function () {
  67207. return this._enablePosition;
  67208. },
  67209. /**
  67210. * Sets wether or not position are enabled for the G buffer.
  67211. */
  67212. set: function (enable) {
  67213. this._enablePosition = enable;
  67214. this.dispose();
  67215. this._createRenderTargets();
  67216. },
  67217. enumerable: true,
  67218. configurable: true
  67219. });
  67220. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67221. /**
  67222. * Gets the scene associated with the buffer.
  67223. */
  67224. get: function () {
  67225. return this._scene;
  67226. },
  67227. enumerable: true,
  67228. configurable: true
  67229. });
  67230. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67231. /**
  67232. * Gets the ratio used by the buffer during its creation.
  67233. * How big is the buffer related to the main canvas.
  67234. */
  67235. get: function () {
  67236. return this._ratio;
  67237. },
  67238. enumerable: true,
  67239. configurable: true
  67240. });
  67241. /**
  67242. * Checks wether everything is ready to render a submesh to the G buffer.
  67243. * @param subMesh the submesh to check readiness for
  67244. * @param useInstances is the mesh drawn using instance or not
  67245. * @returns true if ready otherwise false
  67246. */
  67247. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67248. var material = subMesh.getMaterial();
  67249. if (material && material.disableDepthWrite) {
  67250. return false;
  67251. }
  67252. var defines = [];
  67253. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67254. var mesh = subMesh.getMesh();
  67255. // Alpha test
  67256. if (material && material.needAlphaTesting()) {
  67257. defines.push("#define ALPHATEST");
  67258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67259. attribs.push(BABYLON.VertexBuffer.UVKind);
  67260. defines.push("#define UV1");
  67261. }
  67262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67264. defines.push("#define UV2");
  67265. }
  67266. }
  67267. // Buffers
  67268. if (this._enablePosition) {
  67269. defines.push("#define POSITION");
  67270. }
  67271. // Bones
  67272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67275. if (mesh.numBoneInfluencers > 4) {
  67276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67278. }
  67279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67280. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67281. }
  67282. else {
  67283. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67284. }
  67285. // Instances
  67286. if (useInstances) {
  67287. defines.push("#define INSTANCES");
  67288. attribs.push("world0");
  67289. attribs.push("world1");
  67290. attribs.push("world2");
  67291. attribs.push("world3");
  67292. }
  67293. // Get correct effect
  67294. var join = defines.join("\n");
  67295. if (this._cachedDefines !== join) {
  67296. this._cachedDefines = join;
  67297. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67298. }
  67299. return this._effect.isReady();
  67300. };
  67301. /**
  67302. * Gets the current underlying G Buffer.
  67303. * @returns the buffer
  67304. */
  67305. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67306. return this._multiRenderTarget;
  67307. };
  67308. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67309. /**
  67310. * Gets the number of samples used to render the buffer (anti aliasing).
  67311. */
  67312. get: function () {
  67313. return this._multiRenderTarget.samples;
  67314. },
  67315. /**
  67316. * Sets the number of samples used to render the buffer (anti aliasing).
  67317. */
  67318. set: function (value) {
  67319. this._multiRenderTarget.samples = value;
  67320. },
  67321. enumerable: true,
  67322. configurable: true
  67323. });
  67324. /**
  67325. * Disposes the renderer and frees up associated resources.
  67326. */
  67327. GeometryBufferRenderer.prototype.dispose = function () {
  67328. this.getGBuffer().dispose();
  67329. };
  67330. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67331. var _this = this;
  67332. var engine = this._scene.getEngine();
  67333. var count = this._enablePosition ? 3 : 2;
  67334. 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 });
  67335. if (!this.isSupported) {
  67336. return;
  67337. }
  67338. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67339. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67340. this._multiRenderTarget.refreshRate = 1;
  67341. this._multiRenderTarget.renderParticles = false;
  67342. this._multiRenderTarget.renderList = null;
  67343. // set default depth value to 1.0 (far away)
  67344. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67345. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67346. });
  67347. // Custom render function
  67348. var renderSubMesh = function (subMesh) {
  67349. var mesh = subMesh.getRenderingMesh();
  67350. var scene = _this._scene;
  67351. var engine = scene.getEngine();
  67352. var material = subMesh.getMaterial();
  67353. if (!material) {
  67354. return;
  67355. }
  67356. // Culling
  67357. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67358. // Managing instances
  67359. var batch = mesh._getInstancesRenderList(subMesh._id);
  67360. if (batch.mustReturn) {
  67361. return;
  67362. }
  67363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67365. engine.enableEffect(_this._effect);
  67366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67367. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67368. _this._effect.setMatrix("view", scene.getViewMatrix());
  67369. // Alpha test
  67370. if (material && material.needAlphaTesting()) {
  67371. var alphaTexture = material.getAlphaTestTexture();
  67372. if (alphaTexture) {
  67373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67375. }
  67376. }
  67377. // Bones
  67378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67379. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67380. }
  67381. // Draw
  67382. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67383. }
  67384. };
  67385. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67386. var index;
  67387. if (depthOnlySubMeshes.length) {
  67388. engine.setColorWrite(false);
  67389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67390. renderSubMesh(depthOnlySubMeshes.data[index]);
  67391. }
  67392. engine.setColorWrite(true);
  67393. }
  67394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67395. renderSubMesh(opaqueSubMeshes.data[index]);
  67396. }
  67397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67398. renderSubMesh(alphaTestSubMeshes.data[index]);
  67399. }
  67400. };
  67401. };
  67402. return GeometryBufferRenderer;
  67403. }());
  67404. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67405. })(BABYLON || (BABYLON = {}));
  67406. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67407. var BABYLON;
  67408. (function (BABYLON) {
  67409. var RefractionPostProcess = /** @class */ (function (_super) {
  67410. __extends(RefractionPostProcess, _super);
  67411. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67412. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67413. _this.color = color;
  67414. _this.depth = depth;
  67415. _this.colorLevel = colorLevel;
  67416. _this.onActivateObservable.add(function (cam) {
  67417. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67418. });
  67419. _this.onApplyObservable.add(function (effect) {
  67420. effect.setColor3("baseColor", _this.color);
  67421. effect.setFloat("depth", _this.depth);
  67422. effect.setFloat("colorLevel", _this.colorLevel);
  67423. effect.setTexture("refractionSampler", _this._refRexture);
  67424. });
  67425. return _this;
  67426. }
  67427. // Methods
  67428. RefractionPostProcess.prototype.dispose = function (camera) {
  67429. if (this._refRexture) {
  67430. this._refRexture.dispose();
  67431. }
  67432. _super.prototype.dispose.call(this, camera);
  67433. };
  67434. return RefractionPostProcess;
  67435. }(BABYLON.PostProcess));
  67436. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67437. })(BABYLON || (BABYLON = {}));
  67438. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67439. var BABYLON;
  67440. (function (BABYLON) {
  67441. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67442. __extends(BlackAndWhitePostProcess, _super);
  67443. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67444. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67445. _this.degree = 1;
  67446. _this.onApplyObservable.add(function (effect) {
  67447. effect.setFloat("degree", _this.degree);
  67448. });
  67449. return _this;
  67450. }
  67451. return BlackAndWhitePostProcess;
  67452. }(BABYLON.PostProcess));
  67453. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67454. })(BABYLON || (BABYLON = {}));
  67455. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67456. var BABYLON;
  67457. (function (BABYLON) {
  67458. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67459. __extends(ConvolutionPostProcess, _super);
  67460. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67461. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67462. _this.kernel = kernel;
  67463. _this.onApply = function (effect) {
  67464. effect.setFloat2("screenSize", _this.width, _this.height);
  67465. effect.setArray("kernel", _this.kernel);
  67466. };
  67467. return _this;
  67468. }
  67469. // Statics
  67470. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67471. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67472. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67473. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67474. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67475. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67476. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67477. return ConvolutionPostProcess;
  67478. }(BABYLON.PostProcess));
  67479. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67480. })(BABYLON || (BABYLON = {}));
  67481. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67482. var BABYLON;
  67483. (function (BABYLON) {
  67484. var FilterPostProcess = /** @class */ (function (_super) {
  67485. __extends(FilterPostProcess, _super);
  67486. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67487. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67488. _this.kernelMatrix = kernelMatrix;
  67489. _this.onApply = function (effect) {
  67490. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67491. };
  67492. return _this;
  67493. }
  67494. return FilterPostProcess;
  67495. }(BABYLON.PostProcess));
  67496. BABYLON.FilterPostProcess = FilterPostProcess;
  67497. })(BABYLON || (BABYLON = {}));
  67498. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67499. var BABYLON;
  67500. (function (BABYLON) {
  67501. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67502. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67503. __extends(VolumetricLightScatteringPostProcess, _super);
  67504. /**
  67505. * @constructor
  67506. * @param {string} name - The post-process name
  67507. * @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)
  67508. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67509. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67510. * @param {number} samples - The post-process quality, default 100
  67511. * @param {number} samplingMode - The post-process filtering mode
  67512. * @param {BABYLON.Engine} engine - The babylon engine
  67513. * @param {boolean} reusable - If the post-process is reusable
  67514. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67515. */
  67516. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67517. if (samples === void 0) { samples = 100; }
  67518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67519. 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;
  67520. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67521. /**
  67522. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67523. * @type {Vector3}
  67524. */
  67525. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67526. /**
  67527. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67528. * @type {boolean}
  67529. */
  67530. _this.useCustomMeshPosition = false;
  67531. /**
  67532. * If the post-process should inverse the light scattering direction
  67533. * @type {boolean}
  67534. */
  67535. _this.invert = true;
  67536. /**
  67537. * Array containing the excluded meshes not rendered in the internal pass
  67538. */
  67539. _this.excludedMeshes = new Array();
  67540. /**
  67541. * Controls the overall intensity of the post-process
  67542. * @type {number}
  67543. */
  67544. _this.exposure = 0.3;
  67545. /**
  67546. * Dissipates each sample's contribution in range [0, 1]
  67547. * @type {number}
  67548. */
  67549. _this.decay = 0.96815;
  67550. /**
  67551. * Controls the overall intensity of each sample
  67552. * @type {number}
  67553. */
  67554. _this.weight = 0.58767;
  67555. /**
  67556. * Controls the density of each sample
  67557. * @type {number}
  67558. */
  67559. _this.density = 0.926;
  67560. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67561. engine = scene.getEngine();
  67562. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67563. // Configure mesh
  67564. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67565. // Configure
  67566. _this._createPass(scene, ratio.passRatio || ratio);
  67567. _this.onActivate = function (camera) {
  67568. if (!_this.isSupported) {
  67569. _this.dispose(camera);
  67570. }
  67571. _this.onActivate = null;
  67572. };
  67573. _this.onApplyObservable.add(function (effect) {
  67574. _this._updateMeshScreenCoordinates(scene);
  67575. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67576. effect.setFloat("exposure", _this.exposure);
  67577. effect.setFloat("decay", _this.decay);
  67578. effect.setFloat("weight", _this.weight);
  67579. effect.setFloat("density", _this.density);
  67580. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67581. });
  67582. return _this;
  67583. }
  67584. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67585. get: function () {
  67586. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67587. return false;
  67588. },
  67589. set: function (useDiffuseColor) {
  67590. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67591. },
  67592. enumerable: true,
  67593. configurable: true
  67594. });
  67595. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67596. return "VolumetricLightScatteringPostProcess";
  67597. };
  67598. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67599. var mesh = subMesh.getMesh();
  67600. // Render this.mesh as default
  67601. if (mesh === this.mesh && mesh.material) {
  67602. return mesh.material.isReady(mesh);
  67603. }
  67604. var defines = [];
  67605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67606. var material = subMesh.getMaterial();
  67607. // Alpha test
  67608. if (material) {
  67609. if (material.needAlphaTesting()) {
  67610. defines.push("#define ALPHATEST");
  67611. }
  67612. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67613. attribs.push(BABYLON.VertexBuffer.UVKind);
  67614. defines.push("#define UV1");
  67615. }
  67616. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67617. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67618. defines.push("#define UV2");
  67619. }
  67620. }
  67621. // Bones
  67622. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67623. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67624. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67625. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67626. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67627. }
  67628. else {
  67629. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67630. }
  67631. // Instances
  67632. if (useInstances) {
  67633. defines.push("#define INSTANCES");
  67634. attribs.push("world0");
  67635. attribs.push("world1");
  67636. attribs.push("world2");
  67637. attribs.push("world3");
  67638. }
  67639. // Get correct effect
  67640. var join = defines.join("\n");
  67641. if (this._cachedDefines !== join) {
  67642. this._cachedDefines = join;
  67643. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67644. }
  67645. return this._volumetricLightScatteringPass.isReady();
  67646. };
  67647. /**
  67648. * Sets the new light position for light scattering effect
  67649. * @param {BABYLON.Vector3} The new custom light position
  67650. */
  67651. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67652. this.customMeshPosition = position;
  67653. };
  67654. /**
  67655. * Returns the light position for light scattering effect
  67656. * @return {BABYLON.Vector3} The custom light position
  67657. */
  67658. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67659. return this.customMeshPosition;
  67660. };
  67661. /**
  67662. * Disposes the internal assets and detaches the post-process from the camera
  67663. */
  67664. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67665. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67666. if (rttIndex !== -1) {
  67667. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67668. }
  67669. this._volumetricLightScatteringRTT.dispose();
  67670. _super.prototype.dispose.call(this, camera);
  67671. };
  67672. /**
  67673. * Returns the render target texture used by the post-process
  67674. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67675. */
  67676. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67677. return this._volumetricLightScatteringRTT;
  67678. };
  67679. // Private methods
  67680. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67681. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67682. return true;
  67683. }
  67684. return false;
  67685. };
  67686. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67687. var _this = this;
  67688. var engine = scene.getEngine();
  67689. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67690. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67691. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67692. this._volumetricLightScatteringRTT.renderList = null;
  67693. this._volumetricLightScatteringRTT.renderParticles = false;
  67694. var camera = this.getCamera();
  67695. if (camera) {
  67696. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67697. }
  67698. else {
  67699. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67700. }
  67701. // Custom render function for submeshes
  67702. var renderSubMesh = function (subMesh) {
  67703. var mesh = subMesh.getRenderingMesh();
  67704. if (_this._meshExcluded(mesh)) {
  67705. return;
  67706. }
  67707. var material = subMesh.getMaterial();
  67708. if (!material) {
  67709. return;
  67710. }
  67711. var scene = mesh.getScene();
  67712. var engine = scene.getEngine();
  67713. // Culling
  67714. engine.setState(material.backFaceCulling);
  67715. // Managing instances
  67716. var batch = mesh._getInstancesRenderList(subMesh._id);
  67717. if (batch.mustReturn) {
  67718. return;
  67719. }
  67720. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67721. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67722. var effect = _this._volumetricLightScatteringPass;
  67723. if (mesh === _this.mesh) {
  67724. if (subMesh.effect) {
  67725. effect = subMesh.effect;
  67726. }
  67727. else {
  67728. effect = material.getEffect();
  67729. }
  67730. }
  67731. engine.enableEffect(effect);
  67732. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67733. if (mesh === _this.mesh) {
  67734. material.bind(mesh.getWorldMatrix(), mesh);
  67735. }
  67736. else {
  67737. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67738. // Alpha test
  67739. if (material && material.needAlphaTesting()) {
  67740. var alphaTexture = material.getAlphaTestTexture();
  67741. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67742. if (alphaTexture) {
  67743. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67744. }
  67745. }
  67746. // Bones
  67747. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67748. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67749. }
  67750. }
  67751. // Draw
  67752. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67753. }
  67754. };
  67755. // Render target texture callbacks
  67756. var savedSceneClearColor;
  67757. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67758. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67759. savedSceneClearColor = scene.clearColor;
  67760. scene.clearColor = sceneClearColor;
  67761. });
  67762. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67763. scene.clearColor = savedSceneClearColor;
  67764. });
  67765. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67766. var engine = scene.getEngine();
  67767. var index;
  67768. if (depthOnlySubMeshes.length) {
  67769. engine.setColorWrite(false);
  67770. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67771. renderSubMesh(depthOnlySubMeshes.data[index]);
  67772. }
  67773. engine.setColorWrite(true);
  67774. }
  67775. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67776. renderSubMesh(opaqueSubMeshes.data[index]);
  67777. }
  67778. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67779. renderSubMesh(alphaTestSubMeshes.data[index]);
  67780. }
  67781. if (transparentSubMeshes.length) {
  67782. // Sort sub meshes
  67783. for (index = 0; index < transparentSubMeshes.length; index++) {
  67784. var submesh = transparentSubMeshes.data[index];
  67785. var boundingInfo = submesh.getBoundingInfo();
  67786. if (boundingInfo && scene.activeCamera) {
  67787. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67788. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67789. }
  67790. }
  67791. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67792. sortedArray.sort(function (a, b) {
  67793. // Alpha index first
  67794. if (a._alphaIndex > b._alphaIndex) {
  67795. return 1;
  67796. }
  67797. if (a._alphaIndex < b._alphaIndex) {
  67798. return -1;
  67799. }
  67800. // Then distance to camera
  67801. if (a._distanceToCamera < b._distanceToCamera) {
  67802. return 1;
  67803. }
  67804. if (a._distanceToCamera > b._distanceToCamera) {
  67805. return -1;
  67806. }
  67807. return 0;
  67808. });
  67809. // Render sub meshes
  67810. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67811. for (index = 0; index < sortedArray.length; index++) {
  67812. renderSubMesh(sortedArray[index]);
  67813. }
  67814. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67815. }
  67816. };
  67817. };
  67818. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67819. var transform = scene.getTransformMatrix();
  67820. var meshPosition;
  67821. if (this.useCustomMeshPosition) {
  67822. meshPosition = this.customMeshPosition;
  67823. }
  67824. else if (this.attachedNode) {
  67825. meshPosition = this.attachedNode.position;
  67826. }
  67827. else {
  67828. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67829. }
  67830. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67831. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67832. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67833. if (this.invert)
  67834. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67835. };
  67836. // Static methods
  67837. /**
  67838. * Creates a default mesh for the Volumeric Light Scattering post-process
  67839. * @param {string} The mesh name
  67840. * @param {BABYLON.Scene} The scene where to create the mesh
  67841. * @return {BABYLON.Mesh} the default mesh
  67842. */
  67843. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67844. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67845. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67846. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67847. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67848. mesh.material = material;
  67849. return mesh;
  67850. };
  67851. __decorate([
  67852. BABYLON.serializeAsVector3()
  67853. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67854. __decorate([
  67855. BABYLON.serialize()
  67856. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67857. __decorate([
  67858. BABYLON.serialize()
  67859. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67860. __decorate([
  67861. BABYLON.serializeAsMeshReference()
  67862. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67863. __decorate([
  67864. BABYLON.serialize()
  67865. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67866. __decorate([
  67867. BABYLON.serialize()
  67868. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67869. __decorate([
  67870. BABYLON.serialize()
  67871. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67872. __decorate([
  67873. BABYLON.serialize()
  67874. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67875. __decorate([
  67876. BABYLON.serialize()
  67877. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67878. return VolumetricLightScatteringPostProcess;
  67879. }(BABYLON.PostProcess));
  67880. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67881. })(BABYLON || (BABYLON = {}));
  67882. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67883. //
  67884. // This post-process allows the modification of rendered colors by using
  67885. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67886. //
  67887. // The object needs to be provided an url to a texture containing the color
  67888. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67889. // Use an image editing software to tweak the LUT to match your needs.
  67890. //
  67891. // For an example of a color LUT, see here:
  67892. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67893. // For explanations on color grading, see here:
  67894. // http://udn.epicgames.com/Three/ColorGrading.html
  67895. //
  67896. var BABYLON;
  67897. (function (BABYLON) {
  67898. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67899. __extends(ColorCorrectionPostProcess, _super);
  67900. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67901. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67902. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67903. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67904. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67905. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67906. _this.onApply = function (effect) {
  67907. effect.setTexture("colorTable", _this._colorTableTexture);
  67908. };
  67909. return _this;
  67910. }
  67911. return ColorCorrectionPostProcess;
  67912. }(BABYLON.PostProcess));
  67913. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67914. })(BABYLON || (BABYLON = {}));
  67915. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67916. var BABYLON;
  67917. (function (BABYLON) {
  67918. var TonemappingOperator;
  67919. (function (TonemappingOperator) {
  67920. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67921. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67922. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67923. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67924. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67925. ;
  67926. var TonemapPostProcess = /** @class */ (function (_super) {
  67927. __extends(TonemapPostProcess, _super);
  67928. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67930. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67931. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67932. _this._operator = _operator;
  67933. _this.exposureAdjustment = exposureAdjustment;
  67934. var defines = "#define ";
  67935. if (_this._operator === TonemappingOperator.Hable)
  67936. defines += "HABLE_TONEMAPPING";
  67937. else if (_this._operator === TonemappingOperator.Reinhard)
  67938. defines += "REINHARD_TONEMAPPING";
  67939. else if (_this._operator === TonemappingOperator.HejiDawson)
  67940. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67941. else if (_this._operator === TonemappingOperator.Photographic)
  67942. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67943. //sadly a second call to create the effect.
  67944. _this.updateEffect(defines);
  67945. _this.onApply = function (effect) {
  67946. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67947. };
  67948. return _this;
  67949. }
  67950. return TonemapPostProcess;
  67951. }(BABYLON.PostProcess));
  67952. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67953. })(BABYLON || (BABYLON = {}));
  67954. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67955. var BABYLON;
  67956. (function (BABYLON) {
  67957. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67958. __extends(DisplayPassPostProcess, _super);
  67959. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67960. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67961. }
  67962. return DisplayPassPostProcess;
  67963. }(BABYLON.PostProcess));
  67964. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67965. })(BABYLON || (BABYLON = {}));
  67966. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67967. var BABYLON;
  67968. (function (BABYLON) {
  67969. var HighlightsPostProcess = /** @class */ (function (_super) {
  67970. __extends(HighlightsPostProcess, _super);
  67971. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67972. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67973. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67974. }
  67975. return HighlightsPostProcess;
  67976. }(BABYLON.PostProcess));
  67977. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67978. })(BABYLON || (BABYLON = {}));
  67979. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67980. var BABYLON;
  67981. (function (BABYLON) {
  67982. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67983. __extends(ImageProcessingPostProcess, _super);
  67984. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67985. if (camera === void 0) { camera = null; }
  67986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67987. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67988. _this._fromLinearSpace = true;
  67989. /**
  67990. * Defines cache preventing GC.
  67991. */
  67992. _this._defines = {
  67993. IMAGEPROCESSING: false,
  67994. VIGNETTE: false,
  67995. VIGNETTEBLENDMODEMULTIPLY: false,
  67996. VIGNETTEBLENDMODEOPAQUE: false,
  67997. TONEMAPPING: false,
  67998. CONTRAST: false,
  67999. COLORCURVES: false,
  68000. COLORGRADING: false,
  68001. COLORGRADING3D: false,
  68002. FROMLINEARSPACE: false,
  68003. SAMPLER3DGREENDEPTH: false,
  68004. SAMPLER3DBGRMAP: false,
  68005. IMAGEPROCESSINGPOSTPROCESS: false,
  68006. EXPOSURE: false,
  68007. };
  68008. // Setup the configuration as forced by the constructor. This would then not force the
  68009. // scene materials output in linear space and let untouched the default forward pass.
  68010. if (imageProcessingConfiguration) {
  68011. imageProcessingConfiguration.applyByPostProcess = true;
  68012. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68013. // This will cause the shader to be compiled
  68014. _this.fromLinearSpace = false;
  68015. }
  68016. else {
  68017. _this._attachImageProcessingConfiguration(null, true);
  68018. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68019. }
  68020. _this.onApply = function (effect) {
  68021. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68022. };
  68023. return _this;
  68024. }
  68025. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68026. /**
  68027. * Gets the image processing configuration used either in this material.
  68028. */
  68029. get: function () {
  68030. return this._imageProcessingConfiguration;
  68031. },
  68032. /**
  68033. * Sets the Default image processing configuration used either in the this material.
  68034. *
  68035. * If sets to null, the scene one is in use.
  68036. */
  68037. set: function (value) {
  68038. this._attachImageProcessingConfiguration(value);
  68039. },
  68040. enumerable: true,
  68041. configurable: true
  68042. });
  68043. /**
  68044. * Attaches a new image processing configuration to the PBR Material.
  68045. * @param configuration
  68046. */
  68047. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68048. var _this = this;
  68049. if (doNotBuild === void 0) { doNotBuild = false; }
  68050. if (configuration === this._imageProcessingConfiguration) {
  68051. return;
  68052. }
  68053. // Detaches observer.
  68054. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68055. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68056. }
  68057. // Pick the scene configuration if needed.
  68058. if (!configuration) {
  68059. var scene = null;
  68060. var engine = this.getEngine();
  68061. var camera = this.getCamera();
  68062. if (camera) {
  68063. scene = camera.getScene();
  68064. }
  68065. else if (engine && engine.scenes) {
  68066. var scenes = engine.scenes;
  68067. scene = scenes[scenes.length - 1];
  68068. }
  68069. else {
  68070. scene = BABYLON.Engine.LastCreatedScene;
  68071. }
  68072. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68073. }
  68074. else {
  68075. this._imageProcessingConfiguration = configuration;
  68076. }
  68077. // Attaches observer.
  68078. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68079. _this._updateParameters();
  68080. });
  68081. // Ensure the effect will be rebuilt.
  68082. if (!doNotBuild) {
  68083. this._updateParameters();
  68084. }
  68085. };
  68086. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68087. /**
  68088. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68089. */
  68090. get: function () {
  68091. return this.imageProcessingConfiguration.colorCurves;
  68092. },
  68093. /**
  68094. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68095. */
  68096. set: function (value) {
  68097. this.imageProcessingConfiguration.colorCurves = value;
  68098. },
  68099. enumerable: true,
  68100. configurable: true
  68101. });
  68102. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68103. /**
  68104. * Gets wether the color curves effect is enabled.
  68105. */
  68106. get: function () {
  68107. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68108. },
  68109. /**
  68110. * Sets wether the color curves effect is enabled.
  68111. */
  68112. set: function (value) {
  68113. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68114. },
  68115. enumerable: true,
  68116. configurable: true
  68117. });
  68118. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68119. /**
  68120. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68121. */
  68122. get: function () {
  68123. return this.imageProcessingConfiguration.colorGradingTexture;
  68124. },
  68125. /**
  68126. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68127. */
  68128. set: function (value) {
  68129. this.imageProcessingConfiguration.colorGradingTexture = value;
  68130. },
  68131. enumerable: true,
  68132. configurable: true
  68133. });
  68134. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68135. /**
  68136. * Gets wether the color grading effect is enabled.
  68137. */
  68138. get: function () {
  68139. return this.imageProcessingConfiguration.colorGradingEnabled;
  68140. },
  68141. /**
  68142. * Gets wether the color grading effect is enabled.
  68143. */
  68144. set: function (value) {
  68145. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68146. },
  68147. enumerable: true,
  68148. configurable: true
  68149. });
  68150. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68151. /**
  68152. * Gets exposure used in the effect.
  68153. */
  68154. get: function () {
  68155. return this.imageProcessingConfiguration.exposure;
  68156. },
  68157. /**
  68158. * Sets exposure used in the effect.
  68159. */
  68160. set: function (value) {
  68161. this.imageProcessingConfiguration.exposure = value;
  68162. },
  68163. enumerable: true,
  68164. configurable: true
  68165. });
  68166. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68167. /**
  68168. * Gets wether tonemapping is enabled or not.
  68169. */
  68170. get: function () {
  68171. return this._imageProcessingConfiguration.toneMappingEnabled;
  68172. },
  68173. /**
  68174. * Sets wether tonemapping is enabled or not
  68175. */
  68176. set: function (value) {
  68177. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68178. },
  68179. enumerable: true,
  68180. configurable: true
  68181. });
  68182. ;
  68183. ;
  68184. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68185. /**
  68186. * Gets contrast used in the effect.
  68187. */
  68188. get: function () {
  68189. return this.imageProcessingConfiguration.contrast;
  68190. },
  68191. /**
  68192. * Sets contrast used in the effect.
  68193. */
  68194. set: function (value) {
  68195. this.imageProcessingConfiguration.contrast = value;
  68196. },
  68197. enumerable: true,
  68198. configurable: true
  68199. });
  68200. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68201. /**
  68202. * Gets Vignette stretch size.
  68203. */
  68204. get: function () {
  68205. return this.imageProcessingConfiguration.vignetteStretch;
  68206. },
  68207. /**
  68208. * Sets Vignette stretch size.
  68209. */
  68210. set: function (value) {
  68211. this.imageProcessingConfiguration.vignetteStretch = value;
  68212. },
  68213. enumerable: true,
  68214. configurable: true
  68215. });
  68216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68217. /**
  68218. * Gets Vignette centre X Offset.
  68219. */
  68220. get: function () {
  68221. return this.imageProcessingConfiguration.vignetteCentreX;
  68222. },
  68223. /**
  68224. * Sets Vignette centre X Offset.
  68225. */
  68226. set: function (value) {
  68227. this.imageProcessingConfiguration.vignetteCentreX = value;
  68228. },
  68229. enumerable: true,
  68230. configurable: true
  68231. });
  68232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68233. /**
  68234. * Gets Vignette centre Y Offset.
  68235. */
  68236. get: function () {
  68237. return this.imageProcessingConfiguration.vignetteCentreY;
  68238. },
  68239. /**
  68240. * Sets Vignette centre Y Offset.
  68241. */
  68242. set: function (value) {
  68243. this.imageProcessingConfiguration.vignetteCentreY = value;
  68244. },
  68245. enumerable: true,
  68246. configurable: true
  68247. });
  68248. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68249. /**
  68250. * Gets Vignette weight or intensity of the vignette effect.
  68251. */
  68252. get: function () {
  68253. return this.imageProcessingConfiguration.vignetteWeight;
  68254. },
  68255. /**
  68256. * Sets Vignette weight or intensity of the vignette effect.
  68257. */
  68258. set: function (value) {
  68259. this.imageProcessingConfiguration.vignetteWeight = value;
  68260. },
  68261. enumerable: true,
  68262. configurable: true
  68263. });
  68264. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68265. /**
  68266. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68267. * if vignetteEnabled is set to true.
  68268. */
  68269. get: function () {
  68270. return this.imageProcessingConfiguration.vignetteColor;
  68271. },
  68272. /**
  68273. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68274. * if vignetteEnabled is set to true.
  68275. */
  68276. set: function (value) {
  68277. this.imageProcessingConfiguration.vignetteColor = value;
  68278. },
  68279. enumerable: true,
  68280. configurable: true
  68281. });
  68282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68283. /**
  68284. * Gets Camera field of view used by the Vignette effect.
  68285. */
  68286. get: function () {
  68287. return this.imageProcessingConfiguration.vignetteCameraFov;
  68288. },
  68289. /**
  68290. * Sets Camera field of view used by the Vignette effect.
  68291. */
  68292. set: function (value) {
  68293. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68294. },
  68295. enumerable: true,
  68296. configurable: true
  68297. });
  68298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68299. /**
  68300. * Gets the vignette blend mode allowing different kind of effect.
  68301. */
  68302. get: function () {
  68303. return this.imageProcessingConfiguration.vignetteBlendMode;
  68304. },
  68305. /**
  68306. * Sets the vignette blend mode allowing different kind of effect.
  68307. */
  68308. set: function (value) {
  68309. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68310. },
  68311. enumerable: true,
  68312. configurable: true
  68313. });
  68314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68315. /**
  68316. * Gets wether the vignette effect is enabled.
  68317. */
  68318. get: function () {
  68319. return this.imageProcessingConfiguration.vignetteEnabled;
  68320. },
  68321. /**
  68322. * Sets wether the vignette effect is enabled.
  68323. */
  68324. set: function (value) {
  68325. this.imageProcessingConfiguration.vignetteEnabled = value;
  68326. },
  68327. enumerable: true,
  68328. configurable: true
  68329. });
  68330. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68331. /**
  68332. * Gets wether the input of the processing is in Gamma or Linear Space.
  68333. */
  68334. get: function () {
  68335. return this._fromLinearSpace;
  68336. },
  68337. /**
  68338. * Sets wether the input of the processing is in Gamma or Linear Space.
  68339. */
  68340. set: function (value) {
  68341. if (this._fromLinearSpace === value) {
  68342. return;
  68343. }
  68344. this._fromLinearSpace = value;
  68345. this._updateParameters();
  68346. },
  68347. enumerable: true,
  68348. configurable: true
  68349. });
  68350. ImageProcessingPostProcess.prototype.getClassName = function () {
  68351. return "ImageProcessingPostProcess";
  68352. };
  68353. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68354. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68355. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68356. var defines = "";
  68357. for (var define in this._defines) {
  68358. if (this._defines[define]) {
  68359. defines += "#define " + define + ";\r\n";
  68360. }
  68361. }
  68362. var samplers = ["textureSampler"];
  68363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68364. var uniforms = ["scale"];
  68365. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68366. this.updateEffect(defines, uniforms, samplers);
  68367. };
  68368. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68369. _super.prototype.dispose.call(this, camera);
  68370. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68371. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68372. }
  68373. this.imageProcessingConfiguration.applyByPostProcess = false;
  68374. };
  68375. __decorate([
  68376. BABYLON.serialize()
  68377. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68378. return ImageProcessingPostProcess;
  68379. }(BABYLON.PostProcess));
  68380. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68381. })(BABYLON || (BABYLON = {}));
  68382. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68383. var BABYLON;
  68384. (function (BABYLON) {
  68385. /**
  68386. * The Blur Post Process which blurs an image based on a kernel and direction.
  68387. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68388. */
  68389. var BlurPostProcess = /** @class */ (function (_super) {
  68390. __extends(BlurPostProcess, _super);
  68391. /**
  68392. * Creates a new instance of @see BlurPostProcess
  68393. * @param name The name of the effect.
  68394. * @param direction The direction in which to blur the image.
  68395. * @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.
  68396. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68397. * @param camera The camera to apply the render pass to.
  68398. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68399. * @param engine The engine which the post process will be applied. (default: current engine)
  68400. * @param reusable If the post process can be reused on the same frame. (default: false)
  68401. * @param textureType Type of textures used when performing the post process. (default: 0)
  68402. */
  68403. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68406. if (defines === void 0) { defines = ""; }
  68407. 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;
  68408. _this.direction = direction;
  68409. _this._packedFloat = false;
  68410. _this._staticDefines = "";
  68411. _this._staticDefines = defines;
  68412. _this.onApplyObservable.add(function (effect) {
  68413. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68414. });
  68415. _this.kernel = kernel;
  68416. return _this;
  68417. }
  68418. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68419. /**
  68420. * Gets the length in pixels of the blur sample region
  68421. */
  68422. get: function () {
  68423. return this._idealKernel;
  68424. },
  68425. /**
  68426. * Sets the length in pixels of the blur sample region
  68427. */
  68428. set: function (v) {
  68429. if (this._idealKernel === v) {
  68430. return;
  68431. }
  68432. v = Math.max(v, 1);
  68433. this._idealKernel = v;
  68434. this._kernel = this._nearestBestKernel(v);
  68435. this._updateParameters();
  68436. },
  68437. enumerable: true,
  68438. configurable: true
  68439. });
  68440. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68441. /**
  68442. * Gets wether or not the blur is unpacking/repacking floats
  68443. */
  68444. get: function () {
  68445. return this._packedFloat;
  68446. },
  68447. /**
  68448. * Sets wether or not the blur needs to unpack/repack floats
  68449. */
  68450. set: function (v) {
  68451. if (this._packedFloat === v) {
  68452. return;
  68453. }
  68454. this._packedFloat = v;
  68455. this._updateParameters();
  68456. },
  68457. enumerable: true,
  68458. configurable: true
  68459. });
  68460. BlurPostProcess.prototype._updateParameters = function () {
  68461. // Generate sampling offsets and weights
  68462. var N = this._kernel;
  68463. var centerIndex = (N - 1) / 2;
  68464. // Generate Gaussian sampling weights over kernel
  68465. var offsets = [];
  68466. var weights = [];
  68467. var totalWeight = 0;
  68468. for (var i = 0; i < N; i++) {
  68469. var u = i / (N - 1);
  68470. var w = this._gaussianWeight(u * 2.0 - 1);
  68471. offsets[i] = (i - centerIndex);
  68472. weights[i] = w;
  68473. totalWeight += w;
  68474. }
  68475. // Normalize weights
  68476. for (var i = 0; i < weights.length; i++) {
  68477. weights[i] /= totalWeight;
  68478. }
  68479. // Optimize: combine samples to take advantage of hardware linear sampling
  68480. // Walk from left to center, combining pairs (symmetrically)
  68481. var linearSamplingWeights = [];
  68482. var linearSamplingOffsets = [];
  68483. var linearSamplingMap = [];
  68484. for (var i = 0; i <= centerIndex; i += 2) {
  68485. var j = Math.min(i + 1, Math.floor(centerIndex));
  68486. var singleCenterSample = i === j;
  68487. if (singleCenterSample) {
  68488. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68489. }
  68490. else {
  68491. var sharedCell = j === centerIndex;
  68492. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68493. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68494. if (offsetLinear === 0) {
  68495. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68496. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68497. }
  68498. else {
  68499. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68500. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68501. }
  68502. }
  68503. }
  68504. for (var i = 0; i < linearSamplingMap.length; i++) {
  68505. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68506. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68507. }
  68508. // Replace with optimized
  68509. offsets = linearSamplingOffsets;
  68510. weights = linearSamplingWeights;
  68511. // Generate shaders
  68512. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68513. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68514. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68515. var defines = "";
  68516. defines += this._staticDefines;
  68517. for (var i = 0; i < varyingCount; i++) {
  68518. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68519. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68520. }
  68521. var depCount = 0;
  68522. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68523. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68524. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68525. depCount++;
  68526. }
  68527. if (this.packedFloat) {
  68528. defines += "#define PACKEDFLOAT 1";
  68529. }
  68530. this.updateEffect(defines, null, null, {
  68531. varyingCount: varyingCount,
  68532. depCount: depCount
  68533. });
  68534. };
  68535. /**
  68536. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68537. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68538. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68539. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68540. * The gaps between physical kernels are compensated for in the weighting of the samples
  68541. * @param idealKernel Ideal blur kernel.
  68542. * @return Nearest best kernel.
  68543. */
  68544. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68545. var v = Math.round(idealKernel);
  68546. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68547. var k = _a[_i];
  68548. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68549. return Math.max(k, 3);
  68550. }
  68551. }
  68552. return Math.max(v, 3);
  68553. };
  68554. /**
  68555. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68556. * @param x The point on the Gaussian distribution to sample.
  68557. * @return the value of the Gaussian function at x.
  68558. */
  68559. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68560. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68561. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68562. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68563. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68564. // truncated at around 1.3% of peak strength.
  68565. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68566. var sigma = (1 / 3);
  68567. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68568. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68569. var weight = (1.0 / denominator) * Math.exp(exponent);
  68570. return weight;
  68571. };
  68572. /**
  68573. * Generates a string that can be used as a floating point number in GLSL.
  68574. * @param x Value to print.
  68575. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68576. * @return GLSL float string.
  68577. */
  68578. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68579. if (decimalFigures === void 0) { decimalFigures = 8; }
  68580. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68581. };
  68582. return BlurPostProcess;
  68583. }(BABYLON.PostProcess));
  68584. BABYLON.BlurPostProcess = BlurPostProcess;
  68585. })(BABYLON || (BABYLON = {}));
  68586. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68587. var BABYLON;
  68588. (function (BABYLON) {
  68589. /**
  68590. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68591. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68592. * based on samples that have a large difference in distance than the center pixel.
  68593. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68594. */
  68595. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68596. __extends(DepthOfFieldBlurPostProcess, _super);
  68597. /**
  68598. * Creates a new instance of @see CircleOfConfusionPostProcess
  68599. * @param name The name of the effect.
  68600. * @param scene The scene the effect belongs to.
  68601. * @param direction The direction the blur should be applied.
  68602. * @param kernel The size of the kernel used to blur.
  68603. * @param options The required width/height ratio to downsize to before computing the render pass.
  68604. * @param camera The camera to apply the render pass to.
  68605. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68606. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68607. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68608. * @param engine The engine which the post process will be applied. (default: current engine)
  68609. * @param reusable If the post process can be reused on the same frame. (default: false)
  68610. * @param textureType Type of textures used when performing the post process. (default: 0)
  68611. */
  68612. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  68613. if (imageToBlur === void 0) { imageToBlur = null; }
  68614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68615. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68616. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n") || this;
  68617. _this.direction = direction;
  68618. _this.onApplyObservable.add(function (effect) {
  68619. if (imageToBlur != null) {
  68620. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68621. }
  68622. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68623. if (scene.activeCamera) {
  68624. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68625. }
  68626. });
  68627. return _this;
  68628. }
  68629. return DepthOfFieldBlurPostProcess;
  68630. }(BABYLON.BlurPostProcess));
  68631. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68632. })(BABYLON || (BABYLON = {}));
  68633. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68634. var BABYLON;
  68635. (function (BABYLON) {
  68636. var Bone = /** @class */ (function (_super) {
  68637. __extends(Bone, _super);
  68638. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68639. if (parentBone === void 0) { parentBone = null; }
  68640. if (localMatrix === void 0) { localMatrix = null; }
  68641. if (restPose === void 0) { restPose = null; }
  68642. if (baseMatrix === void 0) { baseMatrix = null; }
  68643. if (index === void 0) { index = null; }
  68644. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68645. _this.name = name;
  68646. _this.children = new Array();
  68647. _this.animations = new Array();
  68648. // Set this value to map this bone to a different index in the transform matrices.
  68649. // Set this value to -1 to exclude the bone from the transform matrices.
  68650. _this._index = null;
  68651. _this._worldTransform = new BABYLON.Matrix();
  68652. _this._absoluteTransform = new BABYLON.Matrix();
  68653. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68654. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68655. _this._scaleVector = BABYLON.Vector3.One();
  68656. _this._negateScaleChildren = BABYLON.Vector3.One();
  68657. _this._scalingDeterminant = 1;
  68658. _this._skeleton = skeleton;
  68659. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68660. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68661. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68662. _this._index = index;
  68663. skeleton.bones.push(_this);
  68664. _this.setParent(parentBone, false);
  68665. _this._updateDifferenceMatrix();
  68666. return _this;
  68667. }
  68668. Object.defineProperty(Bone.prototype, "_matrix", {
  68669. get: function () {
  68670. return this._localMatrix;
  68671. },
  68672. set: function (val) {
  68673. if (this._localMatrix) {
  68674. this._localMatrix.copyFrom(val);
  68675. }
  68676. else {
  68677. this._localMatrix = val;
  68678. }
  68679. },
  68680. enumerable: true,
  68681. configurable: true
  68682. });
  68683. // Members
  68684. Bone.prototype.getSkeleton = function () {
  68685. return this._skeleton;
  68686. };
  68687. Bone.prototype.getParent = function () {
  68688. return this._parent;
  68689. };
  68690. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68691. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68692. if (this._parent === parent) {
  68693. return;
  68694. }
  68695. if (this._parent) {
  68696. var index = this._parent.children.indexOf(this);
  68697. if (index !== -1) {
  68698. this._parent.children.splice(index, 1);
  68699. }
  68700. }
  68701. this._parent = parent;
  68702. if (this._parent) {
  68703. this._parent.children.push(this);
  68704. }
  68705. if (updateDifferenceMatrix) {
  68706. this._updateDifferenceMatrix();
  68707. }
  68708. };
  68709. Bone.prototype.getLocalMatrix = function () {
  68710. return this._localMatrix;
  68711. };
  68712. Bone.prototype.getBaseMatrix = function () {
  68713. return this._baseMatrix;
  68714. };
  68715. Bone.prototype.getRestPose = function () {
  68716. return this._restPose;
  68717. };
  68718. Bone.prototype.returnToRest = function () {
  68719. this.updateMatrix(this._restPose.clone());
  68720. };
  68721. Bone.prototype.getWorldMatrix = function () {
  68722. return this._worldTransform;
  68723. };
  68724. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68725. return this._invertedAbsoluteTransform;
  68726. };
  68727. Bone.prototype.getAbsoluteTransform = function () {
  68728. return this._absoluteTransform;
  68729. };
  68730. Object.defineProperty(Bone.prototype, "position", {
  68731. // Properties (matches AbstractMesh properties)
  68732. get: function () {
  68733. return this.getPosition();
  68734. },
  68735. set: function (newPosition) {
  68736. this.setPosition(newPosition);
  68737. },
  68738. enumerable: true,
  68739. configurable: true
  68740. });
  68741. Object.defineProperty(Bone.prototype, "rotation", {
  68742. get: function () {
  68743. return this.getRotation();
  68744. },
  68745. set: function (newRotation) {
  68746. this.setRotation(newRotation);
  68747. },
  68748. enumerable: true,
  68749. configurable: true
  68750. });
  68751. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68752. get: function () {
  68753. return this.getRotationQuaternion();
  68754. },
  68755. set: function (newRotation) {
  68756. this.setRotationQuaternion(newRotation);
  68757. },
  68758. enumerable: true,
  68759. configurable: true
  68760. });
  68761. Object.defineProperty(Bone.prototype, "scaling", {
  68762. get: function () {
  68763. return this.getScale();
  68764. },
  68765. set: function (newScaling) {
  68766. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68767. },
  68768. enumerable: true,
  68769. configurable: true
  68770. });
  68771. // Methods
  68772. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68773. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68774. this._baseMatrix = matrix.clone();
  68775. this._localMatrix = matrix.clone();
  68776. this._skeleton._markAsDirty();
  68777. if (updateDifferenceMatrix) {
  68778. this._updateDifferenceMatrix();
  68779. }
  68780. };
  68781. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68782. if (!rootMatrix) {
  68783. rootMatrix = this._baseMatrix;
  68784. }
  68785. if (this._parent) {
  68786. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68787. }
  68788. else {
  68789. this._absoluteTransform.copyFrom(rootMatrix);
  68790. }
  68791. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68792. for (var index = 0; index < this.children.length; index++) {
  68793. this.children[index]._updateDifferenceMatrix();
  68794. }
  68795. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68796. };
  68797. Bone.prototype.markAsDirty = function () {
  68798. this._currentRenderId++;
  68799. this._skeleton._markAsDirty();
  68800. };
  68801. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68802. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68803. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68804. // all animation may be coming from a library skeleton, so may need to create animation
  68805. if (this.animations.length === 0) {
  68806. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68807. this.animations[0].setKeys([]);
  68808. }
  68809. // get animation info / verify there is such a range from the source bone
  68810. var sourceRange = source.animations[0].getRange(rangeName);
  68811. if (!sourceRange) {
  68812. return false;
  68813. }
  68814. var from = sourceRange.from;
  68815. var to = sourceRange.to;
  68816. var sourceKeys = source.animations[0].getKeys();
  68817. // rescaling prep
  68818. var sourceBoneLength = source.length;
  68819. var sourceParent = source.getParent();
  68820. var parent = this.getParent();
  68821. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68822. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68823. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68824. var destKeys = this.animations[0].getKeys();
  68825. // loop vars declaration
  68826. var orig;
  68827. var origTranslation;
  68828. var mat;
  68829. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68830. orig = sourceKeys[key];
  68831. if (orig.frame >= from && orig.frame <= to) {
  68832. if (rescaleAsRequired) {
  68833. mat = orig.value.clone();
  68834. // scale based on parent ratio, when bone has parent
  68835. if (parentScalingReqd) {
  68836. origTranslation = mat.getTranslation();
  68837. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68838. // scale based on skeleton dimension ratio when root bone, and value is passed
  68839. }
  68840. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68841. origTranslation = mat.getTranslation();
  68842. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68843. // use original when root bone, and no data for skelDimensionsRatio
  68844. }
  68845. else {
  68846. mat = orig.value;
  68847. }
  68848. }
  68849. else {
  68850. mat = orig.value;
  68851. }
  68852. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68853. }
  68854. }
  68855. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68856. return true;
  68857. };
  68858. /**
  68859. * Translate the bone in local or world space.
  68860. * @param vec The amount to translate the bone.
  68861. * @param space The space that the translation is in.
  68862. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68863. */
  68864. Bone.prototype.translate = function (vec, space, mesh) {
  68865. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68866. var lm = this.getLocalMatrix();
  68867. if (space == BABYLON.Space.LOCAL) {
  68868. lm.m[12] += vec.x;
  68869. lm.m[13] += vec.y;
  68870. lm.m[14] += vec.z;
  68871. }
  68872. else {
  68873. var wm = null;
  68874. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68875. if (mesh) {
  68876. wm = mesh.getWorldMatrix();
  68877. }
  68878. this._skeleton.computeAbsoluteTransforms();
  68879. var tmat = Bone._tmpMats[0];
  68880. var tvec = Bone._tmpVecs[0];
  68881. if (this._parent) {
  68882. if (mesh && wm) {
  68883. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68884. tmat.multiplyToRef(wm, tmat);
  68885. }
  68886. else {
  68887. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68888. }
  68889. }
  68890. tmat.m[12] = 0;
  68891. tmat.m[13] = 0;
  68892. tmat.m[14] = 0;
  68893. tmat.invert();
  68894. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68895. lm.m[12] += tvec.x;
  68896. lm.m[13] += tvec.y;
  68897. lm.m[14] += tvec.z;
  68898. }
  68899. this.markAsDirty();
  68900. };
  68901. /**
  68902. * Set the postion of the bone in local or world space.
  68903. * @param position The position to set the bone.
  68904. * @param space The space that the position is in.
  68905. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68906. */
  68907. Bone.prototype.setPosition = function (position, space, mesh) {
  68908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68909. var lm = this.getLocalMatrix();
  68910. if (space == BABYLON.Space.LOCAL) {
  68911. lm.m[12] = position.x;
  68912. lm.m[13] = position.y;
  68913. lm.m[14] = position.z;
  68914. }
  68915. else {
  68916. var wm = null;
  68917. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68918. if (mesh) {
  68919. wm = mesh.getWorldMatrix();
  68920. }
  68921. this._skeleton.computeAbsoluteTransforms();
  68922. var tmat = Bone._tmpMats[0];
  68923. var vec = Bone._tmpVecs[0];
  68924. if (this._parent) {
  68925. if (mesh && wm) {
  68926. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68927. tmat.multiplyToRef(wm, tmat);
  68928. }
  68929. else {
  68930. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68931. }
  68932. }
  68933. tmat.invert();
  68934. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68935. lm.m[12] = vec.x;
  68936. lm.m[13] = vec.y;
  68937. lm.m[14] = vec.z;
  68938. }
  68939. this.markAsDirty();
  68940. };
  68941. /**
  68942. * Set the absolute postion of the bone (world space).
  68943. * @param position The position to set the bone.
  68944. * @param mesh The mesh that this bone is attached to.
  68945. */
  68946. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68947. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68948. };
  68949. /**
  68950. * Set the scale of the bone on the x, y and z axes.
  68951. * @param x The scale of the bone on the x axis.
  68952. * @param x The scale of the bone on the y axis.
  68953. * @param z The scale of the bone on the z axis.
  68954. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68955. */
  68956. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68957. if (scaleChildren === void 0) { scaleChildren = false; }
  68958. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68959. if (!scaleChildren) {
  68960. this._negateScaleChildren.x = 1 / x;
  68961. this._negateScaleChildren.y = 1 / y;
  68962. this._negateScaleChildren.z = 1 / z;
  68963. }
  68964. this._syncScaleVector();
  68965. }
  68966. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68967. };
  68968. /**
  68969. * Scale the bone on the x, y and z axes.
  68970. * @param x The amount to scale the bone on the x axis.
  68971. * @param x The amount to scale the bone on the y axis.
  68972. * @param z The amount to scale the bone on the z axis.
  68973. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68974. */
  68975. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68976. if (scaleChildren === void 0) { scaleChildren = false; }
  68977. var locMat = this.getLocalMatrix();
  68978. var origLocMat = Bone._tmpMats[0];
  68979. origLocMat.copyFrom(locMat);
  68980. var origLocMatInv = Bone._tmpMats[1];
  68981. origLocMatInv.copyFrom(origLocMat);
  68982. origLocMatInv.invert();
  68983. var scaleMat = Bone._tmpMats[2];
  68984. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68985. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68986. this._scaleVector.x *= x;
  68987. this._scaleVector.y *= y;
  68988. this._scaleVector.z *= z;
  68989. locMat.multiplyToRef(origLocMatInv, locMat);
  68990. locMat.multiplyToRef(scaleMat, locMat);
  68991. locMat.multiplyToRef(origLocMat, locMat);
  68992. var parent = this.getParent();
  68993. if (parent) {
  68994. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68995. }
  68996. else {
  68997. this.getAbsoluteTransform().copyFrom(locMat);
  68998. }
  68999. var len = this.children.length;
  69000. scaleMat.invert();
  69001. for (var i = 0; i < len; i++) {
  69002. var child = this.children[i];
  69003. var cm = child.getLocalMatrix();
  69004. cm.multiplyToRef(scaleMat, cm);
  69005. var lm = child.getLocalMatrix();
  69006. lm.m[12] *= x;
  69007. lm.m[13] *= y;
  69008. lm.m[14] *= z;
  69009. }
  69010. this.computeAbsoluteTransforms();
  69011. if (scaleChildren) {
  69012. for (var i = 0; i < len; i++) {
  69013. this.children[i].scale(x, y, z, scaleChildren);
  69014. }
  69015. }
  69016. this.markAsDirty();
  69017. };
  69018. /**
  69019. * Set the yaw, pitch, and roll of the bone in local or world space.
  69020. * @param yaw The rotation of the bone on the y axis.
  69021. * @param pitch The rotation of the bone on the x axis.
  69022. * @param roll The rotation of the bone on the z axis.
  69023. * @param space The space that the axes of rotation are in.
  69024. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69025. */
  69026. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69028. var rotMat = Bone._tmpMats[0];
  69029. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69030. var rotMatInv = Bone._tmpMats[1];
  69031. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69032. rotMatInv.multiplyToRef(rotMat, rotMat);
  69033. this._rotateWithMatrix(rotMat, space, mesh);
  69034. };
  69035. /**
  69036. * Rotate the bone on an axis in local or world space.
  69037. * @param axis The axis to rotate the bone on.
  69038. * @param amount The amount to rotate the bone.
  69039. * @param space The space that the axis is in.
  69040. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69041. */
  69042. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69043. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69044. var rmat = Bone._tmpMats[0];
  69045. rmat.m[12] = 0;
  69046. rmat.m[13] = 0;
  69047. rmat.m[14] = 0;
  69048. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69049. this._rotateWithMatrix(rmat, space, mesh);
  69050. };
  69051. /**
  69052. * Set the rotation of the bone to a particular axis angle in local or world space.
  69053. * @param axis The axis to rotate the bone on.
  69054. * @param angle The angle that the bone should be rotated to.
  69055. * @param space The space that the axis is in.
  69056. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69057. */
  69058. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69060. var rotMat = Bone._tmpMats[0];
  69061. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69062. var rotMatInv = Bone._tmpMats[1];
  69063. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69064. rotMatInv.multiplyToRef(rotMat, rotMat);
  69065. this._rotateWithMatrix(rotMat, space, mesh);
  69066. };
  69067. /**
  69068. * Set the euler rotation of the bone in local of world space.
  69069. * @param rotation The euler rotation that the bone should be set to.
  69070. * @param space The space that the rotation is in.
  69071. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69072. */
  69073. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69074. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69075. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69076. };
  69077. /**
  69078. * Set the quaternion rotation of the bone in local of world space.
  69079. * @param quat The quaternion rotation that the bone should be set to.
  69080. * @param space The space that the rotation is in.
  69081. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69082. */
  69083. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69085. var rotMatInv = Bone._tmpMats[0];
  69086. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69087. var rotMat = Bone._tmpMats[1];
  69088. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69089. rotMatInv.multiplyToRef(rotMat, rotMat);
  69090. this._rotateWithMatrix(rotMat, space, mesh);
  69091. };
  69092. /**
  69093. * Set the rotation matrix of the bone in local of world space.
  69094. * @param rotMat The rotation matrix that the bone should be set to.
  69095. * @param space The space that the rotation is in.
  69096. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69097. */
  69098. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69099. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69100. var rotMatInv = Bone._tmpMats[0];
  69101. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69102. var rotMat2 = Bone._tmpMats[1];
  69103. rotMat2.copyFrom(rotMat);
  69104. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69105. this._rotateWithMatrix(rotMat2, space, mesh);
  69106. };
  69107. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69109. var lmat = this.getLocalMatrix();
  69110. var lx = lmat.m[12];
  69111. var ly = lmat.m[13];
  69112. var lz = lmat.m[14];
  69113. var parent = this.getParent();
  69114. var parentScale = Bone._tmpMats[3];
  69115. var parentScaleInv = Bone._tmpMats[4];
  69116. if (parent) {
  69117. if (space == BABYLON.Space.WORLD) {
  69118. if (mesh) {
  69119. parentScale.copyFrom(mesh.getWorldMatrix());
  69120. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69121. }
  69122. else {
  69123. parentScale.copyFrom(parent.getAbsoluteTransform());
  69124. }
  69125. }
  69126. else {
  69127. parentScale = parent._scaleMatrix;
  69128. }
  69129. parentScaleInv.copyFrom(parentScale);
  69130. parentScaleInv.invert();
  69131. lmat.multiplyToRef(parentScale, lmat);
  69132. lmat.multiplyToRef(rmat, lmat);
  69133. lmat.multiplyToRef(parentScaleInv, lmat);
  69134. }
  69135. else {
  69136. if (space == BABYLON.Space.WORLD && mesh) {
  69137. parentScale.copyFrom(mesh.getWorldMatrix());
  69138. parentScaleInv.copyFrom(parentScale);
  69139. parentScaleInv.invert();
  69140. lmat.multiplyToRef(parentScale, lmat);
  69141. lmat.multiplyToRef(rmat, lmat);
  69142. lmat.multiplyToRef(parentScaleInv, lmat);
  69143. }
  69144. else {
  69145. lmat.multiplyToRef(rmat, lmat);
  69146. }
  69147. }
  69148. lmat.m[12] = lx;
  69149. lmat.m[13] = ly;
  69150. lmat.m[14] = lz;
  69151. this.computeAbsoluteTransforms();
  69152. this.markAsDirty();
  69153. };
  69154. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69155. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69156. if (space == BABYLON.Space.WORLD) {
  69157. var scaleMatrix = Bone._tmpMats[2];
  69158. scaleMatrix.copyFrom(this._scaleMatrix);
  69159. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69160. if (mesh) {
  69161. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69162. var meshScale = Bone._tmpMats[3];
  69163. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69164. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69165. }
  69166. rotMatInv.invert();
  69167. scaleMatrix.m[0] *= this._scalingDeterminant;
  69168. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69169. }
  69170. else {
  69171. rotMatInv.copyFrom(this.getLocalMatrix());
  69172. rotMatInv.invert();
  69173. var scaleMatrix = Bone._tmpMats[2];
  69174. scaleMatrix.copyFrom(this._scaleMatrix);
  69175. if (this._parent) {
  69176. var pscaleMatrix = Bone._tmpMats[3];
  69177. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69178. pscaleMatrix.invert();
  69179. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69180. }
  69181. else {
  69182. scaleMatrix.m[0] *= this._scalingDeterminant;
  69183. }
  69184. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69185. }
  69186. };
  69187. /**
  69188. * Get the scale of the bone
  69189. * @returns the scale of the bone
  69190. */
  69191. Bone.prototype.getScale = function () {
  69192. return this._scaleVector.clone();
  69193. };
  69194. /**
  69195. * Copy the scale of the bone to a vector3.
  69196. * @param result The vector3 to copy the scale to
  69197. */
  69198. Bone.prototype.getScaleToRef = function (result) {
  69199. result.copyFrom(this._scaleVector);
  69200. };
  69201. /**
  69202. * Get the position of the bone in local or world space.
  69203. * @param space The space that the returned position is in.
  69204. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69205. * @returns The position of the bone
  69206. */
  69207. Bone.prototype.getPosition = function (space, mesh) {
  69208. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69209. if (mesh === void 0) { mesh = null; }
  69210. var pos = BABYLON.Vector3.Zero();
  69211. this.getPositionToRef(space, mesh, pos);
  69212. return pos;
  69213. };
  69214. /**
  69215. * Copy the position of the bone to a vector3 in local or world space.
  69216. * @param space The space that the returned position is in.
  69217. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69218. * @param result The vector3 to copy the position to.
  69219. */
  69220. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69222. if (space == BABYLON.Space.LOCAL) {
  69223. var lm = this.getLocalMatrix();
  69224. result.x = lm.m[12];
  69225. result.y = lm.m[13];
  69226. result.z = lm.m[14];
  69227. }
  69228. else {
  69229. var wm = null;
  69230. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69231. if (mesh) {
  69232. wm = mesh.getWorldMatrix();
  69233. }
  69234. this._skeleton.computeAbsoluteTransforms();
  69235. var tmat = Bone._tmpMats[0];
  69236. if (mesh && wm) {
  69237. tmat.copyFrom(this.getAbsoluteTransform());
  69238. tmat.multiplyToRef(wm, tmat);
  69239. }
  69240. else {
  69241. tmat = this.getAbsoluteTransform();
  69242. }
  69243. result.x = tmat.m[12];
  69244. result.y = tmat.m[13];
  69245. result.z = tmat.m[14];
  69246. }
  69247. };
  69248. /**
  69249. * Get the absolute position of the bone (world space).
  69250. * @param mesh The mesh that this bone is attached to.
  69251. * @returns The absolute position of the bone
  69252. */
  69253. Bone.prototype.getAbsolutePosition = function (mesh) {
  69254. if (mesh === void 0) { mesh = null; }
  69255. var pos = BABYLON.Vector3.Zero();
  69256. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69257. return pos;
  69258. };
  69259. /**
  69260. * Copy the absolute position of the bone (world space) to the result param.
  69261. * @param mesh The mesh that this bone is attached to.
  69262. * @param result The vector3 to copy the absolute position to.
  69263. */
  69264. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69265. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69266. };
  69267. /**
  69268. * Compute the absolute transforms of this bone and its children.
  69269. */
  69270. Bone.prototype.computeAbsoluteTransforms = function () {
  69271. if (this._parent) {
  69272. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69273. }
  69274. else {
  69275. this._absoluteTransform.copyFrom(this._localMatrix);
  69276. var poseMatrix = this._skeleton.getPoseMatrix();
  69277. if (poseMatrix) {
  69278. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69279. }
  69280. }
  69281. var children = this.children;
  69282. var len = children.length;
  69283. for (var i = 0; i < len; i++) {
  69284. children[i].computeAbsoluteTransforms();
  69285. }
  69286. };
  69287. Bone.prototype._syncScaleVector = function () {
  69288. var lm = this.getLocalMatrix();
  69289. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69290. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69291. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69292. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69293. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69294. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69295. this._scaleVector.x = xs * Math.sqrt(xsq);
  69296. this._scaleVector.y = ys * Math.sqrt(ysq);
  69297. this._scaleVector.z = zs * Math.sqrt(zsq);
  69298. if (this._parent) {
  69299. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69300. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69301. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69302. }
  69303. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  69304. };
  69305. /**
  69306. * Get the world direction from an axis that is in the local space of the bone.
  69307. * @param localAxis The local direction that is used to compute the world direction.
  69308. * @param mesh The mesh that this bone is attached to.
  69309. * @returns The world direction
  69310. */
  69311. Bone.prototype.getDirection = function (localAxis, mesh) {
  69312. if (mesh === void 0) { mesh = null; }
  69313. var result = BABYLON.Vector3.Zero();
  69314. this.getDirectionToRef(localAxis, mesh, result);
  69315. return result;
  69316. };
  69317. /**
  69318. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69319. * @param localAxis The local direction that is used to compute the world direction.
  69320. * @param mesh The mesh that this bone is attached to.
  69321. * @param result The vector3 that the world direction will be copied to.
  69322. */
  69323. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69324. if (mesh === void 0) { mesh = null; }
  69325. var wm = null;
  69326. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69327. if (mesh) {
  69328. wm = mesh.getWorldMatrix();
  69329. }
  69330. this._skeleton.computeAbsoluteTransforms();
  69331. var mat = Bone._tmpMats[0];
  69332. mat.copyFrom(this.getAbsoluteTransform());
  69333. if (mesh && wm) {
  69334. mat.multiplyToRef(wm, mat);
  69335. }
  69336. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69337. result.normalize();
  69338. };
  69339. /**
  69340. * Get the euler rotation of the bone in local or world space.
  69341. * @param space The space that the rotation should be in.
  69342. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69343. * @returns The euler rotation
  69344. */
  69345. Bone.prototype.getRotation = function (space, mesh) {
  69346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69347. if (mesh === void 0) { mesh = null; }
  69348. var result = BABYLON.Vector3.Zero();
  69349. this.getRotationToRef(space, mesh, result);
  69350. return result;
  69351. };
  69352. /**
  69353. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69354. * @param space The space that the rotation should be in.
  69355. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69356. * @param result The vector3 that the rotation should be copied to.
  69357. */
  69358. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69360. if (mesh === void 0) { mesh = null; }
  69361. var quat = Bone._tmpQuat;
  69362. this.getRotationQuaternionToRef(space, mesh, quat);
  69363. quat.toEulerAnglesToRef(result);
  69364. };
  69365. /**
  69366. * Get the quaternion rotation of the bone in either local or world space.
  69367. * @param space The space that the rotation should be in.
  69368. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69369. * @returns The quaternion rotation
  69370. */
  69371. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69373. if (mesh === void 0) { mesh = null; }
  69374. var result = BABYLON.Quaternion.Identity();
  69375. this.getRotationQuaternionToRef(space, mesh, result);
  69376. return result;
  69377. };
  69378. /**
  69379. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69380. * @param space The space that the rotation should be in.
  69381. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69382. * @param result The quaternion that the rotation should be copied to.
  69383. */
  69384. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69385. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69386. if (mesh === void 0) { mesh = null; }
  69387. if (space == BABYLON.Space.LOCAL) {
  69388. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69389. }
  69390. else {
  69391. var mat = Bone._tmpMats[0];
  69392. var amat = this.getAbsoluteTransform();
  69393. if (mesh) {
  69394. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69395. }
  69396. else {
  69397. mat.copyFrom(amat);
  69398. }
  69399. mat.m[0] *= this._scalingDeterminant;
  69400. mat.m[1] *= this._scalingDeterminant;
  69401. mat.m[2] *= this._scalingDeterminant;
  69402. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69403. }
  69404. };
  69405. /**
  69406. * Get the rotation matrix of the bone in local or world space.
  69407. * @param space The space that the rotation should be in.
  69408. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69409. * @returns The rotation matrix
  69410. */
  69411. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69412. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69413. var result = BABYLON.Matrix.Identity();
  69414. this.getRotationMatrixToRef(space, mesh, result);
  69415. return result;
  69416. };
  69417. /**
  69418. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69419. * @param space The space that the rotation should be in.
  69420. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69421. * @param result The quaternion that the rotation should be copied to.
  69422. */
  69423. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69424. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69425. if (space == BABYLON.Space.LOCAL) {
  69426. this.getLocalMatrix().getRotationMatrixToRef(result);
  69427. }
  69428. else {
  69429. var mat = Bone._tmpMats[0];
  69430. var amat = this.getAbsoluteTransform();
  69431. if (mesh) {
  69432. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69433. }
  69434. else {
  69435. mat.copyFrom(amat);
  69436. }
  69437. mat.m[0] *= this._scalingDeterminant;
  69438. mat.m[1] *= this._scalingDeterminant;
  69439. mat.m[2] *= this._scalingDeterminant;
  69440. mat.getRotationMatrixToRef(result);
  69441. }
  69442. };
  69443. /**
  69444. * Get the world position of a point that is in the local space of the bone.
  69445. * @param position The local position
  69446. * @param mesh The mesh that this bone is attached to.
  69447. * @returns The world position
  69448. */
  69449. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69450. if (mesh === void 0) { mesh = null; }
  69451. var result = BABYLON.Vector3.Zero();
  69452. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69453. return result;
  69454. };
  69455. /**
  69456. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69457. * @param position The local position
  69458. * @param mesh The mesh that this bone is attached to.
  69459. * @param result The vector3 that the world position should be copied to.
  69460. */
  69461. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69462. if (mesh === void 0) { mesh = null; }
  69463. var wm = null;
  69464. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69465. if (mesh) {
  69466. wm = mesh.getWorldMatrix();
  69467. }
  69468. this._skeleton.computeAbsoluteTransforms();
  69469. var tmat = Bone._tmpMats[0];
  69470. if (mesh && wm) {
  69471. tmat.copyFrom(this.getAbsoluteTransform());
  69472. tmat.multiplyToRef(wm, tmat);
  69473. }
  69474. else {
  69475. tmat = this.getAbsoluteTransform();
  69476. }
  69477. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69478. };
  69479. /**
  69480. * Get the local position of a point that is in world space.
  69481. * @param position The world position
  69482. * @param mesh The mesh that this bone is attached to.
  69483. * @returns The local position
  69484. */
  69485. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69486. if (mesh === void 0) { mesh = null; }
  69487. var result = BABYLON.Vector3.Zero();
  69488. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69489. return result;
  69490. };
  69491. /**
  69492. * Get the local position of a point that is in world space and copy it to the result param.
  69493. * @param position The world position
  69494. * @param mesh The mesh that this bone is attached to.
  69495. * @param result The vector3 that the local position should be copied to.
  69496. */
  69497. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69498. if (mesh === void 0) { mesh = null; }
  69499. var wm = null;
  69500. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69501. if (mesh) {
  69502. wm = mesh.getWorldMatrix();
  69503. }
  69504. this._skeleton.computeAbsoluteTransforms();
  69505. var tmat = Bone._tmpMats[0];
  69506. tmat.copyFrom(this.getAbsoluteTransform());
  69507. if (mesh && wm) {
  69508. tmat.multiplyToRef(wm, tmat);
  69509. }
  69510. tmat.invert();
  69511. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69512. };
  69513. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69514. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69515. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69516. return Bone;
  69517. }(BABYLON.Node));
  69518. BABYLON.Bone = Bone;
  69519. })(BABYLON || (BABYLON = {}));
  69520. //# sourceMappingURL=babylon.bone.js.map
  69521. var BABYLON;
  69522. (function (BABYLON) {
  69523. var BoneIKController = /** @class */ (function () {
  69524. function BoneIKController(mesh, bone, options) {
  69525. this.targetPosition = BABYLON.Vector3.Zero();
  69526. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69527. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69528. this.poleAngle = 0;
  69529. this.slerpAmount = 1;
  69530. this._bone1Quat = BABYLON.Quaternion.Identity();
  69531. this._bone1Mat = BABYLON.Matrix.Identity();
  69532. this._bone2Ang = Math.PI;
  69533. this._maxAngle = Math.PI;
  69534. this._rightHandedSystem = false;
  69535. this._bendAxis = BABYLON.Vector3.Right();
  69536. this._slerping = false;
  69537. this._adjustRoll = 0;
  69538. this._bone2 = bone;
  69539. this._bone1 = bone.getParent();
  69540. if (!this._bone1) {
  69541. return;
  69542. }
  69543. this.mesh = mesh;
  69544. var bonePos = bone.getPosition();
  69545. if (bone.getAbsoluteTransform().determinant() > 0) {
  69546. this._rightHandedSystem = true;
  69547. this._bendAxis.x = 0;
  69548. this._bendAxis.y = 0;
  69549. this._bendAxis.z = -1;
  69550. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69551. this._adjustRoll = Math.PI * .5;
  69552. this._bendAxis.z = 1;
  69553. }
  69554. }
  69555. if (this._bone1.length) {
  69556. var boneScale1 = this._bone1.getScale();
  69557. var boneScale2 = this._bone2.getScale();
  69558. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69559. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69560. }
  69561. else if (this._bone1.children[0]) {
  69562. mesh.computeWorldMatrix(true);
  69563. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69564. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69565. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69566. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69567. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69568. }
  69569. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69570. this.maxAngle = Math.PI;
  69571. if (options) {
  69572. if (options.targetMesh) {
  69573. this.targetMesh = options.targetMesh;
  69574. this.targetMesh.computeWorldMatrix(true);
  69575. }
  69576. if (options.poleTargetMesh) {
  69577. this.poleTargetMesh = options.poleTargetMesh;
  69578. this.poleTargetMesh.computeWorldMatrix(true);
  69579. }
  69580. else if (options.poleTargetBone) {
  69581. this.poleTargetBone = options.poleTargetBone;
  69582. }
  69583. else if (this._bone1.getParent()) {
  69584. this.poleTargetBone = this._bone1.getParent();
  69585. }
  69586. if (options.poleTargetLocalOffset) {
  69587. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69588. }
  69589. if (options.poleAngle) {
  69590. this.poleAngle = options.poleAngle;
  69591. }
  69592. if (options.bendAxis) {
  69593. this._bendAxis.copyFrom(options.bendAxis);
  69594. }
  69595. if (options.maxAngle) {
  69596. this.maxAngle = options.maxAngle;
  69597. }
  69598. if (options.slerpAmount) {
  69599. this.slerpAmount = options.slerpAmount;
  69600. }
  69601. }
  69602. }
  69603. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69604. get: function () {
  69605. return this._maxAngle;
  69606. },
  69607. set: function (value) {
  69608. this._setMaxAngle(value);
  69609. },
  69610. enumerable: true,
  69611. configurable: true
  69612. });
  69613. BoneIKController.prototype._setMaxAngle = function (ang) {
  69614. if (ang < 0) {
  69615. ang = 0;
  69616. }
  69617. if (ang > Math.PI || ang == undefined) {
  69618. ang = Math.PI;
  69619. }
  69620. this._maxAngle = ang;
  69621. var a = this._bone1Length;
  69622. var b = this._bone2Length;
  69623. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69624. };
  69625. BoneIKController.prototype.update = function () {
  69626. var bone1 = this._bone1;
  69627. if (!bone1) {
  69628. return;
  69629. }
  69630. var target = this.targetPosition;
  69631. var poleTarget = this.poleTargetPosition;
  69632. var mat1 = BoneIKController._tmpMats[0];
  69633. var mat2 = BoneIKController._tmpMats[1];
  69634. if (this.targetMesh) {
  69635. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69636. }
  69637. if (this.poleTargetBone) {
  69638. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69639. }
  69640. else if (this.poleTargetMesh) {
  69641. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69642. }
  69643. var bonePos = BoneIKController._tmpVecs[0];
  69644. var zaxis = BoneIKController._tmpVecs[1];
  69645. var xaxis = BoneIKController._tmpVecs[2];
  69646. var yaxis = BoneIKController._tmpVecs[3];
  69647. var upAxis = BoneIKController._tmpVecs[4];
  69648. var _tmpQuat = BoneIKController._tmpQuat;
  69649. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69650. poleTarget.subtractToRef(bonePos, upAxis);
  69651. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69652. upAxis.y = 1;
  69653. }
  69654. else {
  69655. upAxis.normalize();
  69656. }
  69657. target.subtractToRef(bonePos, yaxis);
  69658. yaxis.normalize();
  69659. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69660. zaxis.normalize();
  69661. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69662. xaxis.normalize();
  69663. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69664. var a = this._bone1Length;
  69665. var b = this._bone2Length;
  69666. var c = BABYLON.Vector3.Distance(bonePos, target);
  69667. if (this._maxReach > 0) {
  69668. c = Math.min(this._maxReach, c);
  69669. }
  69670. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69671. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69672. if (acosa > 1) {
  69673. acosa = 1;
  69674. }
  69675. if (acosb > 1) {
  69676. acosb = 1;
  69677. }
  69678. if (acosa < -1) {
  69679. acosa = -1;
  69680. }
  69681. if (acosb < -1) {
  69682. acosb = -1;
  69683. }
  69684. var angA = Math.acos(acosa);
  69685. var angB = Math.acos(acosb);
  69686. var angC = -angA - angB;
  69687. if (this._rightHandedSystem) {
  69688. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69689. mat2.multiplyToRef(mat1, mat1);
  69690. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69691. mat2.multiplyToRef(mat1, mat1);
  69692. }
  69693. else {
  69694. var _tmpVec = BoneIKController._tmpVecs[5];
  69695. _tmpVec.copyFrom(this._bendAxis);
  69696. _tmpVec.x *= -1;
  69697. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69698. mat2.multiplyToRef(mat1, mat1);
  69699. }
  69700. if (this.poleAngle) {
  69701. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69702. mat1.multiplyToRef(mat2, mat1);
  69703. }
  69704. if (this._bone1) {
  69705. if (this.slerpAmount < 1) {
  69706. if (!this._slerping) {
  69707. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69708. }
  69709. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69710. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69711. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69712. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69713. this._slerping = true;
  69714. }
  69715. else {
  69716. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69717. this._bone1Mat.copyFrom(mat1);
  69718. this._slerping = false;
  69719. }
  69720. }
  69721. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69722. this._bone2Ang = angC;
  69723. };
  69724. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69725. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69726. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69727. return BoneIKController;
  69728. }());
  69729. BABYLON.BoneIKController = BoneIKController;
  69730. })(BABYLON || (BABYLON = {}));
  69731. //# sourceMappingURL=babylon.boneIKController.js.map
  69732. var BABYLON;
  69733. (function (BABYLON) {
  69734. var BoneLookController = /** @class */ (function () {
  69735. /**
  69736. * Create a BoneLookController
  69737. * @param mesh the mesh that the bone belongs to
  69738. * @param bone the bone that will be looking to the target
  69739. * @param target the target Vector3 to look at
  69740. * @param settings optional settings:
  69741. * - maxYaw: the maximum angle the bone will yaw to
  69742. * - minYaw: the minimum angle the bone will yaw to
  69743. * - maxPitch: the maximum angle the bone will pitch to
  69744. * - minPitch: the minimum angle the bone will yaw to
  69745. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69746. * - upAxis: the up axis of the coordinate system
  69747. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69748. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69749. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69750. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69751. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69752. * - adjustRoll: used to make an adjustment to the roll of the bone
  69753. **/
  69754. function BoneLookController(mesh, bone, target, options) {
  69755. /**
  69756. * The up axis of the coordinate system that is used when the bone is rotated.
  69757. */
  69758. this.upAxis = BABYLON.Vector3.Up();
  69759. /**
  69760. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69761. */
  69762. this.upAxisSpace = BABYLON.Space.LOCAL;
  69763. /**
  69764. * Used to make an adjustment to the yaw of the bone.
  69765. */
  69766. this.adjustYaw = 0;
  69767. /**
  69768. * Used to make an adjustment to the pitch of the bone.
  69769. */
  69770. this.adjustPitch = 0;
  69771. /**
  69772. * Used to make an adjustment to the roll of the bone.
  69773. */
  69774. this.adjustRoll = 0;
  69775. /**
  69776. * 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).
  69777. */
  69778. this.slerpAmount = 1;
  69779. this._boneQuat = BABYLON.Quaternion.Identity();
  69780. this._slerping = false;
  69781. this._firstFrameSkipped = false;
  69782. this._fowardAxis = BABYLON.Vector3.Forward();
  69783. this.mesh = mesh;
  69784. this.bone = bone;
  69785. this.target = target;
  69786. if (options) {
  69787. if (options.adjustYaw) {
  69788. this.adjustYaw = options.adjustYaw;
  69789. }
  69790. if (options.adjustPitch) {
  69791. this.adjustPitch = options.adjustPitch;
  69792. }
  69793. if (options.adjustRoll) {
  69794. this.adjustRoll = options.adjustRoll;
  69795. }
  69796. if (options.maxYaw != null) {
  69797. this.maxYaw = options.maxYaw;
  69798. }
  69799. else {
  69800. this.maxYaw = Math.PI;
  69801. }
  69802. if (options.minYaw != null) {
  69803. this.minYaw = options.minYaw;
  69804. }
  69805. else {
  69806. this.minYaw = -Math.PI;
  69807. }
  69808. if (options.maxPitch != null) {
  69809. this.maxPitch = options.maxPitch;
  69810. }
  69811. else {
  69812. this.maxPitch = Math.PI;
  69813. }
  69814. if (options.minPitch != null) {
  69815. this.minPitch = options.minPitch;
  69816. }
  69817. else {
  69818. this.minPitch = -Math.PI;
  69819. }
  69820. if (options.slerpAmount != null) {
  69821. this.slerpAmount = options.slerpAmount;
  69822. }
  69823. if (options.upAxis != null) {
  69824. this.upAxis = options.upAxis;
  69825. }
  69826. if (options.upAxisSpace != null) {
  69827. this.upAxisSpace = options.upAxisSpace;
  69828. }
  69829. if (options.yawAxis != null || options.pitchAxis != null) {
  69830. var newYawAxis = BABYLON.Axis.Y;
  69831. var newPitchAxis = BABYLON.Axis.X;
  69832. if (options.yawAxis != null) {
  69833. newYawAxis = options.yawAxis.clone();
  69834. newYawAxis.normalize();
  69835. }
  69836. if (options.pitchAxis != null) {
  69837. newPitchAxis = options.pitchAxis.clone();
  69838. newPitchAxis.normalize();
  69839. }
  69840. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69841. this._transformYawPitch = BABYLON.Matrix.Identity();
  69842. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69843. this._transformYawPitchInv = this._transformYawPitch.clone();
  69844. this._transformYawPitch.invert();
  69845. }
  69846. }
  69847. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69848. this.upAxisSpace = BABYLON.Space.LOCAL;
  69849. }
  69850. }
  69851. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69852. /**
  69853. * Get/set the minimum yaw angle that the bone can look to.
  69854. */
  69855. get: function () {
  69856. return this._minYaw;
  69857. },
  69858. set: function (value) {
  69859. this._minYaw = value;
  69860. this._minYawSin = Math.sin(value);
  69861. this._minYawCos = Math.cos(value);
  69862. if (this._maxYaw != null) {
  69863. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69864. this._yawRange = this._maxYaw - this._minYaw;
  69865. }
  69866. },
  69867. enumerable: true,
  69868. configurable: true
  69869. });
  69870. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69871. /**
  69872. * Get/set the maximum yaw angle that the bone can look to.
  69873. */
  69874. get: function () {
  69875. return this._maxYaw;
  69876. },
  69877. set: function (value) {
  69878. this._maxYaw = value;
  69879. this._maxYawSin = Math.sin(value);
  69880. this._maxYawCos = Math.cos(value);
  69881. if (this._minYaw != null) {
  69882. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69883. this._yawRange = this._maxYaw - this._minYaw;
  69884. }
  69885. },
  69886. enumerable: true,
  69887. configurable: true
  69888. });
  69889. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69890. /**
  69891. * Get/set the minimum pitch angle that the bone can look to.
  69892. */
  69893. get: function () {
  69894. return this._minPitch;
  69895. },
  69896. set: function (value) {
  69897. this._minPitch = value;
  69898. this._minPitchTan = Math.tan(value);
  69899. },
  69900. enumerable: true,
  69901. configurable: true
  69902. });
  69903. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69904. /**
  69905. * Get/set the maximum pitch angle that the bone can look to.
  69906. */
  69907. get: function () {
  69908. return this._maxPitch;
  69909. },
  69910. set: function (value) {
  69911. this._maxPitch = value;
  69912. this._maxPitchTan = Math.tan(value);
  69913. },
  69914. enumerable: true,
  69915. configurable: true
  69916. });
  69917. /**
  69918. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69919. */
  69920. BoneLookController.prototype.update = function () {
  69921. //skip the first frame when slerping so that the mesh rotation is correct
  69922. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69923. this._firstFrameSkipped = true;
  69924. return;
  69925. }
  69926. var bone = this.bone;
  69927. var bonePos = BoneLookController._tmpVecs[0];
  69928. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69929. var target = this.target;
  69930. var _tmpMat1 = BoneLookController._tmpMats[0];
  69931. var _tmpMat2 = BoneLookController._tmpMats[1];
  69932. var mesh = this.mesh;
  69933. var parentBone = bone.getParent();
  69934. var upAxis = BoneLookController._tmpVecs[1];
  69935. upAxis.copyFrom(this.upAxis);
  69936. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69937. if (this._transformYawPitch) {
  69938. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69939. }
  69940. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69941. }
  69942. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69943. mesh.getDirectionToRef(upAxis, upAxis);
  69944. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69945. upAxis.normalize();
  69946. }
  69947. }
  69948. var checkYaw = false;
  69949. var checkPitch = false;
  69950. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69951. checkYaw = true;
  69952. }
  69953. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69954. checkPitch = true;
  69955. }
  69956. if (checkYaw || checkPitch) {
  69957. var spaceMat = BoneLookController._tmpMats[2];
  69958. var spaceMatInv = BoneLookController._tmpMats[3];
  69959. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69960. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69961. }
  69962. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69963. spaceMat.copyFrom(mesh.getWorldMatrix());
  69964. }
  69965. else {
  69966. var forwardAxis = BoneLookController._tmpVecs[2];
  69967. forwardAxis.copyFrom(this._fowardAxis);
  69968. if (this._transformYawPitch) {
  69969. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69970. }
  69971. if (parentBone) {
  69972. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69973. }
  69974. else {
  69975. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69976. }
  69977. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69978. rightAxis.normalize();
  69979. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69980. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69981. }
  69982. spaceMat.invertToRef(spaceMatInv);
  69983. var xzlen = null;
  69984. if (checkPitch) {
  69985. var localTarget = BoneLookController._tmpVecs[3];
  69986. target.subtractToRef(bonePos, localTarget);
  69987. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69988. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69989. var pitch = Math.atan2(localTarget.y, xzlen);
  69990. var newPitch = pitch;
  69991. if (pitch > this._maxPitch) {
  69992. localTarget.y = this._maxPitchTan * xzlen;
  69993. newPitch = this._maxPitch;
  69994. }
  69995. else if (pitch < this._minPitch) {
  69996. localTarget.y = this._minPitchTan * xzlen;
  69997. newPitch = this._minPitch;
  69998. }
  69999. if (pitch != newPitch) {
  70000. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70001. localTarget.addInPlace(bonePos);
  70002. target = localTarget;
  70003. }
  70004. }
  70005. if (checkYaw) {
  70006. var localTarget = BoneLookController._tmpVecs[4];
  70007. target.subtractToRef(bonePos, localTarget);
  70008. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70009. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70010. var newYaw = yaw;
  70011. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70012. if (xzlen == null) {
  70013. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70014. }
  70015. if (this._yawRange > Math.PI) {
  70016. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70017. localTarget.z = this._maxYawCos * xzlen;
  70018. localTarget.x = this._maxYawSin * xzlen;
  70019. newYaw = this._maxYaw;
  70020. }
  70021. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70022. localTarget.z = this._minYawCos * xzlen;
  70023. localTarget.x = this._minYawSin * xzlen;
  70024. newYaw = this._minYaw;
  70025. }
  70026. }
  70027. else {
  70028. if (yaw > this._maxYaw) {
  70029. localTarget.z = this._maxYawCos * xzlen;
  70030. localTarget.x = this._maxYawSin * xzlen;
  70031. newYaw = this._maxYaw;
  70032. }
  70033. else if (yaw < this._minYaw) {
  70034. localTarget.z = this._minYawCos * xzlen;
  70035. localTarget.x = this._minYawSin * xzlen;
  70036. newYaw = this._minYaw;
  70037. }
  70038. }
  70039. }
  70040. if (this._slerping && this._yawRange > Math.PI) {
  70041. //are we going to be crossing into the min/max region?
  70042. var boneFwd = BoneLookController._tmpVecs[8];
  70043. boneFwd.copyFrom(BABYLON.Axis.Z);
  70044. if (this._transformYawPitch) {
  70045. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70046. }
  70047. var boneRotMat = BoneLookController._tmpMats[4];
  70048. this._boneQuat.toRotationMatrix(boneRotMat);
  70049. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70050. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70051. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70052. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70053. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70054. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70055. if (angBtwTar > angBtwMidYaw) {
  70056. if (xzlen == null) {
  70057. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70058. }
  70059. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70060. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70061. if (angBtwMin < angBtwMax) {
  70062. newYaw = boneYaw + Math.PI * .75;
  70063. localTarget.z = Math.cos(newYaw) * xzlen;
  70064. localTarget.x = Math.sin(newYaw) * xzlen;
  70065. }
  70066. else {
  70067. newYaw = boneYaw - Math.PI * .75;
  70068. localTarget.z = Math.cos(newYaw) * xzlen;
  70069. localTarget.x = Math.sin(newYaw) * xzlen;
  70070. }
  70071. }
  70072. }
  70073. if (yaw != newYaw) {
  70074. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70075. localTarget.addInPlace(bonePos);
  70076. target = localTarget;
  70077. }
  70078. }
  70079. }
  70080. var zaxis = BoneLookController._tmpVecs[5];
  70081. var xaxis = BoneLookController._tmpVecs[6];
  70082. var yaxis = BoneLookController._tmpVecs[7];
  70083. var _tmpQuat = BoneLookController._tmpQuat;
  70084. target.subtractToRef(bonePos, zaxis);
  70085. zaxis.normalize();
  70086. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70087. xaxis.normalize();
  70088. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70089. yaxis.normalize();
  70090. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70091. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70092. return;
  70093. }
  70094. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70095. return;
  70096. }
  70097. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70098. return;
  70099. }
  70100. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70101. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70102. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70103. }
  70104. if (this.slerpAmount < 1) {
  70105. if (!this._slerping) {
  70106. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70107. }
  70108. if (this._transformYawPitch) {
  70109. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70110. }
  70111. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70112. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70113. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70114. this._slerping = true;
  70115. }
  70116. else {
  70117. if (this._transformYawPitch) {
  70118. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70119. }
  70120. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70121. this._slerping = false;
  70122. }
  70123. };
  70124. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70125. var angDiff = ang2 - ang1;
  70126. angDiff %= Math.PI * 2;
  70127. if (angDiff > Math.PI) {
  70128. angDiff -= Math.PI * 2;
  70129. }
  70130. else if (angDiff < -Math.PI) {
  70131. angDiff += Math.PI * 2;
  70132. }
  70133. return angDiff;
  70134. };
  70135. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70136. ang1 %= (2 * Math.PI);
  70137. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70138. ang2 %= (2 * Math.PI);
  70139. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70140. var ab = 0;
  70141. if (ang1 < ang2) {
  70142. ab = ang2 - ang1;
  70143. }
  70144. else {
  70145. ab = ang1 - ang2;
  70146. }
  70147. if (ab > Math.PI) {
  70148. ab = Math.PI * 2 - ab;
  70149. }
  70150. return ab;
  70151. };
  70152. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70153. ang %= (2 * Math.PI);
  70154. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70155. ang1 %= (2 * Math.PI);
  70156. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70157. ang2 %= (2 * Math.PI);
  70158. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70159. if (ang1 < ang2) {
  70160. if (ang > ang1 && ang < ang2) {
  70161. return true;
  70162. }
  70163. }
  70164. else {
  70165. if (ang > ang2 && ang < ang1) {
  70166. return true;
  70167. }
  70168. }
  70169. return false;
  70170. };
  70171. 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()];
  70172. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70173. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70174. return BoneLookController;
  70175. }());
  70176. BABYLON.BoneLookController = BoneLookController;
  70177. })(BABYLON || (BABYLON = {}));
  70178. //# sourceMappingURL=babylon.boneLookController.js.map
  70179. var BABYLON;
  70180. (function (BABYLON) {
  70181. var Skeleton = /** @class */ (function () {
  70182. function Skeleton(name, id, scene) {
  70183. this.name = name;
  70184. this.id = id;
  70185. this.bones = new Array();
  70186. this.needInitialSkinMatrix = false;
  70187. this._isDirty = true;
  70188. this._meshesWithPoseMatrix = new Array();
  70189. this._identity = BABYLON.Matrix.Identity();
  70190. this._ranges = {};
  70191. this._lastAbsoluteTransformsUpdateId = -1;
  70192. // Events
  70193. /**
  70194. * An event triggered before computing the skeleton's matrices
  70195. * @type {BABYLON.Observable}
  70196. */
  70197. this.onBeforeComputeObservable = new BABYLON.Observable();
  70198. this.bones = [];
  70199. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70200. scene.skeletons.push(this);
  70201. //make sure it will recalculate the matrix next time prepare is called.
  70202. this._isDirty = true;
  70203. }
  70204. // Members
  70205. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70206. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70207. return mesh._bonesTransformMatrices;
  70208. }
  70209. if (!this._transformMatrices) {
  70210. this.prepare();
  70211. }
  70212. return this._transformMatrices;
  70213. };
  70214. Skeleton.prototype.getScene = function () {
  70215. return this._scene;
  70216. };
  70217. // Methods
  70218. /**
  70219. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70220. */
  70221. Skeleton.prototype.toString = function (fullDetails) {
  70222. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70223. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70224. if (fullDetails) {
  70225. ret += ", Ranges: {";
  70226. var first = true;
  70227. for (var name_1 in this._ranges) {
  70228. if (first) {
  70229. ret += ", ";
  70230. first = false;
  70231. }
  70232. ret += name_1;
  70233. }
  70234. ret += "}";
  70235. }
  70236. return ret;
  70237. };
  70238. /**
  70239. * Get bone's index searching by name
  70240. * @param {string} name is bone's name to search for
  70241. * @return {number} Indice of the bone. Returns -1 if not found
  70242. */
  70243. Skeleton.prototype.getBoneIndexByName = function (name) {
  70244. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70245. if (this.bones[boneIndex].name === name) {
  70246. return boneIndex;
  70247. }
  70248. }
  70249. return -1;
  70250. };
  70251. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70252. // check name not already in use
  70253. if (!this._ranges[name]) {
  70254. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70255. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70256. if (this.bones[i].animations[0]) {
  70257. this.bones[i].animations[0].createRange(name, from, to);
  70258. }
  70259. }
  70260. }
  70261. };
  70262. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70263. if (deleteFrames === void 0) { deleteFrames = true; }
  70264. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70265. if (this.bones[i].animations[0]) {
  70266. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70267. }
  70268. }
  70269. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70270. };
  70271. Skeleton.prototype.getAnimationRange = function (name) {
  70272. return this._ranges[name];
  70273. };
  70274. /**
  70275. * Returns as an Array, all AnimationRanges defined on this skeleton
  70276. */
  70277. Skeleton.prototype.getAnimationRanges = function () {
  70278. var animationRanges = [];
  70279. var name;
  70280. var i = 0;
  70281. for (name in this._ranges) {
  70282. animationRanges[i] = this._ranges[name];
  70283. i++;
  70284. }
  70285. return animationRanges;
  70286. };
  70287. /**
  70288. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70289. */
  70290. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70291. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70292. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70293. return false;
  70294. }
  70295. var ret = true;
  70296. var frameOffset = this._getHighestAnimationFrame() + 1;
  70297. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70298. var boneDict = {};
  70299. var sourceBones = source.bones;
  70300. var nBones;
  70301. var i;
  70302. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70303. boneDict[sourceBones[i].name] = sourceBones[i];
  70304. }
  70305. if (this.bones.length !== sourceBones.length) {
  70306. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70307. ret = false;
  70308. }
  70309. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70310. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70311. var boneName = this.bones[i].name;
  70312. var sourceBone = boneDict[boneName];
  70313. if (sourceBone) {
  70314. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70315. }
  70316. else {
  70317. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70318. ret = false;
  70319. }
  70320. }
  70321. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70322. var range = source.getAnimationRange(name);
  70323. if (range) {
  70324. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70325. }
  70326. return ret;
  70327. };
  70328. Skeleton.prototype.returnToRest = function () {
  70329. for (var index = 0; index < this.bones.length; index++) {
  70330. this.bones[index].returnToRest();
  70331. }
  70332. };
  70333. Skeleton.prototype._getHighestAnimationFrame = function () {
  70334. var ret = 0;
  70335. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70336. if (this.bones[i].animations[0]) {
  70337. var highest = this.bones[i].animations[0].getHighestFrame();
  70338. if (ret < highest) {
  70339. ret = highest;
  70340. }
  70341. }
  70342. }
  70343. return ret;
  70344. };
  70345. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70346. var range = this.getAnimationRange(name);
  70347. if (!range) {
  70348. return null;
  70349. }
  70350. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70351. };
  70352. Skeleton.prototype._markAsDirty = function () {
  70353. this._isDirty = true;
  70354. };
  70355. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70356. this._meshesWithPoseMatrix.push(mesh);
  70357. };
  70358. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70359. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70360. if (index > -1) {
  70361. this._meshesWithPoseMatrix.splice(index, 1);
  70362. }
  70363. };
  70364. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70365. this.onBeforeComputeObservable.notifyObservers(this);
  70366. for (var index = 0; index < this.bones.length; index++) {
  70367. var bone = this.bones[index];
  70368. var parentBone = bone.getParent();
  70369. if (parentBone) {
  70370. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70371. }
  70372. else {
  70373. if (initialSkinMatrix) {
  70374. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70375. }
  70376. else {
  70377. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70378. }
  70379. }
  70380. if (bone._index !== -1) {
  70381. var mappedIndex = bone._index === null ? index : bone._index;
  70382. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70383. }
  70384. }
  70385. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70386. };
  70387. Skeleton.prototype.prepare = function () {
  70388. if (!this._isDirty) {
  70389. return;
  70390. }
  70391. if (this.needInitialSkinMatrix) {
  70392. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70393. var mesh = this._meshesWithPoseMatrix[index];
  70394. var poseMatrix = mesh.getPoseMatrix();
  70395. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70396. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70397. }
  70398. if (this._synchronizedWithMesh !== mesh) {
  70399. this._synchronizedWithMesh = mesh;
  70400. // Prepare bones
  70401. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70402. var bone = this.bones[boneIndex];
  70403. if (!bone.getParent()) {
  70404. var matrix = bone.getBaseMatrix();
  70405. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70406. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70407. }
  70408. }
  70409. }
  70410. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70411. }
  70412. }
  70413. else {
  70414. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70415. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70416. }
  70417. this._computeTransformMatrices(this._transformMatrices, null);
  70418. }
  70419. this._isDirty = false;
  70420. this._scene._activeBones.addCount(this.bones.length, false);
  70421. };
  70422. Skeleton.prototype.getAnimatables = function () {
  70423. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70424. this._animatables = [];
  70425. for (var index = 0; index < this.bones.length; index++) {
  70426. this._animatables.push(this.bones[index]);
  70427. }
  70428. }
  70429. return this._animatables;
  70430. };
  70431. Skeleton.prototype.clone = function (name, id) {
  70432. var result = new Skeleton(name, id || name, this._scene);
  70433. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70434. for (var index = 0; index < this.bones.length; index++) {
  70435. var source = this.bones[index];
  70436. var parentBone = null;
  70437. var parent_1 = source.getParent();
  70438. if (parent_1) {
  70439. var parentIndex = this.bones.indexOf(parent_1);
  70440. parentBone = result.bones[parentIndex];
  70441. }
  70442. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70443. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70444. }
  70445. if (this._ranges) {
  70446. result._ranges = {};
  70447. for (var rangeName in this._ranges) {
  70448. var range = this._ranges[rangeName];
  70449. if (range) {
  70450. result._ranges[rangeName] = range.clone();
  70451. }
  70452. }
  70453. }
  70454. this._isDirty = true;
  70455. return result;
  70456. };
  70457. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70458. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70459. this.bones.forEach(function (bone) {
  70460. bone.animations.forEach(function (animation) {
  70461. animation.enableBlending = true;
  70462. animation.blendingSpeed = blendingSpeed;
  70463. });
  70464. });
  70465. };
  70466. Skeleton.prototype.dispose = function () {
  70467. this._meshesWithPoseMatrix = [];
  70468. // Animations
  70469. this.getScene().stopAnimation(this);
  70470. // Remove from scene
  70471. this.getScene().removeSkeleton(this);
  70472. };
  70473. Skeleton.prototype.serialize = function () {
  70474. var serializationObject = {};
  70475. serializationObject.name = this.name;
  70476. serializationObject.id = this.id;
  70477. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70478. serializationObject.bones = [];
  70479. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70480. for (var index = 0; index < this.bones.length; index++) {
  70481. var bone = this.bones[index];
  70482. var parent_2 = bone.getParent();
  70483. var serializedBone = {
  70484. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70485. name: bone.name,
  70486. matrix: bone.getBaseMatrix().toArray(),
  70487. rest: bone.getRestPose().toArray()
  70488. };
  70489. serializationObject.bones.push(serializedBone);
  70490. if (bone.length) {
  70491. serializedBone.length = bone.length;
  70492. }
  70493. if (bone.animations && bone.animations.length > 0) {
  70494. serializedBone.animation = bone.animations[0].serialize();
  70495. }
  70496. serializationObject.ranges = [];
  70497. for (var name in this._ranges) {
  70498. var source = this._ranges[name];
  70499. if (!source) {
  70500. continue;
  70501. }
  70502. var range = {};
  70503. range.name = name;
  70504. range.from = source.from;
  70505. range.to = source.to;
  70506. serializationObject.ranges.push(range);
  70507. }
  70508. }
  70509. return serializationObject;
  70510. };
  70511. Skeleton.Parse = function (parsedSkeleton, scene) {
  70512. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70513. if (parsedSkeleton.dimensionsAtRest) {
  70514. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70515. }
  70516. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70517. var index;
  70518. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70519. var parsedBone = parsedSkeleton.bones[index];
  70520. var parentBone = null;
  70521. if (parsedBone.parentBoneIndex > -1) {
  70522. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70523. }
  70524. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70525. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70526. if (parsedBone.length) {
  70527. bone.length = parsedBone.length;
  70528. }
  70529. if (parsedBone.animation) {
  70530. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70531. }
  70532. }
  70533. // placed after bones, so createAnimationRange can cascade down
  70534. if (parsedSkeleton.ranges) {
  70535. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70536. var data = parsedSkeleton.ranges[index];
  70537. skeleton.createAnimationRange(data.name, data.from, data.to);
  70538. }
  70539. }
  70540. return skeleton;
  70541. };
  70542. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70543. if (forceUpdate === void 0) { forceUpdate = false; }
  70544. var renderId = this._scene.getRenderId();
  70545. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70546. this.bones[0].computeAbsoluteTransforms();
  70547. this._lastAbsoluteTransformsUpdateId = renderId;
  70548. }
  70549. };
  70550. Skeleton.prototype.getPoseMatrix = function () {
  70551. var poseMatrix = null;
  70552. if (this._meshesWithPoseMatrix.length > 0) {
  70553. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70554. }
  70555. return poseMatrix;
  70556. };
  70557. Skeleton.prototype.sortBones = function () {
  70558. var bones = new Array();
  70559. var visited = new Array(this.bones.length);
  70560. for (var index = 0; index < this.bones.length; index++) {
  70561. this._sortBones(index, bones, visited);
  70562. }
  70563. this.bones = bones;
  70564. };
  70565. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70566. if (visited[index]) {
  70567. return;
  70568. }
  70569. visited[index] = true;
  70570. var bone = this.bones[index];
  70571. if (bone._index === undefined) {
  70572. bone._index = index;
  70573. }
  70574. var parentBone = bone.getParent();
  70575. if (parentBone) {
  70576. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70577. }
  70578. bones.push(bone);
  70579. };
  70580. return Skeleton;
  70581. }());
  70582. BABYLON.Skeleton = Skeleton;
  70583. })(BABYLON || (BABYLON = {}));
  70584. //# sourceMappingURL=babylon.skeleton.js.map
  70585. var BABYLON;
  70586. (function (BABYLON) {
  70587. var SphericalPolynomial = /** @class */ (function () {
  70588. function SphericalPolynomial() {
  70589. this.x = BABYLON.Vector3.Zero();
  70590. this.y = BABYLON.Vector3.Zero();
  70591. this.z = BABYLON.Vector3.Zero();
  70592. this.xx = BABYLON.Vector3.Zero();
  70593. this.yy = BABYLON.Vector3.Zero();
  70594. this.zz = BABYLON.Vector3.Zero();
  70595. this.xy = BABYLON.Vector3.Zero();
  70596. this.yz = BABYLON.Vector3.Zero();
  70597. this.zx = BABYLON.Vector3.Zero();
  70598. }
  70599. SphericalPolynomial.prototype.addAmbient = function (color) {
  70600. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70601. this.xx = this.xx.add(colorVector);
  70602. this.yy = this.yy.add(colorVector);
  70603. this.zz = this.zz.add(colorVector);
  70604. };
  70605. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70606. var result = new SphericalPolynomial();
  70607. result.x = harmonics.L11.scale(1.02333);
  70608. result.y = harmonics.L1_1.scale(1.02333);
  70609. result.z = harmonics.L10.scale(1.02333);
  70610. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70611. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70612. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70613. result.yz = harmonics.L2_1.scale(0.858086);
  70614. result.zx = harmonics.L21.scale(0.858086);
  70615. result.xy = harmonics.L2_2.scale(0.858086);
  70616. result.scale(1.0 / Math.PI);
  70617. return result;
  70618. };
  70619. SphericalPolynomial.prototype.scale = function (scale) {
  70620. this.x = this.x.scale(scale);
  70621. this.y = this.y.scale(scale);
  70622. this.z = this.z.scale(scale);
  70623. this.xx = this.xx.scale(scale);
  70624. this.yy = this.yy.scale(scale);
  70625. this.zz = this.zz.scale(scale);
  70626. this.yz = this.yz.scale(scale);
  70627. this.zx = this.zx.scale(scale);
  70628. this.xy = this.xy.scale(scale);
  70629. };
  70630. return SphericalPolynomial;
  70631. }());
  70632. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70633. var SphericalHarmonics = /** @class */ (function () {
  70634. function SphericalHarmonics() {
  70635. this.L00 = BABYLON.Vector3.Zero();
  70636. this.L1_1 = BABYLON.Vector3.Zero();
  70637. this.L10 = BABYLON.Vector3.Zero();
  70638. this.L11 = BABYLON.Vector3.Zero();
  70639. this.L2_2 = BABYLON.Vector3.Zero();
  70640. this.L2_1 = BABYLON.Vector3.Zero();
  70641. this.L20 = BABYLON.Vector3.Zero();
  70642. this.L21 = BABYLON.Vector3.Zero();
  70643. this.L22 = BABYLON.Vector3.Zero();
  70644. }
  70645. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70646. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70647. var c = colorVector.scale(deltaSolidAngle);
  70648. this.L00 = this.L00.add(c.scale(0.282095));
  70649. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70650. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70651. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70652. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70653. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70654. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70655. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70656. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70657. };
  70658. SphericalHarmonics.prototype.scale = function (scale) {
  70659. this.L00 = this.L00.scale(scale);
  70660. this.L1_1 = this.L1_1.scale(scale);
  70661. this.L10 = this.L10.scale(scale);
  70662. this.L11 = this.L11.scale(scale);
  70663. this.L2_2 = this.L2_2.scale(scale);
  70664. this.L2_1 = this.L2_1.scale(scale);
  70665. this.L20 = this.L20.scale(scale);
  70666. this.L21 = this.L21.scale(scale);
  70667. this.L22 = this.L22.scale(scale);
  70668. };
  70669. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70670. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70671. //
  70672. // E_lm = A_l * L_lm
  70673. //
  70674. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70675. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70676. // the scaling factors are given in equation 9.
  70677. // Constant (Band 0)
  70678. this.L00 = this.L00.scale(3.141593);
  70679. // Linear (Band 1)
  70680. this.L1_1 = this.L1_1.scale(2.094395);
  70681. this.L10 = this.L10.scale(2.094395);
  70682. this.L11 = this.L11.scale(2.094395);
  70683. // Quadratic (Band 2)
  70684. this.L2_2 = this.L2_2.scale(0.785398);
  70685. this.L2_1 = this.L2_1.scale(0.785398);
  70686. this.L20 = this.L20.scale(0.785398);
  70687. this.L21 = this.L21.scale(0.785398);
  70688. this.L22 = this.L22.scale(0.785398);
  70689. };
  70690. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70691. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70692. // L = (1/pi) * E * rho
  70693. //
  70694. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70695. this.scale(1.0 / Math.PI);
  70696. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70697. // (The pixel shader must apply albedo after texture fetches, etc).
  70698. };
  70699. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70700. var result = new SphericalHarmonics();
  70701. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70702. result.L1_1 = polynomial.y.scale(0.977204);
  70703. result.L10 = polynomial.z.scale(0.977204);
  70704. result.L11 = polynomial.x.scale(0.977204);
  70705. result.L2_2 = polynomial.xy.scale(1.16538);
  70706. result.L2_1 = polynomial.yz.scale(1.16538);
  70707. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70708. result.L21 = polynomial.zx.scale(1.16538);
  70709. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70710. result.scale(Math.PI);
  70711. return result;
  70712. };
  70713. return SphericalHarmonics;
  70714. }());
  70715. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70716. })(BABYLON || (BABYLON = {}));
  70717. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70718. var BABYLON;
  70719. (function (BABYLON) {
  70720. var FileFaceOrientation = /** @class */ (function () {
  70721. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70722. this.name = name;
  70723. this.worldAxisForNormal = worldAxisForNormal;
  70724. this.worldAxisForFileX = worldAxisForFileX;
  70725. this.worldAxisForFileY = worldAxisForFileY;
  70726. }
  70727. return FileFaceOrientation;
  70728. }());
  70729. ;
  70730. /**
  70731. * Helper class dealing with the extraction of spherical polynomial dataArray
  70732. * from a cube map.
  70733. */
  70734. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70735. function CubeMapToSphericalPolynomialTools() {
  70736. }
  70737. /**
  70738. * Converts a texture to the according Spherical Polynomial data.
  70739. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70740. *
  70741. * @param texture The texture to extract the information from.
  70742. * @return The Spherical Polynomial data.
  70743. */
  70744. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70745. if (!texture.isCube) {
  70746. // Only supports cube Textures currently.
  70747. return null;
  70748. }
  70749. var size = texture.getSize().width;
  70750. var right = texture.readPixels(0);
  70751. var left = texture.readPixels(1);
  70752. var up;
  70753. var down;
  70754. if (texture.isRenderTarget) {
  70755. up = texture.readPixels(3);
  70756. down = texture.readPixels(2);
  70757. }
  70758. else {
  70759. up = texture.readPixels(2);
  70760. down = texture.readPixels(3);
  70761. }
  70762. var front = texture.readPixels(4);
  70763. var back = texture.readPixels(5);
  70764. var gammaSpace = texture.gammaSpace;
  70765. // Always read as RGBA.
  70766. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70767. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70768. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70769. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70770. }
  70771. var cubeInfo = {
  70772. size: size,
  70773. right: right,
  70774. left: left,
  70775. up: up,
  70776. down: down,
  70777. front: front,
  70778. back: back,
  70779. format: format,
  70780. type: type,
  70781. gammaSpace: gammaSpace,
  70782. };
  70783. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70784. };
  70785. /**
  70786. * Converts a cubemap to the according Spherical Polynomial data.
  70787. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70788. *
  70789. * @param cubeInfo The Cube map to extract the information from.
  70790. * @return The Spherical Polynomial data.
  70791. */
  70792. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70793. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70794. var totalSolidAngle = 0.0;
  70795. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70796. var du = 2.0 / cubeInfo.size;
  70797. var dv = du;
  70798. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70799. var minUV = du * 0.5 - 1.0;
  70800. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70801. var fileFace = this.FileFaces[faceIndex];
  70802. var dataArray = cubeInfo[fileFace.name];
  70803. var v = minUV;
  70804. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70805. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70806. // Because SP is still linear, so summation is fine in that basis.
  70807. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70808. for (var y = 0; y < cubeInfo.size; y++) {
  70809. var u = minUV;
  70810. for (var x = 0; x < cubeInfo.size; x++) {
  70811. // World direction (not normalised)
  70812. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70813. worldDirection.normalize();
  70814. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70815. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70816. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70817. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70818. // Handle Integer types.
  70819. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70820. r /= 255;
  70821. g /= 255;
  70822. b /= 255;
  70823. }
  70824. // Handle Gamma space textures.
  70825. if (cubeInfo.gammaSpace) {
  70826. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70827. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70828. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70829. }
  70830. var color = new BABYLON.Color3(r, g, b);
  70831. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70832. totalSolidAngle += deltaSolidAngle;
  70833. u += du;
  70834. }
  70835. v += dv;
  70836. }
  70837. }
  70838. // Solid angle for entire sphere is 4*pi
  70839. var sphereSolidAngle = 4.0 * Math.PI;
  70840. // Adjust the solid angle to allow for how many faces we processed.
  70841. var facesProcessed = 6.0;
  70842. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70843. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70844. // This is needed because the numerical integration over the cube uses a
  70845. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70846. // and also to compensate for accumulative error due to float precision in the summation.
  70847. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70848. sphericalHarmonics.scale(correctionFactor);
  70849. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70850. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70851. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70852. };
  70853. CubeMapToSphericalPolynomialTools.FileFaces = [
  70854. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70855. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70856. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70857. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70858. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70859. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70860. ];
  70861. return CubeMapToSphericalPolynomialTools;
  70862. }());
  70863. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70864. })(BABYLON || (BABYLON = {}));
  70865. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70866. var BABYLON;
  70867. (function (BABYLON) {
  70868. /**
  70869. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70870. */
  70871. var PanoramaToCubeMapTools = /** @class */ (function () {
  70872. function PanoramaToCubeMapTools() {
  70873. }
  70874. /**
  70875. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70876. *
  70877. * @param float32Array The source data.
  70878. * @param inputWidth The width of the input panorama.
  70879. * @param inputhHeight The height of the input panorama.
  70880. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70881. * @return The cubemap data
  70882. */
  70883. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70884. if (!float32Array) {
  70885. throw "ConvertPanoramaToCubemap: input cannot be null";
  70886. }
  70887. if (float32Array.length != inputWidth * inputHeight * 3) {
  70888. throw "ConvertPanoramaToCubemap: input size is wrong";
  70889. }
  70890. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70891. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70892. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70893. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70894. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70895. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70896. return {
  70897. front: textureFront,
  70898. back: textureBack,
  70899. left: textureLeft,
  70900. right: textureRight,
  70901. up: textureUp,
  70902. down: textureDown,
  70903. size: size,
  70904. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70905. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70906. gammaSpace: false,
  70907. };
  70908. };
  70909. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70910. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70911. var textureArray = new Float32Array(buffer);
  70912. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70913. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70914. var dy = 1 / texSize;
  70915. var fy = 0;
  70916. for (var y = 0; y < texSize; y++) {
  70917. var xv1 = faceData[0];
  70918. var xv2 = faceData[2];
  70919. for (var x = 0; x < texSize; x++) {
  70920. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70921. v.normalize();
  70922. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70923. // 3 channels per pixels
  70924. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70925. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70926. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70927. xv1 = xv1.add(rotDX1);
  70928. xv2 = xv2.add(rotDX2);
  70929. }
  70930. fy += dy;
  70931. }
  70932. return textureArray;
  70933. };
  70934. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70935. var theta = Math.atan2(vDir.z, vDir.x);
  70936. var phi = Math.acos(vDir.y);
  70937. while (theta < -Math.PI)
  70938. theta += 2 * Math.PI;
  70939. while (theta > Math.PI)
  70940. theta -= 2 * Math.PI;
  70941. var dx = theta / Math.PI;
  70942. var dy = phi / Math.PI;
  70943. // recenter.
  70944. dx = dx * 0.5 + 0.5;
  70945. var px = Math.round(dx * inputWidth);
  70946. if (px < 0)
  70947. px = 0;
  70948. else if (px >= inputWidth)
  70949. px = inputWidth - 1;
  70950. var py = Math.round(dy * inputHeight);
  70951. if (py < 0)
  70952. py = 0;
  70953. else if (py >= inputHeight)
  70954. py = inputHeight - 1;
  70955. var inputY = (inputHeight - py - 1);
  70956. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70957. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70958. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70959. return {
  70960. r: r,
  70961. g: g,
  70962. b: b
  70963. };
  70964. };
  70965. PanoramaToCubeMapTools.FACE_FRONT = [
  70966. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70967. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70968. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70969. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70970. ];
  70971. PanoramaToCubeMapTools.FACE_BACK = [
  70972. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70973. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70974. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70975. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70976. ];
  70977. PanoramaToCubeMapTools.FACE_RIGHT = [
  70978. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70979. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70980. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70981. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70982. ];
  70983. PanoramaToCubeMapTools.FACE_LEFT = [
  70984. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70985. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70986. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70987. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70988. ];
  70989. PanoramaToCubeMapTools.FACE_DOWN = [
  70990. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70991. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70992. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70993. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70994. ];
  70995. PanoramaToCubeMapTools.FACE_UP = [
  70996. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70997. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70998. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70999. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71000. ];
  71001. return PanoramaToCubeMapTools;
  71002. }());
  71003. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71004. })(BABYLON || (BABYLON = {}));
  71005. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71006. var BABYLON;
  71007. (function (BABYLON) {
  71008. ;
  71009. /**
  71010. * This groups tools to convert HDR texture to native colors array.
  71011. */
  71012. var HDRTools = /** @class */ (function () {
  71013. function HDRTools() {
  71014. }
  71015. HDRTools.Ldexp = function (mantissa, exponent) {
  71016. if (exponent > 1023) {
  71017. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71018. }
  71019. if (exponent < -1074) {
  71020. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71021. }
  71022. return mantissa * Math.pow(2, exponent);
  71023. };
  71024. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71025. if (exponent > 0) {
  71026. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71027. float32array[index + 0] = red * exponent;
  71028. float32array[index + 1] = green * exponent;
  71029. float32array[index + 2] = blue * exponent;
  71030. }
  71031. else {
  71032. float32array[index + 0] = 0;
  71033. float32array[index + 1] = 0;
  71034. float32array[index + 2] = 0;
  71035. }
  71036. };
  71037. HDRTools.readStringLine = function (uint8array, startIndex) {
  71038. var line = "";
  71039. var character = "";
  71040. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71041. character = String.fromCharCode(uint8array[i]);
  71042. if (character == "\n") {
  71043. break;
  71044. }
  71045. line += character;
  71046. }
  71047. return line;
  71048. };
  71049. /**
  71050. * Reads header information from an RGBE texture stored in a native array.
  71051. * More information on this format are available here:
  71052. * https://en.wikipedia.org/wiki/RGBE_image_format
  71053. *
  71054. * @param uint8array The binary file stored in native array.
  71055. * @return The header information.
  71056. */
  71057. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71058. var height = 0;
  71059. var width = 0;
  71060. var line = this.readStringLine(uint8array, 0);
  71061. if (line[0] != '#' || line[1] != '?') {
  71062. throw "Bad HDR Format.";
  71063. }
  71064. var endOfHeader = false;
  71065. var findFormat = false;
  71066. var lineIndex = 0;
  71067. do {
  71068. lineIndex += (line.length + 1);
  71069. line = this.readStringLine(uint8array, lineIndex);
  71070. if (line == "FORMAT=32-bit_rle_rgbe") {
  71071. findFormat = true;
  71072. }
  71073. else if (line.length == 0) {
  71074. endOfHeader = true;
  71075. }
  71076. } while (!endOfHeader);
  71077. if (!findFormat) {
  71078. throw "HDR Bad header format, unsupported FORMAT";
  71079. }
  71080. lineIndex += (line.length + 1);
  71081. line = this.readStringLine(uint8array, lineIndex);
  71082. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71083. var match = sizeRegexp.exec(line);
  71084. // TODO. Support +Y and -X if needed.
  71085. if (!match || match.length < 3) {
  71086. throw "HDR Bad header format, no size";
  71087. }
  71088. width = parseInt(match[2]);
  71089. height = parseInt(match[1]);
  71090. if (width < 8 || width > 0x7fff) {
  71091. throw "HDR Bad header format, unsupported size";
  71092. }
  71093. lineIndex += (line.length + 1);
  71094. return {
  71095. height: height,
  71096. width: width,
  71097. dataPosition: lineIndex
  71098. };
  71099. };
  71100. /**
  71101. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71102. * This RGBE texture needs to store the information as a panorama.
  71103. *
  71104. * More information on this format are available here:
  71105. * https://en.wikipedia.org/wiki/RGBE_image_format
  71106. *
  71107. * @param buffer The binary file stored in an array buffer.
  71108. * @param size The expected size of the extracted cubemap.
  71109. * @return The Cube Map information.
  71110. */
  71111. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71112. var uint8array = new Uint8Array(buffer);
  71113. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71114. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71115. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71116. return cubeMapData;
  71117. };
  71118. /**
  71119. * Returns the pixels data extracted from an RGBE texture.
  71120. * This pixels will be stored left to right up to down in the R G B order in one array.
  71121. *
  71122. * More information on this format are available here:
  71123. * https://en.wikipedia.org/wiki/RGBE_image_format
  71124. *
  71125. * @param uint8array The binary file stored in an array buffer.
  71126. * @param hdrInfo The header information of the file.
  71127. * @return The pixels data in RGB right to left up to down order.
  71128. */
  71129. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71130. // Keep for multi format supports.
  71131. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71132. };
  71133. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71134. var num_scanlines = hdrInfo.height;
  71135. var scanline_width = hdrInfo.width;
  71136. var a, b, c, d, count;
  71137. var dataIndex = hdrInfo.dataPosition;
  71138. var index = 0, endIndex = 0, i = 0;
  71139. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71140. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71141. // 3 channels of 4 bytes per pixel in float.
  71142. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71143. var resultArray = new Float32Array(resultBuffer);
  71144. // read in each successive scanline
  71145. while (num_scanlines > 0) {
  71146. a = uint8array[dataIndex++];
  71147. b = uint8array[dataIndex++];
  71148. c = uint8array[dataIndex++];
  71149. d = uint8array[dataIndex++];
  71150. if (a != 2 || b != 2 || (c & 0x80)) {
  71151. // this file is not run length encoded
  71152. throw "HDR Bad header format, not RLE";
  71153. }
  71154. if (((c << 8) | d) != scanline_width) {
  71155. throw "HDR Bad header format, wrong scan line width";
  71156. }
  71157. index = 0;
  71158. // read each of the four channels for the scanline into the buffer
  71159. for (i = 0; i < 4; i++) {
  71160. endIndex = (i + 1) * scanline_width;
  71161. while (index < endIndex) {
  71162. a = uint8array[dataIndex++];
  71163. b = uint8array[dataIndex++];
  71164. if (a > 128) {
  71165. // a run of the same value
  71166. count = a - 128;
  71167. if ((count == 0) || (count > endIndex - index)) {
  71168. throw "HDR Bad Format, bad scanline data (run)";
  71169. }
  71170. while (count-- > 0) {
  71171. scanLineArray[index++] = b;
  71172. }
  71173. }
  71174. else {
  71175. // a non-run
  71176. count = a;
  71177. if ((count == 0) || (count > endIndex - index)) {
  71178. throw "HDR Bad Format, bad scanline data (non-run)";
  71179. }
  71180. scanLineArray[index++] = b;
  71181. if (--count > 0) {
  71182. for (var j = 0; j < count; j++) {
  71183. scanLineArray[index++] = uint8array[dataIndex++];
  71184. }
  71185. }
  71186. }
  71187. }
  71188. }
  71189. // now convert data from buffer into floats
  71190. for (i = 0; i < scanline_width; i++) {
  71191. a = scanLineArray[i];
  71192. b = scanLineArray[i + scanline_width];
  71193. c = scanLineArray[i + 2 * scanline_width];
  71194. d = scanLineArray[i + 3 * scanline_width];
  71195. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71196. }
  71197. num_scanlines--;
  71198. }
  71199. return resultArray;
  71200. };
  71201. return HDRTools;
  71202. }());
  71203. BABYLON.HDRTools = HDRTools;
  71204. })(BABYLON || (BABYLON = {}));
  71205. //# sourceMappingURL=babylon.hdr.js.map
  71206. var BABYLON;
  71207. (function (BABYLON) {
  71208. /**
  71209. * This represents a texture coming from an HDR input.
  71210. *
  71211. * The only supported format is currently panorama picture stored in RGBE format.
  71212. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71213. */
  71214. var HDRCubeTexture = /** @class */ (function (_super) {
  71215. __extends(HDRCubeTexture, _super);
  71216. /**
  71217. * Instantiates an HDRTexture from the following parameters.
  71218. *
  71219. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71220. * @param scene The scene the texture will be used in
  71221. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  71222. * @param noMipmap Forces to not generate the mipmap if true
  71223. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71224. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  71225. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71226. */
  71227. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71228. if (noMipmap === void 0) { noMipmap = false; }
  71229. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71230. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71231. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71232. if (onLoad === void 0) { onLoad = null; }
  71233. if (onError === void 0) { onError = null; }
  71234. var _this = _super.call(this, scene) || this;
  71235. _this._useInGammaSpace = false;
  71236. _this._generateHarmonics = true;
  71237. _this._isBABYLONPreprocessed = false;
  71238. _this._onLoad = null;
  71239. _this._onError = null;
  71240. /**
  71241. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71242. */
  71243. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71244. /**
  71245. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71246. * This is usefull at run time to apply the good shader.
  71247. */
  71248. _this.isPMREM = false;
  71249. _this._isBlocking = true;
  71250. if (!url) {
  71251. return _this;
  71252. }
  71253. _this.name = url;
  71254. _this.url = url;
  71255. _this.hasAlpha = false;
  71256. _this.isCube = true;
  71257. _this._textureMatrix = BABYLON.Matrix.Identity();
  71258. _this._onLoad = onLoad;
  71259. _this._onError = onError;
  71260. _this.gammaSpace = false;
  71261. var caps = scene.getEngine().getCaps();
  71262. if (size) {
  71263. _this._isBABYLONPreprocessed = false;
  71264. _this._noMipmap = noMipmap;
  71265. _this._size = size;
  71266. _this._useInGammaSpace = useInGammaSpace;
  71267. _this._usePMREMGenerator = usePMREMGenerator &&
  71268. caps.textureLOD &&
  71269. caps.textureFloat &&
  71270. !_this._useInGammaSpace;
  71271. }
  71272. else {
  71273. _this._isBABYLONPreprocessed = true;
  71274. _this._noMipmap = false;
  71275. _this._useInGammaSpace = false;
  71276. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71277. !_this._useInGammaSpace;
  71278. }
  71279. _this.isPMREM = _this._usePMREMGenerator;
  71280. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71281. if (!_this._texture) {
  71282. if (!scene.useDelayedTextureLoading) {
  71283. _this.loadTexture();
  71284. }
  71285. else {
  71286. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71287. }
  71288. }
  71289. return _this;
  71290. }
  71291. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71292. /**
  71293. * Gets wether or not the texture is blocking during loading.
  71294. */
  71295. get: function () {
  71296. return this._isBlocking;
  71297. },
  71298. /**
  71299. * Sets wether or not the texture is blocking during loading.
  71300. */
  71301. set: function (value) {
  71302. this._isBlocking = value;
  71303. },
  71304. enumerable: true,
  71305. configurable: true
  71306. });
  71307. /**
  71308. * Occurs when the file is a preprocessed .babylon.hdr file.
  71309. */
  71310. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71311. var _this = this;
  71312. var mipLevels = 0;
  71313. var floatArrayView = null;
  71314. var scene = this.getScene();
  71315. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71316. var mips = new Array();
  71317. if (!floatArrayView) {
  71318. return mips;
  71319. }
  71320. var startIndex = 30;
  71321. for (var level = 0; level < mipLevels; level++) {
  71322. mips.push([]);
  71323. // Fill each pixel of the mip level.
  71324. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71325. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71326. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71327. mips[level].push(faceData);
  71328. startIndex += faceSize;
  71329. }
  71330. }
  71331. return mips;
  71332. } : null;
  71333. var callback = function (buffer) {
  71334. var scene = _this.getScene();
  71335. if (!scene) {
  71336. return null;
  71337. }
  71338. // Create Native Array Views
  71339. var intArrayView = new Int32Array(buffer);
  71340. floatArrayView = new Float32Array(buffer);
  71341. // Fill header.
  71342. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71343. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71344. // Update Texture Information.
  71345. if (!_this._texture) {
  71346. return null;
  71347. }
  71348. _this._texture.updateSize(_this._size, _this._size);
  71349. // Fill polynomial information.
  71350. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71351. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71352. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71353. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71354. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71355. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71356. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71357. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71358. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71359. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71360. _this.sphericalPolynomial = sphericalPolynomial;
  71361. // Fill pixel data.
  71362. mipLevels = intArrayView[29]; // Number of mip levels.
  71363. var startIndex = 30;
  71364. var data = [];
  71365. var faceSize = Math.pow(_this._size, 2) * 3;
  71366. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71367. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71368. startIndex += faceSize;
  71369. }
  71370. var results = [];
  71371. var byteArray = null;
  71372. // Push each faces.
  71373. for (var k = 0; k < 6; k++) {
  71374. var dataFace = null;
  71375. // To be deprecated.
  71376. if (version === 1) {
  71377. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71378. dataFace = data[j];
  71379. }
  71380. // If special cases.
  71381. if (!mipmapGenerator && dataFace) {
  71382. if (!scene.getEngine().getCaps().textureFloat) {
  71383. // 3 channels of 1 bytes per pixel in bytes.
  71384. var byteBuffer = new ArrayBuffer(faceSize);
  71385. byteArray = new Uint8Array(byteBuffer);
  71386. }
  71387. for (var i = 0; i < _this._size * _this._size; i++) {
  71388. // Put in gamma space if requested.
  71389. if (_this._useInGammaSpace) {
  71390. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71391. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71392. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71393. }
  71394. // Convert to int texture for fallback.
  71395. if (byteArray) {
  71396. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71397. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71398. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71399. // May use luminance instead if the result is not accurate.
  71400. var max = Math.max(Math.max(r, g), b);
  71401. if (max > 255) {
  71402. var scale = 255 / max;
  71403. r *= scale;
  71404. g *= scale;
  71405. b *= scale;
  71406. }
  71407. byteArray[(i * 3) + 0] = r;
  71408. byteArray[(i * 3) + 1] = g;
  71409. byteArray[(i * 3) + 2] = b;
  71410. }
  71411. }
  71412. }
  71413. // Fill the array accordingly.
  71414. if (byteArray) {
  71415. results.push(byteArray);
  71416. }
  71417. else {
  71418. results.push(dataFace);
  71419. }
  71420. }
  71421. return results;
  71422. };
  71423. if (scene) {
  71424. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  71425. }
  71426. };
  71427. /**
  71428. * Occurs when the file is raw .hdr file.
  71429. */
  71430. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71431. var _this = this;
  71432. var callback = function (buffer) {
  71433. var scene = _this.getScene();
  71434. if (!scene) {
  71435. return null;
  71436. }
  71437. // Extract the raw linear data.
  71438. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71439. // Generate harmonics if needed.
  71440. if (_this._generateHarmonics) {
  71441. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71442. _this.sphericalPolynomial = sphericalPolynomial;
  71443. }
  71444. var results = [];
  71445. var byteArray = null;
  71446. // Push each faces.
  71447. for (var j = 0; j < 6; j++) {
  71448. // Create uintarray fallback.
  71449. if (!scene.getEngine().getCaps().textureFloat) {
  71450. // 3 channels of 1 bytes per pixel in bytes.
  71451. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71452. byteArray = new Uint8Array(byteBuffer);
  71453. }
  71454. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71455. // If special cases.
  71456. if (_this._useInGammaSpace || byteArray) {
  71457. for (var i = 0; i < _this._size * _this._size; i++) {
  71458. // Put in gamma space if requested.
  71459. if (_this._useInGammaSpace) {
  71460. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71461. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71462. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71463. }
  71464. // Convert to int texture for fallback.
  71465. if (byteArray) {
  71466. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71467. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71468. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71469. // May use luminance instead if the result is not accurate.
  71470. var max = Math.max(Math.max(r, g), b);
  71471. if (max > 255) {
  71472. var scale = 255 / max;
  71473. r *= scale;
  71474. g *= scale;
  71475. b *= scale;
  71476. }
  71477. byteArray[(i * 3) + 0] = r;
  71478. byteArray[(i * 3) + 1] = g;
  71479. byteArray[(i * 3) + 2] = b;
  71480. }
  71481. }
  71482. }
  71483. if (byteArray) {
  71484. results.push(byteArray);
  71485. }
  71486. else {
  71487. results.push(dataFace);
  71488. }
  71489. }
  71490. return results;
  71491. };
  71492. var mipmapGenerator = null;
  71493. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71494. // if (!this._noMipmap &&
  71495. // this._usePMREMGenerator) {
  71496. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71497. // // Custom setup of the generator matching with the PBR shader values.
  71498. // var generator = new BABYLON.PMREMGenerator(data,
  71499. // this._size,
  71500. // this._size,
  71501. // 0,
  71502. // 3,
  71503. // this.getScene().getEngine().getCaps().textureFloat,
  71504. // 2048,
  71505. // 0.25,
  71506. // false,
  71507. // true);
  71508. // return generator.filterCubeMap();
  71509. // };
  71510. // }
  71511. var scene = this.getScene();
  71512. if (scene) {
  71513. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  71514. }
  71515. };
  71516. /**
  71517. * Starts the loading process of the texture.
  71518. */
  71519. HDRCubeTexture.prototype.loadTexture = function () {
  71520. if (this._isBABYLONPreprocessed) {
  71521. this.loadBabylonTexture();
  71522. }
  71523. else {
  71524. this.loadHDRTexture();
  71525. }
  71526. };
  71527. HDRCubeTexture.prototype.clone = function () {
  71528. var scene = this.getScene();
  71529. if (!scene) {
  71530. return this;
  71531. }
  71532. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71533. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71534. // Base texture
  71535. newTexture.level = this.level;
  71536. newTexture.wrapU = this.wrapU;
  71537. newTexture.wrapV = this.wrapV;
  71538. newTexture.coordinatesIndex = this.coordinatesIndex;
  71539. newTexture.coordinatesMode = this.coordinatesMode;
  71540. return newTexture;
  71541. };
  71542. // Methods
  71543. HDRCubeTexture.prototype.delayLoad = function () {
  71544. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71545. return;
  71546. }
  71547. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71548. this._texture = this._getFromCache(this.url, this._noMipmap);
  71549. if (!this._texture) {
  71550. this.loadTexture();
  71551. }
  71552. };
  71553. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71554. return this._textureMatrix;
  71555. };
  71556. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71557. this._textureMatrix = value;
  71558. };
  71559. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71560. var texture = null;
  71561. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71562. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71563. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71564. texture.name = parsedTexture.name;
  71565. texture.hasAlpha = parsedTexture.hasAlpha;
  71566. texture.level = parsedTexture.level;
  71567. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71568. texture.isBlocking = parsedTexture.isBlocking;
  71569. }
  71570. return texture;
  71571. };
  71572. HDRCubeTexture.prototype.serialize = function () {
  71573. if (!this.name) {
  71574. return null;
  71575. }
  71576. var serializationObject = {};
  71577. serializationObject.name = this.name;
  71578. serializationObject.hasAlpha = this.hasAlpha;
  71579. serializationObject.isCube = true;
  71580. serializationObject.level = this.level;
  71581. serializationObject.size = this._size;
  71582. serializationObject.coordinatesMode = this.coordinatesMode;
  71583. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71584. serializationObject.generateHarmonics = this._generateHarmonics;
  71585. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71586. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71587. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71588. serializationObject.noMipmap = this._noMipmap;
  71589. serializationObject.isBlocking = this._isBlocking;
  71590. return serializationObject;
  71591. };
  71592. /**
  71593. * Saves as a file the data contained in the texture in a binary format.
  71594. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71595. * as the spherical used in the lighting.
  71596. * @param url The HDR file url.
  71597. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71598. * @param onError Method called if any error happens during download.
  71599. * @return The packed binary data.
  71600. */
  71601. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71602. if (onError === void 0) { onError = null; }
  71603. var callback = function (buffer) {
  71604. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71605. // Returns a URL you can use as a href.
  71606. var objUrl = window.URL.createObjectURL(data);
  71607. // Simulates a link to it and click to dowload.
  71608. var a = document.createElement("a");
  71609. document.body.appendChild(a);
  71610. a.style.display = "none";
  71611. a.href = objUrl;
  71612. a.download = "envmap.babylon.hdr";
  71613. a.click();
  71614. };
  71615. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71616. };
  71617. /**
  71618. * Serializes the data contained in the texture in a binary format.
  71619. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71620. * as the spherical used in the lighting.
  71621. * @param url The HDR file url.
  71622. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71623. * @param onError Method called if any error happens during download.
  71624. * @return The packed binary data.
  71625. */
  71626. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71627. if (onError === void 0) { onError = null; }
  71628. // Needs the url tho create the texture.
  71629. if (!url) {
  71630. return;
  71631. }
  71632. // Check Power of two size.
  71633. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71634. return;
  71635. }
  71636. // Coming Back in 3.x.
  71637. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71638. };
  71639. HDRCubeTexture._facesMapping = [
  71640. "right",
  71641. "left",
  71642. "up",
  71643. "down",
  71644. "front",
  71645. "back"
  71646. ];
  71647. return HDRCubeTexture;
  71648. }(BABYLON.BaseTexture));
  71649. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71650. })(BABYLON || (BABYLON = {}));
  71651. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71652. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71653. // Huge respect for a such great lib.
  71654. // Earcut license:
  71655. // Copyright (c) 2016, Mapbox
  71656. //
  71657. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71658. // with or without fee is hereby granted, provided that the above copyright notice
  71659. // and this permission notice appear in all copies.
  71660. //
  71661. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71662. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71663. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71664. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71665. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71666. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71667. // THIS SOFTWARE.
  71668. var Earcut;
  71669. (function (Earcut) {
  71670. /**
  71671. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71672. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71673. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  71674. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71675. */
  71676. function earcut(data, holeIndices, dim) {
  71677. dim = dim || 2;
  71678. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71679. if (!outerNode)
  71680. return triangles;
  71681. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71682. if (hasHoles)
  71683. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71684. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71685. if (data.length > 80 * dim) {
  71686. minX = maxX = data[0];
  71687. minY = maxY = data[1];
  71688. for (var i = dim; i < outerLen; i += dim) {
  71689. x = data[i];
  71690. y = data[i + 1];
  71691. if (x < minX)
  71692. minX = x;
  71693. if (y < minY)
  71694. minY = y;
  71695. if (x > maxX)
  71696. maxX = x;
  71697. if (y > maxY)
  71698. maxY = y;
  71699. }
  71700. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71701. size = Math.max(maxX - minX, maxY - minY);
  71702. }
  71703. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71704. return triangles;
  71705. }
  71706. Earcut.earcut = earcut;
  71707. var Node = /** @class */ (function () {
  71708. function Node(i, x, y) {
  71709. this.i = i;
  71710. this.x = x;
  71711. this.y = y;
  71712. this.prev = null;
  71713. this.next = null;
  71714. this.z = null;
  71715. this.prevZ = null;
  71716. this.nextZ = null;
  71717. this.steiner = false;
  71718. }
  71719. return Node;
  71720. }());
  71721. // create a circular doubly linked list from polygon points in the specified winding order
  71722. function linkedList(data, start, end, dim, clockwise) {
  71723. var i, last = null;
  71724. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71725. for (i = start; i < end; i += dim)
  71726. last = insertNode(i, data[i], data[i + 1], last);
  71727. }
  71728. else {
  71729. for (i = end - dim; i >= start; i -= dim)
  71730. last = insertNode(i, data[i], data[i + 1], last);
  71731. }
  71732. if (last && equals(last, last.next)) {
  71733. removeNode(last);
  71734. last = last.next;
  71735. }
  71736. return last;
  71737. }
  71738. // eliminate colinear or duplicate points
  71739. function filterPoints(start, end) {
  71740. if (!start)
  71741. return start;
  71742. if (!end)
  71743. end = start;
  71744. var p = start, again;
  71745. do {
  71746. again = false;
  71747. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71748. removeNode(p);
  71749. p = end = p.prev;
  71750. if (p === p.next)
  71751. return undefined;
  71752. again = true;
  71753. }
  71754. else {
  71755. p = p.next;
  71756. }
  71757. } while (again || p !== end);
  71758. return end;
  71759. }
  71760. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71761. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71762. if (!ear)
  71763. return;
  71764. // interlink polygon nodes in z-order
  71765. if (!pass && size)
  71766. indexCurve(ear, minX, minY, size);
  71767. var stop = ear, prev, next;
  71768. // iterate through ears, slicing them one by one
  71769. while (ear.prev !== ear.next) {
  71770. prev = ear.prev;
  71771. next = ear.next;
  71772. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71773. // cut off the triangle
  71774. triangles.push(prev.i / dim);
  71775. triangles.push(ear.i / dim);
  71776. triangles.push(next.i / dim);
  71777. removeNode(ear);
  71778. // skipping the next vertice leads to less sliver triangles
  71779. ear = next.next;
  71780. stop = next.next;
  71781. continue;
  71782. }
  71783. ear = next;
  71784. // if we looped through the whole remaining polygon and can't find any more ears
  71785. if (ear === stop) {
  71786. // try filtering points and slicing again
  71787. if (!pass) {
  71788. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71789. // if this didn't work, try curing all small self-intersections locally
  71790. }
  71791. else if (pass === 1) {
  71792. ear = cureLocalIntersections(ear, triangles, dim);
  71793. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71794. // as a last resort, try splitting the remaining polygon into two
  71795. }
  71796. else if (pass === 2) {
  71797. splitEarcut(ear, triangles, dim, minX, minY, size);
  71798. }
  71799. break;
  71800. }
  71801. }
  71802. }
  71803. // check whether a polygon node forms a valid ear with adjacent nodes
  71804. function isEar(ear) {
  71805. var a = ear.prev, b = ear, c = ear.next;
  71806. if (area(a, b, c) >= 0)
  71807. return false; // reflex, can't be an ear
  71808. // now make sure we don't have other points inside the potential ear
  71809. var p = ear.next.next;
  71810. while (p !== ear.prev) {
  71811. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71812. area(p.prev, p, p.next) >= 0)
  71813. return false;
  71814. p = p.next;
  71815. }
  71816. return true;
  71817. }
  71818. function isEarHashed(ear, minX, minY, size) {
  71819. var a = ear.prev, b = ear, c = ear.next;
  71820. if (area(a, b, c) >= 0)
  71821. return false; // reflex, can't be an ear
  71822. // triangle bbox; min & max are calculated like this for speed
  71823. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  71824. // z-order range for the current triangle bbox;
  71825. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71826. // first look for points inside the triangle in increasing z-order
  71827. var p = ear.nextZ;
  71828. while (p && p.z <= maxZ) {
  71829. if (p !== ear.prev &&
  71830. p !== ear.next &&
  71831. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71832. area(p.prev, p, p.next) >= 0)
  71833. return false;
  71834. p = p.nextZ;
  71835. }
  71836. // then look for points in decreasing z-order
  71837. p = ear.prevZ;
  71838. while (p && p.z >= minZ) {
  71839. if (p !== ear.prev &&
  71840. p !== ear.next &&
  71841. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71842. area(p.prev, p, p.next) >= 0)
  71843. return false;
  71844. p = p.prevZ;
  71845. }
  71846. return true;
  71847. }
  71848. // go through all polygon nodes and cure small local self-intersections
  71849. function cureLocalIntersections(start, triangles, dim) {
  71850. var p = start;
  71851. do {
  71852. var a = p.prev, b = p.next.next;
  71853. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71854. triangles.push(a.i / dim);
  71855. triangles.push(p.i / dim);
  71856. triangles.push(b.i / dim);
  71857. // remove two nodes involved
  71858. removeNode(p);
  71859. removeNode(p.next);
  71860. p = start = b;
  71861. }
  71862. p = p.next;
  71863. } while (p !== start);
  71864. return p;
  71865. }
  71866. // try splitting polygon into two and triangulate them independently
  71867. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71868. // look for a valid diagonal that divides the polygon into two
  71869. var a = start;
  71870. do {
  71871. var b = a.next.next;
  71872. while (b !== a.prev) {
  71873. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71874. // split the polygon in two by the diagonal
  71875. var c = splitPolygon(a, b);
  71876. // filter colinear points around the cuts
  71877. a = filterPoints(a, a.next);
  71878. c = filterPoints(c, c.next);
  71879. // run earcut on each half
  71880. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71881. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71882. return;
  71883. }
  71884. b = b.next;
  71885. }
  71886. a = a.next;
  71887. } while (a !== start);
  71888. }
  71889. // link every hole into the outer loop, producing a single-ring polygon without holes
  71890. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71891. var queue = [], i, len, start, end, list;
  71892. for (i = 0, len = holeIndices.length; i < len; i++) {
  71893. start = holeIndices[i] * dim;
  71894. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71895. list = linkedList(data, start, end, dim, false);
  71896. if (list === list.next)
  71897. list.steiner = true;
  71898. queue.push(getLeftmost(list));
  71899. }
  71900. queue.sort(compareX);
  71901. // process holes from left to right
  71902. for (i = 0; i < queue.length; i++) {
  71903. eliminateHole(queue[i], outerNode);
  71904. outerNode = filterPoints(outerNode, outerNode.next);
  71905. }
  71906. return outerNode;
  71907. }
  71908. function compareX(a, b) {
  71909. return a.x - b.x;
  71910. }
  71911. // find a bridge between vertices that connects hole with an outer ring and and link it
  71912. function eliminateHole(hole, outerNode) {
  71913. outerNode = findHoleBridge(hole, outerNode);
  71914. if (outerNode) {
  71915. var b = splitPolygon(outerNode, hole);
  71916. filterPoints(b, b.next);
  71917. }
  71918. }
  71919. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71920. function findHoleBridge(hole, outerNode) {
  71921. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71922. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71923. // segment's endpoint with lesser x will be potential connection point
  71924. do {
  71925. if (hy <= p.y && hy >= p.next.y) {
  71926. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71927. if (x <= hx && x > qx) {
  71928. qx = x;
  71929. if (x === hx) {
  71930. if (hy === p.y)
  71931. return p;
  71932. if (hy === p.next.y)
  71933. return p.next;
  71934. }
  71935. m = p.x < p.next.x ? p : p.next;
  71936. }
  71937. }
  71938. p = p.next;
  71939. } while (p !== outerNode);
  71940. if (!m)
  71941. return null;
  71942. if (hx === qx)
  71943. return m.prev; // hole touches outer segment; pick lower endpoint
  71944. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71945. // if there are no points found, we have a valid connection;
  71946. // otherwise choose the point of the minimum angle with the ray as connection point
  71947. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71948. p = m.next;
  71949. while (p !== stop) {
  71950. if (hx >= p.x &&
  71951. p.x >= mx &&
  71952. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71953. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71954. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71955. m = p;
  71956. tanMin = tan;
  71957. }
  71958. }
  71959. p = p.next;
  71960. }
  71961. return m;
  71962. }
  71963. // interlink polygon nodes in z-order
  71964. function indexCurve(start, minX, minY, size) {
  71965. var p = start;
  71966. do {
  71967. if (p.z === null)
  71968. p.z = zOrder(p.x, p.y, minX, minY, size);
  71969. p.prevZ = p.prev;
  71970. p.nextZ = p.next;
  71971. p = p.next;
  71972. } while (p !== start);
  71973. p.prevZ.nextZ = null;
  71974. p.prevZ = null;
  71975. sortLinked(p);
  71976. }
  71977. // Simon Tatham's linked list merge sort algorithm
  71978. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71979. function sortLinked(list) {
  71980. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71981. do {
  71982. p = list;
  71983. list = null;
  71984. tail = null;
  71985. numMerges = 0;
  71986. while (p) {
  71987. numMerges++;
  71988. q = p;
  71989. pSize = 0;
  71990. for (i = 0; i < inSize; i++) {
  71991. pSize++;
  71992. q = q.nextZ;
  71993. if (!q)
  71994. break;
  71995. }
  71996. qSize = inSize;
  71997. while (pSize > 0 || (qSize > 0 && q)) {
  71998. if (pSize === 0) {
  71999. e = q;
  72000. q = q.nextZ;
  72001. qSize--;
  72002. }
  72003. else if (qSize === 0 || !q) {
  72004. e = p;
  72005. p = p.nextZ;
  72006. pSize--;
  72007. }
  72008. else if (p.z <= q.z) {
  72009. e = p;
  72010. p = p.nextZ;
  72011. pSize--;
  72012. }
  72013. else {
  72014. e = q;
  72015. q = q.nextZ;
  72016. qSize--;
  72017. }
  72018. if (tail)
  72019. tail.nextZ = e;
  72020. else
  72021. list = e;
  72022. e.prevZ = tail;
  72023. tail = e;
  72024. }
  72025. p = q;
  72026. }
  72027. tail.nextZ = null;
  72028. inSize *= 2;
  72029. } while (numMerges > 1);
  72030. return list;
  72031. }
  72032. // z-order of a point given coords and size of the data bounding box
  72033. function zOrder(x, y, minX, minY, size) {
  72034. // coords are transformed into non-negative 15-bit integer range
  72035. x = 32767 * (x - minX) / size;
  72036. y = 32767 * (y - minY) / size;
  72037. x = (x | (x << 8)) & 0x00FF00FF;
  72038. x = (x | (x << 4)) & 0x0F0F0F0F;
  72039. x = (x | (x << 2)) & 0x33333333;
  72040. x = (x | (x << 1)) & 0x55555555;
  72041. y = (y | (y << 8)) & 0x00FF00FF;
  72042. y = (y | (y << 4)) & 0x0F0F0F0F;
  72043. y = (y | (y << 2)) & 0x33333333;
  72044. y = (y | (y << 1)) & 0x55555555;
  72045. return x | (y << 1);
  72046. }
  72047. // find the leftmost node of a polygon ring
  72048. function getLeftmost(start) {
  72049. var p = start, leftmost = start;
  72050. do {
  72051. if (p.x < leftmost.x)
  72052. leftmost = p;
  72053. p = p.next;
  72054. } while (p !== start);
  72055. return leftmost;
  72056. }
  72057. // check if a point lies within a convex triangle
  72058. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72059. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72060. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72061. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72062. }
  72063. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72064. function isValidDiagonal(a, b) {
  72065. return a.next.i !== b.i &&
  72066. a.prev.i !== b.i &&
  72067. !intersectsPolygon(a, b) &&
  72068. locallyInside(a, b) &&
  72069. locallyInside(b, a) &&
  72070. middleInside(a, b);
  72071. }
  72072. // signed area of a triangle
  72073. function area(p, q, r) {
  72074. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72075. }
  72076. // check if two points are equal
  72077. function equals(p1, p2) {
  72078. return p1.x === p2.x && p1.y === p2.y;
  72079. }
  72080. // check if two segments intersect
  72081. function intersects(p1, q1, p2, q2) {
  72082. if ((equals(p1, q1) && equals(p2, q2)) ||
  72083. (equals(p1, q2) && equals(p2, q1)))
  72084. return true;
  72085. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72086. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72087. }
  72088. // check if a polygon diagonal intersects any polygon segments
  72089. function intersectsPolygon(a, b) {
  72090. var p = a;
  72091. do {
  72092. if (p.i !== a.i &&
  72093. p.next.i !== a.i &&
  72094. p.i !== b.i &&
  72095. p.next.i !== b.i &&
  72096. intersects(p, p.next, a, b))
  72097. return true;
  72098. p = p.next;
  72099. } while (p !== a);
  72100. return false;
  72101. }
  72102. // check if a polygon diagonal is locally inside the polygon
  72103. function locallyInside(a, b) {
  72104. return area(a.prev, a, a.next) < 0
  72105. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72106. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72107. }
  72108. // check if the middle point of a polygon diagonal is inside the polygon
  72109. function middleInside(a, b) {
  72110. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72111. do {
  72112. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72113. inside = !inside;
  72114. p = p.next;
  72115. } while (p !== a);
  72116. return inside;
  72117. }
  72118. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72119. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72120. function splitPolygon(a, b) {
  72121. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  72122. a.next = b;
  72123. b.prev = a;
  72124. a2.next = an;
  72125. an.prev = a2;
  72126. b2.next = a2;
  72127. a2.prev = b2;
  72128. bp.next = b2;
  72129. b2.prev = bp;
  72130. return b2;
  72131. }
  72132. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72133. function insertNode(i, x, y, last) {
  72134. var p = new Node(i, x, y);
  72135. if (!last) {
  72136. p.prev = p;
  72137. p.next = p;
  72138. }
  72139. else {
  72140. p.next = last.next;
  72141. p.prev = last;
  72142. last.next.prev = p;
  72143. last.next = p;
  72144. }
  72145. return p;
  72146. }
  72147. function removeNode(p) {
  72148. p.next.prev = p.prev;
  72149. p.prev.next = p.next;
  72150. if (p.prevZ)
  72151. p.prevZ.nextZ = p.nextZ;
  72152. if (p.nextZ)
  72153. p.nextZ.prevZ = p.prevZ;
  72154. }
  72155. /**
  72156. * return a percentage difference between the polygon area and its triangulation area;
  72157. * used to verify correctness of triangulation
  72158. */
  72159. function deviation(data, holeIndices, dim, triangles) {
  72160. var hasHoles = holeIndices && holeIndices.length;
  72161. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72162. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72163. if (hasHoles) {
  72164. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72165. var start = holeIndices[i] * dim;
  72166. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72167. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72168. }
  72169. }
  72170. var trianglesArea = 0;
  72171. for (i = 0; i < triangles.length; i += 3) {
  72172. var a = triangles[i] * dim;
  72173. var b = triangles[i + 1] * dim;
  72174. var c = triangles[i + 2] * dim;
  72175. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72176. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72177. }
  72178. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72179. }
  72180. Earcut.deviation = deviation;
  72181. ;
  72182. function signedArea(data, start, end, dim) {
  72183. var sum = 0;
  72184. for (var i = start, j = end - dim; i < end; i += dim) {
  72185. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72186. j = i;
  72187. }
  72188. return sum;
  72189. }
  72190. /**
  72191. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72192. */
  72193. function flatten(data) {
  72194. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72195. for (var i = 0; i < data.length; i++) {
  72196. for (var j = 0; j < data[i].length; j++) {
  72197. for (var d = 0; d < dim; d++)
  72198. result.vertices.push(data[i][j][d]);
  72199. }
  72200. if (i > 0) {
  72201. holeIndex += data[i - 1].length;
  72202. result.holes.push(holeIndex);
  72203. }
  72204. }
  72205. return result;
  72206. }
  72207. Earcut.flatten = flatten;
  72208. ;
  72209. })(Earcut || (Earcut = {}));
  72210. //# sourceMappingURL=babylon.earcut.js.map
  72211. var BABYLON;
  72212. (function (BABYLON) {
  72213. var IndexedVector2 = /** @class */ (function (_super) {
  72214. __extends(IndexedVector2, _super);
  72215. function IndexedVector2(original, index) {
  72216. var _this = _super.call(this, original.x, original.y) || this;
  72217. _this.index = index;
  72218. return _this;
  72219. }
  72220. return IndexedVector2;
  72221. }(BABYLON.Vector2));
  72222. var PolygonPoints = /** @class */ (function () {
  72223. function PolygonPoints() {
  72224. this.elements = new Array();
  72225. }
  72226. PolygonPoints.prototype.add = function (originalPoints) {
  72227. var _this = this;
  72228. var result = new Array();
  72229. originalPoints.forEach(function (point) {
  72230. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72231. var newPoint = new IndexedVector2(point, _this.elements.length);
  72232. result.push(newPoint);
  72233. _this.elements.push(newPoint);
  72234. }
  72235. });
  72236. return result;
  72237. };
  72238. PolygonPoints.prototype.computeBounds = function () {
  72239. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72240. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72241. this.elements.forEach(function (point) {
  72242. // x
  72243. if (point.x < lmin.x) {
  72244. lmin.x = point.x;
  72245. }
  72246. else if (point.x > lmax.x) {
  72247. lmax.x = point.x;
  72248. }
  72249. // y
  72250. if (point.y < lmin.y) {
  72251. lmin.y = point.y;
  72252. }
  72253. else if (point.y > lmax.y) {
  72254. lmax.y = point.y;
  72255. }
  72256. });
  72257. return {
  72258. min: lmin,
  72259. max: lmax,
  72260. width: lmax.x - lmin.x,
  72261. height: lmax.y - lmin.y
  72262. };
  72263. };
  72264. return PolygonPoints;
  72265. }());
  72266. var Polygon = /** @class */ (function () {
  72267. function Polygon() {
  72268. }
  72269. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72270. return [
  72271. new BABYLON.Vector2(xmin, ymin),
  72272. new BABYLON.Vector2(xmax, ymin),
  72273. new BABYLON.Vector2(xmax, ymax),
  72274. new BABYLON.Vector2(xmin, ymax)
  72275. ];
  72276. };
  72277. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72278. if (cx === void 0) { cx = 0; }
  72279. if (cy === void 0) { cy = 0; }
  72280. if (numberOfSides === void 0) { numberOfSides = 32; }
  72281. var result = new Array();
  72282. var angle = 0;
  72283. var increment = (Math.PI * 2) / numberOfSides;
  72284. for (var i = 0; i < numberOfSides; i++) {
  72285. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72286. angle -= increment;
  72287. }
  72288. return result;
  72289. };
  72290. Polygon.Parse = function (input) {
  72291. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72292. var i, result = [];
  72293. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72294. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72295. }
  72296. return result;
  72297. };
  72298. Polygon.StartingAt = function (x, y) {
  72299. return BABYLON.Path2.StartingAt(x, y);
  72300. };
  72301. return Polygon;
  72302. }());
  72303. BABYLON.Polygon = Polygon;
  72304. var PolygonMeshBuilder = /** @class */ (function () {
  72305. function PolygonMeshBuilder(name, contours, scene) {
  72306. this._points = new PolygonPoints();
  72307. this._outlinepoints = new PolygonPoints();
  72308. this._holes = new Array();
  72309. this._epoints = new Array();
  72310. this._eholes = new Array();
  72311. this._name = name;
  72312. this._scene = scene;
  72313. var points;
  72314. if (contours instanceof BABYLON.Path2) {
  72315. points = contours.getPoints();
  72316. }
  72317. else {
  72318. points = contours;
  72319. }
  72320. this._addToepoint(points);
  72321. this._points.add(points);
  72322. this._outlinepoints.add(points);
  72323. }
  72324. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72325. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72326. var p = points_1[_i];
  72327. this._epoints.push(p.x, p.y);
  72328. }
  72329. };
  72330. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72331. this._points.add(hole);
  72332. var holepoints = new PolygonPoints();
  72333. holepoints.add(hole);
  72334. this._holes.push(holepoints);
  72335. this._eholes.push(this._epoints.length / 2);
  72336. this._addToepoint(hole);
  72337. return this;
  72338. };
  72339. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72340. var _this = this;
  72341. if (updatable === void 0) { updatable = false; }
  72342. if (depth === void 0) { depth = 0; }
  72343. var result = new BABYLON.Mesh(this._name, this._scene);
  72344. var normals = new Array();
  72345. var positions = new Array();
  72346. var uvs = new Array();
  72347. var bounds = this._points.computeBounds();
  72348. this._points.elements.forEach(function (p) {
  72349. normals.push(0, 1.0, 0);
  72350. positions.push(p.x, 0, p.y);
  72351. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72352. });
  72353. var indices = new Array();
  72354. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72355. for (var i = 0; i < res.length; i++) {
  72356. indices.push(res[i]);
  72357. }
  72358. if (depth > 0) {
  72359. var positionscount = (positions.length / 3); //get the current pointcount
  72360. this._points.elements.forEach(function (p) {
  72361. normals.push(0, -1.0, 0);
  72362. positions.push(p.x, -depth, p.y);
  72363. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72364. });
  72365. var totalCount = indices.length;
  72366. for (var i = 0; i < totalCount; i += 3) {
  72367. var i0 = indices[i + 0];
  72368. var i1 = indices[i + 1];
  72369. var i2 = indices[i + 2];
  72370. indices.push(i2 + positionscount);
  72371. indices.push(i1 + positionscount);
  72372. indices.push(i0 + positionscount);
  72373. }
  72374. //Add the sides
  72375. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72376. this._holes.forEach(function (hole) {
  72377. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72378. });
  72379. }
  72380. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72381. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72382. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72383. result.setIndices(indices);
  72384. return result;
  72385. };
  72386. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72387. var StartIndex = positions.length / 3;
  72388. var ulength = 0;
  72389. for (var i = 0; i < points.elements.length; i++) {
  72390. var p = points.elements[i];
  72391. var p1;
  72392. if ((i + 1) > points.elements.length - 1) {
  72393. p1 = points.elements[0];
  72394. }
  72395. else {
  72396. p1 = points.elements[i + 1];
  72397. }
  72398. positions.push(p.x, 0, p.y);
  72399. positions.push(p.x, -depth, p.y);
  72400. positions.push(p1.x, 0, p1.y);
  72401. positions.push(p1.x, -depth, p1.y);
  72402. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72403. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72404. var v3 = v2.subtract(v1);
  72405. var v4 = new BABYLON.Vector3(0, 1, 0);
  72406. var vn = BABYLON.Vector3.Cross(v3, v4);
  72407. vn = vn.normalize();
  72408. uvs.push(ulength / bounds.width, 0);
  72409. uvs.push(ulength / bounds.width, 1);
  72410. ulength += v3.length();
  72411. uvs.push((ulength / bounds.width), 0);
  72412. uvs.push((ulength / bounds.width), 1);
  72413. if (!flip) {
  72414. normals.push(-vn.x, -vn.y, -vn.z);
  72415. normals.push(-vn.x, -vn.y, -vn.z);
  72416. normals.push(-vn.x, -vn.y, -vn.z);
  72417. normals.push(-vn.x, -vn.y, -vn.z);
  72418. indices.push(StartIndex);
  72419. indices.push(StartIndex + 1);
  72420. indices.push(StartIndex + 2);
  72421. indices.push(StartIndex + 1);
  72422. indices.push(StartIndex + 3);
  72423. indices.push(StartIndex + 2);
  72424. }
  72425. else {
  72426. normals.push(vn.x, vn.y, vn.z);
  72427. normals.push(vn.x, vn.y, vn.z);
  72428. normals.push(vn.x, vn.y, vn.z);
  72429. normals.push(vn.x, vn.y, vn.z);
  72430. indices.push(StartIndex);
  72431. indices.push(StartIndex + 2);
  72432. indices.push(StartIndex + 1);
  72433. indices.push(StartIndex + 1);
  72434. indices.push(StartIndex + 2);
  72435. indices.push(StartIndex + 3);
  72436. }
  72437. StartIndex += 4;
  72438. }
  72439. ;
  72440. };
  72441. return PolygonMeshBuilder;
  72442. }());
  72443. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72444. })(BABYLON || (BABYLON = {}));
  72445. //# sourceMappingURL=babylon.polygonMesh.js.map
  72446. var BABYLON;
  72447. (function (BABYLON) {
  72448. // Unique ID when we import meshes from Babylon to CSG
  72449. var currentCSGMeshId = 0;
  72450. // # class Vertex
  72451. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72452. // one to provide additional features like texture coordinates and vertex
  72453. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72454. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72455. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72456. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72457. // is not used anywhere else.
  72458. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72459. var Vertex = /** @class */ (function () {
  72460. function Vertex(pos, normal, uv) {
  72461. this.pos = pos;
  72462. this.normal = normal;
  72463. this.uv = uv;
  72464. }
  72465. Vertex.prototype.clone = function () {
  72466. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72467. };
  72468. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72469. // orientation of a polygon is flipped.
  72470. Vertex.prototype.flip = function () {
  72471. this.normal = this.normal.scale(-1);
  72472. };
  72473. // Create a new vertex between this vertex and `other` by linearly
  72474. // interpolating all properties using a parameter of `t`. Subclasses should
  72475. // override this to interpolate additional properties.
  72476. Vertex.prototype.interpolate = function (other, t) {
  72477. 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));
  72478. };
  72479. return Vertex;
  72480. }());
  72481. // # class Plane
  72482. // Represents a plane in 3D space.
  72483. var Plane = /** @class */ (function () {
  72484. function Plane(normal, w) {
  72485. this.normal = normal;
  72486. this.w = w;
  72487. }
  72488. Plane.FromPoints = function (a, b, c) {
  72489. var v0 = c.subtract(a);
  72490. var v1 = b.subtract(a);
  72491. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72492. return null;
  72493. }
  72494. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72495. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72496. };
  72497. Plane.prototype.clone = function () {
  72498. return new Plane(this.normal.clone(), this.w);
  72499. };
  72500. Plane.prototype.flip = function () {
  72501. this.normal.scaleInPlace(-1);
  72502. this.w = -this.w;
  72503. };
  72504. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72505. // fragments in the appropriate lists. Coplanar polygons go into either
  72506. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72507. // respect to this plane. Polygons in front or in back of this plane go into
  72508. // either `front` or `back`.
  72509. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72510. var COPLANAR = 0;
  72511. var FRONT = 1;
  72512. var BACK = 2;
  72513. var SPANNING = 3;
  72514. // Classify each point as well as the entire polygon into one of the above
  72515. // four classes.
  72516. var polygonType = 0;
  72517. var types = [];
  72518. var i;
  72519. var t;
  72520. for (i = 0; i < polygon.vertices.length; i++) {
  72521. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72522. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72523. polygonType |= type;
  72524. types.push(type);
  72525. }
  72526. // Put the polygon in the correct list, splitting it when necessary.
  72527. switch (polygonType) {
  72528. case COPLANAR:
  72529. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72530. break;
  72531. case FRONT:
  72532. front.push(polygon);
  72533. break;
  72534. case BACK:
  72535. back.push(polygon);
  72536. break;
  72537. case SPANNING:
  72538. var f = [], b = [];
  72539. for (i = 0; i < polygon.vertices.length; i++) {
  72540. var j = (i + 1) % polygon.vertices.length;
  72541. var ti = types[i], tj = types[j];
  72542. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72543. if (ti !== BACK)
  72544. f.push(vi);
  72545. if (ti !== FRONT)
  72546. b.push(ti !== BACK ? vi.clone() : vi);
  72547. if ((ti | tj) === SPANNING) {
  72548. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72549. var v = vi.interpolate(vj, t);
  72550. f.push(v);
  72551. b.push(v.clone());
  72552. }
  72553. }
  72554. var poly;
  72555. if (f.length >= 3) {
  72556. poly = new Polygon(f, polygon.shared);
  72557. if (poly.plane)
  72558. front.push(poly);
  72559. }
  72560. if (b.length >= 3) {
  72561. poly = new Polygon(b, polygon.shared);
  72562. if (poly.plane)
  72563. back.push(poly);
  72564. }
  72565. break;
  72566. }
  72567. };
  72568. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72569. // point is on the plane.
  72570. Plane.EPSILON = 1e-5;
  72571. return Plane;
  72572. }());
  72573. // # class Polygon
  72574. // Represents a convex polygon. The vertices used to initialize a polygon must
  72575. // be coplanar and form a convex loop.
  72576. //
  72577. // Each convex polygon has a `shared` property, which is shared between all
  72578. // polygons that are clones of each other or were split from the same polygon.
  72579. // This can be used to define per-polygon properties (such as surface color).
  72580. var Polygon = /** @class */ (function () {
  72581. function Polygon(vertices, shared) {
  72582. this.vertices = vertices;
  72583. this.shared = shared;
  72584. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72585. }
  72586. Polygon.prototype.clone = function () {
  72587. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72588. return new Polygon(vertices, this.shared);
  72589. };
  72590. Polygon.prototype.flip = function () {
  72591. this.vertices.reverse().map(function (v) { v.flip(); });
  72592. this.plane.flip();
  72593. };
  72594. return Polygon;
  72595. }());
  72596. // # class Node
  72597. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72598. // by picking a polygon to split along. That polygon (and all other coplanar
  72599. // polygons) are added directly to that node and the other polygons are added to
  72600. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72601. // no distinction between internal and leaf nodes.
  72602. var Node = /** @class */ (function () {
  72603. function Node(polygons) {
  72604. this.plane = null;
  72605. this.front = null;
  72606. this.back = null;
  72607. this.polygons = new Array();
  72608. if (polygons) {
  72609. this.build(polygons);
  72610. }
  72611. }
  72612. Node.prototype.clone = function () {
  72613. var node = new Node();
  72614. node.plane = this.plane && this.plane.clone();
  72615. node.front = this.front && this.front.clone();
  72616. node.back = this.back && this.back.clone();
  72617. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72618. return node;
  72619. };
  72620. // Convert solid space to empty space and empty space to solid space.
  72621. Node.prototype.invert = function () {
  72622. for (var i = 0; i < this.polygons.length; i++) {
  72623. this.polygons[i].flip();
  72624. }
  72625. if (this.plane) {
  72626. this.plane.flip();
  72627. }
  72628. if (this.front) {
  72629. this.front.invert();
  72630. }
  72631. if (this.back) {
  72632. this.back.invert();
  72633. }
  72634. var temp = this.front;
  72635. this.front = this.back;
  72636. this.back = temp;
  72637. };
  72638. // Recursively remove all polygons in `polygons` that are inside this BSP
  72639. // tree.
  72640. Node.prototype.clipPolygons = function (polygons) {
  72641. if (!this.plane)
  72642. return polygons.slice();
  72643. var front = new Array(), back = new Array();
  72644. for (var i = 0; i < polygons.length; i++) {
  72645. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72646. }
  72647. if (this.front) {
  72648. front = this.front.clipPolygons(front);
  72649. }
  72650. if (this.back) {
  72651. back = this.back.clipPolygons(back);
  72652. }
  72653. else {
  72654. back = [];
  72655. }
  72656. return front.concat(back);
  72657. };
  72658. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72659. // `bsp`.
  72660. Node.prototype.clipTo = function (bsp) {
  72661. this.polygons = bsp.clipPolygons(this.polygons);
  72662. if (this.front)
  72663. this.front.clipTo(bsp);
  72664. if (this.back)
  72665. this.back.clipTo(bsp);
  72666. };
  72667. // Return a list of all polygons in this BSP tree.
  72668. Node.prototype.allPolygons = function () {
  72669. var polygons = this.polygons.slice();
  72670. if (this.front)
  72671. polygons = polygons.concat(this.front.allPolygons());
  72672. if (this.back)
  72673. polygons = polygons.concat(this.back.allPolygons());
  72674. return polygons;
  72675. };
  72676. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72677. // new polygons are filtered down to the bottom of the tree and become new
  72678. // nodes there. Each set of polygons is partitioned using the first polygon
  72679. // (no heuristic is used to pick a good split).
  72680. Node.prototype.build = function (polygons) {
  72681. if (!polygons.length)
  72682. return;
  72683. if (!this.plane)
  72684. this.plane = polygons[0].plane.clone();
  72685. var front = new Array(), back = new Array();
  72686. for (var i = 0; i < polygons.length; i++) {
  72687. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72688. }
  72689. if (front.length) {
  72690. if (!this.front)
  72691. this.front = new Node();
  72692. this.front.build(front);
  72693. }
  72694. if (back.length) {
  72695. if (!this.back)
  72696. this.back = new Node();
  72697. this.back.build(back);
  72698. }
  72699. };
  72700. return Node;
  72701. }());
  72702. var CSG = /** @class */ (function () {
  72703. function CSG() {
  72704. this.polygons = new Array();
  72705. }
  72706. // Convert BABYLON.Mesh to BABYLON.CSG
  72707. CSG.FromMesh = function (mesh) {
  72708. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72709. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72710. if (mesh instanceof BABYLON.Mesh) {
  72711. mesh.computeWorldMatrix(true);
  72712. matrix = mesh.getWorldMatrix();
  72713. meshPosition = mesh.position.clone();
  72714. meshRotation = mesh.rotation.clone();
  72715. if (mesh.rotationQuaternion) {
  72716. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72717. }
  72718. meshScaling = mesh.scaling.clone();
  72719. }
  72720. else {
  72721. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72722. }
  72723. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72724. var subMeshes = mesh.subMeshes;
  72725. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72726. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72727. vertices = [];
  72728. for (var j = 0; j < 3; j++) {
  72729. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72730. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72731. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72732. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72733. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72734. vertex = new Vertex(position, normal, uv);
  72735. vertices.push(vertex);
  72736. }
  72737. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72738. // To handle the case of degenerated triangle
  72739. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72740. if (polygon.plane)
  72741. polygons.push(polygon);
  72742. }
  72743. }
  72744. var csg = CSG.FromPolygons(polygons);
  72745. csg.matrix = matrix;
  72746. csg.position = meshPosition;
  72747. csg.rotation = meshRotation;
  72748. csg.scaling = meshScaling;
  72749. csg.rotationQuaternion = meshRotationQuaternion;
  72750. currentCSGMeshId++;
  72751. return csg;
  72752. };
  72753. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72754. CSG.FromPolygons = function (polygons) {
  72755. var csg = new CSG();
  72756. csg.polygons = polygons;
  72757. return csg;
  72758. };
  72759. CSG.prototype.clone = function () {
  72760. var csg = new CSG();
  72761. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72762. csg.copyTransformAttributes(this);
  72763. return csg;
  72764. };
  72765. CSG.prototype.union = function (csg) {
  72766. var a = new Node(this.clone().polygons);
  72767. var b = new Node(csg.clone().polygons);
  72768. a.clipTo(b);
  72769. b.clipTo(a);
  72770. b.invert();
  72771. b.clipTo(a);
  72772. b.invert();
  72773. a.build(b.allPolygons());
  72774. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72775. };
  72776. CSG.prototype.unionInPlace = function (csg) {
  72777. var a = new Node(this.polygons);
  72778. var b = new Node(csg.polygons);
  72779. a.clipTo(b);
  72780. b.clipTo(a);
  72781. b.invert();
  72782. b.clipTo(a);
  72783. b.invert();
  72784. a.build(b.allPolygons());
  72785. this.polygons = a.allPolygons();
  72786. };
  72787. CSG.prototype.subtract = function (csg) {
  72788. var a = new Node(this.clone().polygons);
  72789. var b = new Node(csg.clone().polygons);
  72790. a.invert();
  72791. a.clipTo(b);
  72792. b.clipTo(a);
  72793. b.invert();
  72794. b.clipTo(a);
  72795. b.invert();
  72796. a.build(b.allPolygons());
  72797. a.invert();
  72798. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72799. };
  72800. CSG.prototype.subtractInPlace = function (csg) {
  72801. var a = new Node(this.polygons);
  72802. var b = new Node(csg.polygons);
  72803. a.invert();
  72804. a.clipTo(b);
  72805. b.clipTo(a);
  72806. b.invert();
  72807. b.clipTo(a);
  72808. b.invert();
  72809. a.build(b.allPolygons());
  72810. a.invert();
  72811. this.polygons = a.allPolygons();
  72812. };
  72813. CSG.prototype.intersect = function (csg) {
  72814. var a = new Node(this.clone().polygons);
  72815. var b = new Node(csg.clone().polygons);
  72816. a.invert();
  72817. b.clipTo(a);
  72818. b.invert();
  72819. a.clipTo(b);
  72820. b.clipTo(a);
  72821. a.build(b.allPolygons());
  72822. a.invert();
  72823. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72824. };
  72825. CSG.prototype.intersectInPlace = function (csg) {
  72826. var a = new Node(this.polygons);
  72827. var b = new Node(csg.polygons);
  72828. a.invert();
  72829. b.clipTo(a);
  72830. b.invert();
  72831. a.clipTo(b);
  72832. b.clipTo(a);
  72833. a.build(b.allPolygons());
  72834. a.invert();
  72835. this.polygons = a.allPolygons();
  72836. };
  72837. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72838. // not modified.
  72839. CSG.prototype.inverse = function () {
  72840. var csg = this.clone();
  72841. csg.inverseInPlace();
  72842. return csg;
  72843. };
  72844. CSG.prototype.inverseInPlace = function () {
  72845. this.polygons.map(function (p) { p.flip(); });
  72846. };
  72847. // This is used to keep meshes transformations so they can be restored
  72848. // when we build back a Babylon Mesh
  72849. // NB : All CSG operations are performed in world coordinates
  72850. CSG.prototype.copyTransformAttributes = function (csg) {
  72851. this.matrix = csg.matrix;
  72852. this.position = csg.position;
  72853. this.rotation = csg.rotation;
  72854. this.scaling = csg.scaling;
  72855. this.rotationQuaternion = csg.rotationQuaternion;
  72856. return this;
  72857. };
  72858. // Build Raw mesh from CSG
  72859. // Coordinates here are in world space
  72860. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72861. var matrix = this.matrix.clone();
  72862. matrix.invert();
  72863. 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;
  72864. if (keepSubMeshes) {
  72865. // Sort Polygons, since subMeshes are indices range
  72866. polygons.sort(function (a, b) {
  72867. if (a.shared.meshId === b.shared.meshId) {
  72868. return a.shared.subMeshId - b.shared.subMeshId;
  72869. }
  72870. else {
  72871. return a.shared.meshId - b.shared.meshId;
  72872. }
  72873. });
  72874. }
  72875. for (var i = 0, il = polygons.length; i < il; i++) {
  72876. polygon = polygons[i];
  72877. // Building SubMeshes
  72878. if (!subMesh_dict[polygon.shared.meshId]) {
  72879. subMesh_dict[polygon.shared.meshId] = {};
  72880. }
  72881. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72882. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72883. indexStart: +Infinity,
  72884. indexEnd: -Infinity,
  72885. materialIndex: polygon.shared.materialIndex
  72886. };
  72887. }
  72888. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72889. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72890. polygonIndices[0] = 0;
  72891. polygonIndices[1] = j - 1;
  72892. polygonIndices[2] = j;
  72893. for (var k = 0; k < 3; k++) {
  72894. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72895. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72896. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72897. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72898. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72899. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72900. // Check if 2 points can be merged
  72901. if (!(typeof vertex_idx !== 'undefined' &&
  72902. normals[vertex_idx * 3] === localNormal.x &&
  72903. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72904. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72905. uvs[vertex_idx * 2] === uv.x &&
  72906. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72907. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72908. uvs.push(uv.x, uv.y);
  72909. normals.push(normal.x, normal.y, normal.z);
  72910. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72911. }
  72912. indices.push(vertex_idx);
  72913. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72914. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72915. currentIndex++;
  72916. }
  72917. }
  72918. }
  72919. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72920. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72921. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72922. mesh.setIndices(indices, null);
  72923. if (keepSubMeshes) {
  72924. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72925. var materialIndexOffset = 0, materialMaxIndex;
  72926. mesh.subMeshes = new Array();
  72927. for (var m in subMesh_dict) {
  72928. materialMaxIndex = -1;
  72929. for (var sm in subMesh_dict[m]) {
  72930. subMesh_obj = subMesh_dict[m][sm];
  72931. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72932. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72933. }
  72934. materialIndexOffset += ++materialMaxIndex;
  72935. }
  72936. }
  72937. return mesh;
  72938. };
  72939. // Build Mesh from CSG taking material and transforms into account
  72940. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72941. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72942. mesh.material = material;
  72943. mesh.position.copyFrom(this.position);
  72944. mesh.rotation.copyFrom(this.rotation);
  72945. if (this.rotationQuaternion) {
  72946. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72947. }
  72948. mesh.scaling.copyFrom(this.scaling);
  72949. mesh.computeWorldMatrix(true);
  72950. return mesh;
  72951. };
  72952. return CSG;
  72953. }());
  72954. BABYLON.CSG = CSG;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.csg.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. var LensFlare = /** @class */ (function () {
  72960. function LensFlare(size, position, color, imgUrl, system) {
  72961. this.size = size;
  72962. this.position = position;
  72963. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72964. this.color = color || new BABYLON.Color3(1, 1, 1);
  72965. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72966. this._system = system;
  72967. system.lensFlares.push(this);
  72968. }
  72969. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72970. return new LensFlare(size, position, color, imgUrl, system);
  72971. };
  72972. LensFlare.prototype.dispose = function () {
  72973. if (this.texture) {
  72974. this.texture.dispose();
  72975. }
  72976. // Remove from scene
  72977. var index = this._system.lensFlares.indexOf(this);
  72978. this._system.lensFlares.splice(index, 1);
  72979. };
  72980. ;
  72981. return LensFlare;
  72982. }());
  72983. BABYLON.LensFlare = LensFlare;
  72984. })(BABYLON || (BABYLON = {}));
  72985. //# sourceMappingURL=babylon.lensFlare.js.map
  72986. var BABYLON;
  72987. (function (BABYLON) {
  72988. var LensFlareSystem = /** @class */ (function () {
  72989. function LensFlareSystem(name, emitter, scene) {
  72990. this.name = name;
  72991. this.lensFlares = new Array();
  72992. this.borderLimit = 300;
  72993. this.viewportBorder = 0;
  72994. this.layerMask = 0x0FFFFFFF;
  72995. this._vertexBuffers = {};
  72996. this._isEnabled = true;
  72997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72998. this._emitter = emitter;
  72999. this.id = name;
  73000. scene.lensFlareSystems.push(this);
  73001. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73002. var engine = scene.getEngine();
  73003. // VBO
  73004. var vertices = [];
  73005. vertices.push(1, 1);
  73006. vertices.push(-1, 1);
  73007. vertices.push(-1, -1);
  73008. vertices.push(1, -1);
  73009. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73010. // Indices
  73011. var indices = [];
  73012. indices.push(0);
  73013. indices.push(1);
  73014. indices.push(2);
  73015. indices.push(0);
  73016. indices.push(2);
  73017. indices.push(3);
  73018. this._indexBuffer = engine.createIndexBuffer(indices);
  73019. // Effects
  73020. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73021. }
  73022. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73023. get: function () {
  73024. return this._isEnabled;
  73025. },
  73026. set: function (value) {
  73027. this._isEnabled = value;
  73028. },
  73029. enumerable: true,
  73030. configurable: true
  73031. });
  73032. LensFlareSystem.prototype.getScene = function () {
  73033. return this._scene;
  73034. };
  73035. LensFlareSystem.prototype.getEmitter = function () {
  73036. return this._emitter;
  73037. };
  73038. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73039. this._emitter = newEmitter;
  73040. };
  73041. LensFlareSystem.prototype.getEmitterPosition = function () {
  73042. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73043. };
  73044. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73045. var position = this.getEmitterPosition();
  73046. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73047. this._positionX = position.x;
  73048. this._positionY = position.y;
  73049. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73050. if (this.viewportBorder > 0) {
  73051. globalViewport.x -= this.viewportBorder;
  73052. globalViewport.y -= this.viewportBorder;
  73053. globalViewport.width += this.viewportBorder * 2;
  73054. globalViewport.height += this.viewportBorder * 2;
  73055. position.x += this.viewportBorder;
  73056. position.y += this.viewportBorder;
  73057. this._positionX += this.viewportBorder;
  73058. this._positionY += this.viewportBorder;
  73059. }
  73060. if (position.z > 0) {
  73061. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73062. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73063. return true;
  73064. }
  73065. return true;
  73066. }
  73067. return false;
  73068. };
  73069. LensFlareSystem.prototype._isVisible = function () {
  73070. if (!this._isEnabled || !this._scene.activeCamera) {
  73071. return false;
  73072. }
  73073. var emitterPosition = this.getEmitterPosition();
  73074. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73075. var distance = direction.length();
  73076. direction.normalize();
  73077. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73078. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73079. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73080. };
  73081. LensFlareSystem.prototype.render = function () {
  73082. if (!this._effect.isReady() || !this._scene.activeCamera)
  73083. return false;
  73084. var engine = this._scene.getEngine();
  73085. var viewport = this._scene.activeCamera.viewport;
  73086. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73087. // Position
  73088. if (!this.computeEffectivePosition(globalViewport)) {
  73089. return false;
  73090. }
  73091. // Visibility
  73092. if (!this._isVisible()) {
  73093. return false;
  73094. }
  73095. // Intensity
  73096. var awayX;
  73097. var awayY;
  73098. if (this._positionX < this.borderLimit + globalViewport.x) {
  73099. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73100. }
  73101. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73102. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73103. }
  73104. else {
  73105. awayX = 0;
  73106. }
  73107. if (this._positionY < this.borderLimit + globalViewport.y) {
  73108. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73109. }
  73110. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73111. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73112. }
  73113. else {
  73114. awayY = 0;
  73115. }
  73116. var away = (awayX > awayY) ? awayX : awayY;
  73117. away -= this.viewportBorder;
  73118. if (away > this.borderLimit) {
  73119. away = this.borderLimit;
  73120. }
  73121. var intensity = 1.0 - (away / this.borderLimit);
  73122. if (intensity < 0) {
  73123. return false;
  73124. }
  73125. if (intensity > 1.0) {
  73126. intensity = 1.0;
  73127. }
  73128. if (this.viewportBorder > 0) {
  73129. globalViewport.x += this.viewportBorder;
  73130. globalViewport.y += this.viewportBorder;
  73131. globalViewport.width -= this.viewportBorder * 2;
  73132. globalViewport.height -= this.viewportBorder * 2;
  73133. this._positionX -= this.viewportBorder;
  73134. this._positionY -= this.viewportBorder;
  73135. }
  73136. // Position
  73137. var centerX = globalViewport.x + globalViewport.width / 2;
  73138. var centerY = globalViewport.y + globalViewport.height / 2;
  73139. var distX = centerX - this._positionX;
  73140. var distY = centerY - this._positionY;
  73141. // Effects
  73142. engine.enableEffect(this._effect);
  73143. engine.setState(false);
  73144. engine.setDepthBuffer(false);
  73145. // VBOs
  73146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73147. // Flares
  73148. for (var index = 0; index < this.lensFlares.length; index++) {
  73149. var flare = this.lensFlares[index];
  73150. engine.setAlphaMode(flare.alphaMode);
  73151. var x = centerX - (distX * flare.position);
  73152. var y = centerY - (distY * flare.position);
  73153. var cw = flare.size;
  73154. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73155. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73156. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73157. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73158. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73159. // Texture
  73160. this._effect.setTexture("textureSampler", flare.texture);
  73161. // Color
  73162. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73163. // Draw order
  73164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73165. }
  73166. engine.setDepthBuffer(true);
  73167. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73168. return true;
  73169. };
  73170. LensFlareSystem.prototype.dispose = function () {
  73171. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73172. if (vertexBuffer) {
  73173. vertexBuffer.dispose();
  73174. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73175. }
  73176. if (this._indexBuffer) {
  73177. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73178. this._indexBuffer = null;
  73179. }
  73180. while (this.lensFlares.length) {
  73181. this.lensFlares[0].dispose();
  73182. }
  73183. // Remove from scene
  73184. var index = this._scene.lensFlareSystems.indexOf(this);
  73185. this._scene.lensFlareSystems.splice(index, 1);
  73186. };
  73187. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73188. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73189. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73190. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73191. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73192. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73193. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73194. var parsedFlare = parsedLensFlareSystem.flares[index];
  73195. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73196. }
  73197. return lensFlareSystem;
  73198. };
  73199. LensFlareSystem.prototype.serialize = function () {
  73200. var serializationObject = {};
  73201. serializationObject.id = this.id;
  73202. serializationObject.name = this.name;
  73203. serializationObject.emitterId = this.getEmitter().id;
  73204. serializationObject.borderLimit = this.borderLimit;
  73205. serializationObject.flares = [];
  73206. for (var index = 0; index < this.lensFlares.length; index++) {
  73207. var flare = this.lensFlares[index];
  73208. serializationObject.flares.push({
  73209. size: flare.size,
  73210. position: flare.position,
  73211. color: flare.color.asArray(),
  73212. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73213. });
  73214. }
  73215. return serializationObject;
  73216. };
  73217. return LensFlareSystem;
  73218. }());
  73219. BABYLON.LensFlareSystem = LensFlareSystem;
  73220. })(BABYLON || (BABYLON = {}));
  73221. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73222. var BABYLON;
  73223. (function (BABYLON) {
  73224. /**
  73225. * This is a holder class for the physics joint created by the physics plugin.
  73226. * It holds a set of functions to control the underlying joint.
  73227. */
  73228. var PhysicsJoint = /** @class */ (function () {
  73229. function PhysicsJoint(type, jointData) {
  73230. this.type = type;
  73231. this.jointData = jointData;
  73232. jointData.nativeParams = jointData.nativeParams || {};
  73233. }
  73234. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73235. get: function () {
  73236. return this._physicsJoint;
  73237. },
  73238. set: function (newJoint) {
  73239. if (this._physicsJoint) {
  73240. //remove from the wolrd
  73241. }
  73242. this._physicsJoint = newJoint;
  73243. },
  73244. enumerable: true,
  73245. configurable: true
  73246. });
  73247. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73248. set: function (physicsPlugin) {
  73249. this._physicsPlugin = physicsPlugin;
  73250. },
  73251. enumerable: true,
  73252. configurable: true
  73253. });
  73254. /**
  73255. * Execute a function that is physics-plugin specific.
  73256. * @param {Function} func the function that will be executed.
  73257. * It accepts two parameters: the physics world and the physics joint.
  73258. */
  73259. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73260. func(this._physicsPlugin.world, this._physicsJoint);
  73261. };
  73262. //TODO check if the native joints are the same
  73263. //Joint Types
  73264. PhysicsJoint.DistanceJoint = 0;
  73265. PhysicsJoint.HingeJoint = 1;
  73266. PhysicsJoint.BallAndSocketJoint = 2;
  73267. PhysicsJoint.WheelJoint = 3;
  73268. PhysicsJoint.SliderJoint = 4;
  73269. //OIMO
  73270. PhysicsJoint.PrismaticJoint = 5;
  73271. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73272. PhysicsJoint.UniversalJoint = 6;
  73273. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73274. //Cannon
  73275. //Similar to a Ball-Joint. Different in params
  73276. PhysicsJoint.PointToPointJoint = 8;
  73277. //Cannon only at the moment
  73278. PhysicsJoint.SpringJoint = 9;
  73279. PhysicsJoint.LockJoint = 10;
  73280. return PhysicsJoint;
  73281. }());
  73282. BABYLON.PhysicsJoint = PhysicsJoint;
  73283. /**
  73284. * A class representing a physics distance joint.
  73285. */
  73286. var DistanceJoint = /** @class */ (function (_super) {
  73287. __extends(DistanceJoint, _super);
  73288. function DistanceJoint(jointData) {
  73289. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73290. }
  73291. /**
  73292. * Update the predefined distance.
  73293. */
  73294. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73295. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73296. };
  73297. return DistanceJoint;
  73298. }(PhysicsJoint));
  73299. BABYLON.DistanceJoint = DistanceJoint;
  73300. var MotorEnabledJoint = /** @class */ (function (_super) {
  73301. __extends(MotorEnabledJoint, _super);
  73302. function MotorEnabledJoint(type, jointData) {
  73303. return _super.call(this, type, jointData) || this;
  73304. }
  73305. /**
  73306. * Set the motor values.
  73307. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73308. * @param {number} force the force to apply
  73309. * @param {number} maxForce max force for this motor.
  73310. */
  73311. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73312. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73313. };
  73314. /**
  73315. * Set the motor's limits.
  73316. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73317. */
  73318. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73319. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73320. };
  73321. return MotorEnabledJoint;
  73322. }(PhysicsJoint));
  73323. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73324. /**
  73325. * This class represents a single hinge physics joint
  73326. */
  73327. var HingeJoint = /** @class */ (function (_super) {
  73328. __extends(HingeJoint, _super);
  73329. function HingeJoint(jointData) {
  73330. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73331. }
  73332. /**
  73333. * Set the motor values.
  73334. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73335. * @param {number} force the force to apply
  73336. * @param {number} maxForce max force for this motor.
  73337. */
  73338. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73339. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73340. };
  73341. /**
  73342. * Set the motor's limits.
  73343. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73344. */
  73345. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73346. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73347. };
  73348. return HingeJoint;
  73349. }(MotorEnabledJoint));
  73350. BABYLON.HingeJoint = HingeJoint;
  73351. /**
  73352. * This class represents a dual hinge physics joint (same as wheel joint)
  73353. */
  73354. var Hinge2Joint = /** @class */ (function (_super) {
  73355. __extends(Hinge2Joint, _super);
  73356. function Hinge2Joint(jointData) {
  73357. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73358. }
  73359. /**
  73360. * Set the motor values.
  73361. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73362. * @param {number} force the force to apply
  73363. * @param {number} maxForce max force for this motor.
  73364. * @param {motorIndex} the motor's index, 0 or 1.
  73365. */
  73366. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73367. if (motorIndex === void 0) { motorIndex = 0; }
  73368. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73369. };
  73370. /**
  73371. * Set the motor limits.
  73372. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73373. * @param {number} upperLimit the upper limit
  73374. * @param {number} lowerLimit lower limit
  73375. * @param {motorIndex} the motor's index, 0 or 1.
  73376. */
  73377. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73378. if (motorIndex === void 0) { motorIndex = 0; }
  73379. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73380. };
  73381. return Hinge2Joint;
  73382. }(MotorEnabledJoint));
  73383. BABYLON.Hinge2Joint = Hinge2Joint;
  73384. })(BABYLON || (BABYLON = {}));
  73385. //# sourceMappingURL=babylon.physicsJoint.js.map
  73386. var BABYLON;
  73387. (function (BABYLON) {
  73388. var PhysicsImpostor = /** @class */ (function () {
  73389. function PhysicsImpostor(object, type, _options, _scene) {
  73390. if (_options === void 0) { _options = { mass: 0 }; }
  73391. var _this = this;
  73392. this.object = object;
  73393. this.type = type;
  73394. this._options = _options;
  73395. this._scene = _scene;
  73396. this._bodyUpdateRequired = false;
  73397. this._onBeforePhysicsStepCallbacks = new Array();
  73398. this._onAfterPhysicsStepCallbacks = new Array();
  73399. this._onPhysicsCollideCallbacks = [];
  73400. this._deltaPosition = BABYLON.Vector3.Zero();
  73401. this._isDisposed = false;
  73402. //temp variables for parent rotation calculations
  73403. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73404. this._tmpQuat = new BABYLON.Quaternion();
  73405. this._tmpQuat2 = new BABYLON.Quaternion();
  73406. /**
  73407. * this function is executed by the physics engine.
  73408. */
  73409. this.beforeStep = function () {
  73410. if (!_this._physicsEngine) {
  73411. return;
  73412. }
  73413. _this.object.translate(_this._deltaPosition, -1);
  73414. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73415. _this.object.computeWorldMatrix(false);
  73416. if (_this.object.parent && _this.object.rotationQuaternion) {
  73417. _this.getParentsRotation();
  73418. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73419. }
  73420. else {
  73421. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73422. }
  73423. if (!_this._options.disableBidirectionalTransformation) {
  73424. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73425. }
  73426. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73427. func(_this);
  73428. });
  73429. };
  73430. /**
  73431. * this function is executed by the physics engine.
  73432. */
  73433. this.afterStep = function () {
  73434. if (!_this._physicsEngine) {
  73435. return;
  73436. }
  73437. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73438. func(_this);
  73439. });
  73440. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73441. // object has now its world rotation. needs to be converted to local.
  73442. if (_this.object.parent && _this.object.rotationQuaternion) {
  73443. _this.getParentsRotation();
  73444. _this._tmpQuat.conjugateInPlace();
  73445. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73446. }
  73447. // take the position set and make it the absolute position of this object.
  73448. _this.object.setAbsolutePosition(_this.object.position);
  73449. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73450. _this.object.translate(_this._deltaPosition, 1);
  73451. };
  73452. /**
  73453. * Legacy collision detection event support
  73454. */
  73455. this.onCollideEvent = null;
  73456. //event and body object due to cannon's event-based architecture.
  73457. this.onCollide = function (e) {
  73458. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73459. return;
  73460. }
  73461. if (!_this._physicsEngine) {
  73462. return;
  73463. }
  73464. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73465. if (otherImpostor) {
  73466. // Legacy collision detection event support
  73467. if (_this.onCollideEvent) {
  73468. _this.onCollideEvent(_this, otherImpostor);
  73469. }
  73470. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73471. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73472. }).forEach(function (obj) {
  73473. obj.callback(_this, otherImpostor);
  73474. });
  73475. }
  73476. };
  73477. //sanity check!
  73478. if (!this.object) {
  73479. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73480. return;
  73481. }
  73482. //legacy support for old syntax.
  73483. if (!this._scene && object.getScene) {
  73484. this._scene = object.getScene();
  73485. }
  73486. if (!this._scene) {
  73487. return;
  73488. }
  73489. this._physicsEngine = this._scene.getPhysicsEngine();
  73490. if (!this._physicsEngine) {
  73491. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73492. }
  73493. else {
  73494. //set the object's quaternion, if not set
  73495. if (!this.object.rotationQuaternion) {
  73496. if (this.object.rotation) {
  73497. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73498. }
  73499. else {
  73500. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73501. }
  73502. }
  73503. //default options params
  73504. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73505. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73506. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73507. this._joints = [];
  73508. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73509. if (!this.object.parent || this._options.ignoreParent) {
  73510. this._init();
  73511. }
  73512. else if (this.object.parent.physicsImpostor) {
  73513. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73514. }
  73515. }
  73516. }
  73517. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73518. get: function () {
  73519. return this._isDisposed;
  73520. },
  73521. enumerable: true,
  73522. configurable: true
  73523. });
  73524. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73525. get: function () {
  73526. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73527. },
  73528. set: function (value) {
  73529. this.setMass(value);
  73530. },
  73531. enumerable: true,
  73532. configurable: true
  73533. });
  73534. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73535. get: function () {
  73536. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73537. },
  73538. set: function (value) {
  73539. if (!this._physicsEngine) {
  73540. return;
  73541. }
  73542. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73543. },
  73544. enumerable: true,
  73545. configurable: true
  73546. });
  73547. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73548. get: function () {
  73549. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73550. },
  73551. set: function (value) {
  73552. if (!this._physicsEngine) {
  73553. return;
  73554. }
  73555. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73556. },
  73557. enumerable: true,
  73558. configurable: true
  73559. });
  73560. /**
  73561. * This function will completly initialize this impostor.
  73562. * It will create a new body - but only if this mesh has no parent.
  73563. * If it has, this impostor will not be used other than to define the impostor
  73564. * of the child mesh.
  73565. */
  73566. PhysicsImpostor.prototype._init = function () {
  73567. if (!this._physicsEngine) {
  73568. return;
  73569. }
  73570. this._physicsEngine.removeImpostor(this);
  73571. this.physicsBody = null;
  73572. this._parent = this._parent || this._getPhysicsParent();
  73573. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73574. this._physicsEngine.addImpostor(this);
  73575. }
  73576. };
  73577. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73578. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73579. var parentMesh = this.object.parent;
  73580. return parentMesh.physicsImpostor;
  73581. }
  73582. return null;
  73583. };
  73584. /**
  73585. * Should a new body be generated.
  73586. */
  73587. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73588. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73589. };
  73590. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73591. this.forceUpdate();
  73592. };
  73593. /**
  73594. * Force a regeneration of this or the parent's impostor's body.
  73595. * Use under cautious - This will remove all joints already implemented.
  73596. */
  73597. PhysicsImpostor.prototype.forceUpdate = function () {
  73598. this._init();
  73599. if (this.parent && !this._options.ignoreParent) {
  73600. this.parent.forceUpdate();
  73601. }
  73602. };
  73603. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73604. /*public get mesh(): AbstractMesh {
  73605. return this._mesh;
  73606. }*/
  73607. /**
  73608. * Gets the body that holds this impostor. Either its own, or its parent.
  73609. */
  73610. get: function () {
  73611. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73612. },
  73613. /**
  73614. * Set the physics body. Used mainly by the physics engine/plugin
  73615. */
  73616. set: function (physicsBody) {
  73617. if (this._physicsBody && this._physicsEngine) {
  73618. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73619. }
  73620. this._physicsBody = physicsBody;
  73621. this.resetUpdateFlags();
  73622. },
  73623. enumerable: true,
  73624. configurable: true
  73625. });
  73626. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73627. get: function () {
  73628. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73629. },
  73630. set: function (value) {
  73631. this._parent = value;
  73632. },
  73633. enumerable: true,
  73634. configurable: true
  73635. });
  73636. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73637. this._bodyUpdateRequired = false;
  73638. };
  73639. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73640. if (this.object.getBoundingInfo) {
  73641. var q = this.object.rotationQuaternion;
  73642. //reset rotation
  73643. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73644. //calculate the world matrix with no rotation
  73645. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73646. var boundingInfo = this.object.getBoundingInfo();
  73647. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73648. //bring back the rotation
  73649. this.object.rotationQuaternion = q;
  73650. //calculate the world matrix with the new rotation
  73651. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73652. return size;
  73653. }
  73654. else {
  73655. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73656. }
  73657. };
  73658. PhysicsImpostor.prototype.getObjectCenter = function () {
  73659. if (this.object.getBoundingInfo) {
  73660. var boundingInfo = this.object.getBoundingInfo();
  73661. return boundingInfo.boundingBox.centerWorld;
  73662. }
  73663. else {
  73664. return this.object.position;
  73665. }
  73666. };
  73667. /**
  73668. * Get a specific parametes from the options parameter.
  73669. */
  73670. PhysicsImpostor.prototype.getParam = function (paramName) {
  73671. return this._options[paramName];
  73672. };
  73673. /**
  73674. * Sets a specific parameter in the options given to the physics plugin
  73675. */
  73676. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73677. this._options[paramName] = value;
  73678. this._bodyUpdateRequired = true;
  73679. };
  73680. /**
  73681. * Specifically change the body's mass option. Won't recreate the physics body object
  73682. */
  73683. PhysicsImpostor.prototype.setMass = function (mass) {
  73684. if (this.getParam("mass") !== mass) {
  73685. this.setParam("mass", mass);
  73686. }
  73687. if (this._physicsEngine) {
  73688. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73689. }
  73690. };
  73691. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73692. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73693. };
  73694. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73695. if (this._physicsEngine) {
  73696. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73697. }
  73698. };
  73699. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73700. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73701. };
  73702. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73703. if (this._physicsEngine) {
  73704. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73705. }
  73706. };
  73707. /**
  73708. * Execute a function with the physics plugin native code.
  73709. * Provide a function the will have two variables - the world object and the physics body object.
  73710. */
  73711. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73712. if (this._physicsEngine) {
  73713. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73714. }
  73715. };
  73716. /**
  73717. * Register a function that will be executed before the physics world is stepping forward.
  73718. */
  73719. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73720. this._onBeforePhysicsStepCallbacks.push(func);
  73721. };
  73722. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73723. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73724. if (index > -1) {
  73725. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73726. }
  73727. else {
  73728. BABYLON.Tools.Warn("Function to remove was not found");
  73729. }
  73730. };
  73731. /**
  73732. * Register a function that will be executed after the physics step
  73733. */
  73734. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73735. this._onAfterPhysicsStepCallbacks.push(func);
  73736. };
  73737. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73738. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73739. if (index > -1) {
  73740. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73741. }
  73742. else {
  73743. BABYLON.Tools.Warn("Function to remove was not found");
  73744. }
  73745. };
  73746. /**
  73747. * register a function that will be executed when this impostor collides against a different body.
  73748. */
  73749. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73750. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73751. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73752. };
  73753. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73754. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73755. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73756. if (index > -1) {
  73757. this._onPhysicsCollideCallbacks.splice(index, 1);
  73758. }
  73759. else {
  73760. BABYLON.Tools.Warn("Function to remove was not found");
  73761. }
  73762. };
  73763. PhysicsImpostor.prototype.getParentsRotation = function () {
  73764. var parent = this.object.parent;
  73765. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73766. while (parent) {
  73767. if (parent.rotationQuaternion) {
  73768. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73769. }
  73770. else {
  73771. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73772. }
  73773. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73774. parent = parent.parent;
  73775. }
  73776. return this._tmpQuat;
  73777. };
  73778. /**
  73779. * Apply a force
  73780. */
  73781. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73782. if (this._physicsEngine) {
  73783. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73784. }
  73785. return this;
  73786. };
  73787. /**
  73788. * Apply an impulse
  73789. */
  73790. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73791. if (this._physicsEngine) {
  73792. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73793. }
  73794. return this;
  73795. };
  73796. /**
  73797. * A help function to create a joint.
  73798. */
  73799. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73800. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73801. this.addJoint(otherImpostor, joint);
  73802. return this;
  73803. };
  73804. /**
  73805. * Add a joint to this impostor with a different impostor.
  73806. */
  73807. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73808. this._joints.push({
  73809. otherImpostor: otherImpostor,
  73810. joint: joint
  73811. });
  73812. if (this._physicsEngine) {
  73813. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73814. }
  73815. return this;
  73816. };
  73817. /**
  73818. * Will keep this body still, in a sleep mode.
  73819. */
  73820. PhysicsImpostor.prototype.sleep = function () {
  73821. if (this._physicsEngine) {
  73822. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73823. }
  73824. return this;
  73825. };
  73826. /**
  73827. * Wake the body up.
  73828. */
  73829. PhysicsImpostor.prototype.wakeUp = function () {
  73830. if (this._physicsEngine) {
  73831. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73832. }
  73833. return this;
  73834. };
  73835. PhysicsImpostor.prototype.clone = function (newObject) {
  73836. if (!newObject)
  73837. return null;
  73838. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73839. };
  73840. PhysicsImpostor.prototype.dispose = function () {
  73841. var _this = this;
  73842. //no dispose if no physics engine is available.
  73843. if (!this._physicsEngine) {
  73844. return;
  73845. }
  73846. this._joints.forEach(function (j) {
  73847. if (_this._physicsEngine) {
  73848. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73849. }
  73850. });
  73851. //dispose the physics body
  73852. this._physicsEngine.removeImpostor(this);
  73853. if (this.parent) {
  73854. this.parent.forceUpdate();
  73855. }
  73856. else {
  73857. /*this._object.getChildMeshes().forEach(function(mesh) {
  73858. if (mesh.physicsImpostor) {
  73859. if (disposeChildren) {
  73860. mesh.physicsImpostor.dispose();
  73861. mesh.physicsImpostor = null;
  73862. }
  73863. }
  73864. })*/
  73865. }
  73866. this._isDisposed = true;
  73867. };
  73868. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73869. this._deltaPosition.copyFrom(position);
  73870. };
  73871. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73872. if (!this._deltaRotation) {
  73873. this._deltaRotation = new BABYLON.Quaternion();
  73874. }
  73875. this._deltaRotation.copyFrom(rotation);
  73876. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73877. };
  73878. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73879. if (this._physicsEngine) {
  73880. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73881. }
  73882. return this;
  73883. };
  73884. PhysicsImpostor.prototype.getRadius = function () {
  73885. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73886. };
  73887. /**
  73888. * Sync a bone with this impostor
  73889. * @param bone The bone to sync to the impostor.
  73890. * @param boneMesh The mesh that the bone is influencing.
  73891. * @param jointPivot The pivot of the joint / bone in local space.
  73892. * @param distToJoint Optional distance from the impostor to the joint.
  73893. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73894. */
  73895. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73896. var tempVec = PhysicsImpostor._tmpVecs[0];
  73897. var mesh = this.object;
  73898. if (mesh.rotationQuaternion) {
  73899. if (adjustRotation) {
  73900. var tempQuat = PhysicsImpostor._tmpQuat;
  73901. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73902. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73903. }
  73904. else {
  73905. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73906. }
  73907. }
  73908. tempVec.x = 0;
  73909. tempVec.y = 0;
  73910. tempVec.z = 0;
  73911. if (jointPivot) {
  73912. tempVec.x = jointPivot.x;
  73913. tempVec.y = jointPivot.y;
  73914. tempVec.z = jointPivot.z;
  73915. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73916. if (distToJoint === undefined || distToJoint === null) {
  73917. distToJoint = jointPivot.length();
  73918. }
  73919. tempVec.x *= distToJoint;
  73920. tempVec.y *= distToJoint;
  73921. tempVec.z *= distToJoint;
  73922. }
  73923. if (bone.getParent()) {
  73924. tempVec.addInPlace(mesh.getAbsolutePosition());
  73925. bone.setAbsolutePosition(tempVec, boneMesh);
  73926. }
  73927. else {
  73928. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73929. boneMesh.position.x -= tempVec.x;
  73930. boneMesh.position.y -= tempVec.y;
  73931. boneMesh.position.z -= tempVec.z;
  73932. }
  73933. };
  73934. /**
  73935. * Sync impostor to a bone
  73936. * @param bone The bone that the impostor will be synced to.
  73937. * @param boneMesh The mesh that the bone is influencing.
  73938. * @param jointPivot The pivot of the joint / bone in local space.
  73939. * @param distToJoint Optional distance from the impostor to the joint.
  73940. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73941. * @param boneAxis Optional vector3 axis the bone is aligned with
  73942. */
  73943. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73944. var mesh = this.object;
  73945. if (mesh.rotationQuaternion) {
  73946. if (adjustRotation) {
  73947. var tempQuat = PhysicsImpostor._tmpQuat;
  73948. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73949. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73950. }
  73951. else {
  73952. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73953. }
  73954. }
  73955. var pos = PhysicsImpostor._tmpVecs[0];
  73956. var boneDir = PhysicsImpostor._tmpVecs[1];
  73957. if (!boneAxis) {
  73958. boneAxis = PhysicsImpostor._tmpVecs[2];
  73959. boneAxis.x = 0;
  73960. boneAxis.y = 1;
  73961. boneAxis.z = 0;
  73962. }
  73963. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73964. bone.getAbsolutePositionToRef(boneMesh, pos);
  73965. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73966. distToJoint = jointPivot.length();
  73967. }
  73968. if (distToJoint !== undefined && distToJoint !== null) {
  73969. pos.x += boneDir.x * distToJoint;
  73970. pos.y += boneDir.y * distToJoint;
  73971. pos.z += boneDir.z * distToJoint;
  73972. }
  73973. mesh.setAbsolutePosition(pos);
  73974. };
  73975. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73976. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73977. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73978. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73979. //Impostor types
  73980. PhysicsImpostor.NoImpostor = 0;
  73981. PhysicsImpostor.SphereImpostor = 1;
  73982. PhysicsImpostor.BoxImpostor = 2;
  73983. PhysicsImpostor.PlaneImpostor = 3;
  73984. PhysicsImpostor.MeshImpostor = 4;
  73985. PhysicsImpostor.CylinderImpostor = 7;
  73986. PhysicsImpostor.ParticleImpostor = 8;
  73987. PhysicsImpostor.HeightmapImpostor = 9;
  73988. return PhysicsImpostor;
  73989. }());
  73990. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73991. })(BABYLON || (BABYLON = {}));
  73992. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73993. var BABYLON;
  73994. (function (BABYLON) {
  73995. var PhysicsEngine = /** @class */ (function () {
  73996. function PhysicsEngine(gravity, _physicsPlugin) {
  73997. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73998. this._physicsPlugin = _physicsPlugin;
  73999. //new methods and parameters
  74000. this._impostors = [];
  74001. this._joints = [];
  74002. if (!this._physicsPlugin.isSupported()) {
  74003. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74004. + "Please make sure it is included.");
  74005. }
  74006. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74007. this.setGravity(gravity);
  74008. this.setTimeStep();
  74009. }
  74010. PhysicsEngine.prototype.setGravity = function (gravity) {
  74011. this.gravity = gravity;
  74012. this._physicsPlugin.setGravity(this.gravity);
  74013. };
  74014. /**
  74015. * Set the time step of the physics engine.
  74016. * default is 1/60.
  74017. * To slow it down, enter 1/600 for example.
  74018. * To speed it up, 1/30
  74019. * @param {number} newTimeStep the new timestep to apply to this world.
  74020. */
  74021. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74022. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74023. this._physicsPlugin.setTimeStep(newTimeStep);
  74024. };
  74025. /**
  74026. * Get the time step of the physics engine.
  74027. */
  74028. PhysicsEngine.prototype.getTimeStep = function () {
  74029. return this._physicsPlugin.getTimeStep();
  74030. };
  74031. PhysicsEngine.prototype.dispose = function () {
  74032. this._impostors.forEach(function (impostor) {
  74033. impostor.dispose();
  74034. });
  74035. this._physicsPlugin.dispose();
  74036. };
  74037. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74038. return this._physicsPlugin.name;
  74039. };
  74040. /**
  74041. * Adding a new impostor for the impostor tracking.
  74042. * This will be done by the impostor itself.
  74043. * @param {PhysicsImpostor} impostor the impostor to add
  74044. */
  74045. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74046. impostor.uniqueId = this._impostors.push(impostor);
  74047. //if no parent, generate the body
  74048. if (!impostor.parent) {
  74049. this._physicsPlugin.generatePhysicsBody(impostor);
  74050. }
  74051. };
  74052. /**
  74053. * Remove an impostor from the engine.
  74054. * This impostor and its mesh will not longer be updated by the physics engine.
  74055. * @param {PhysicsImpostor} impostor the impostor to remove
  74056. */
  74057. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74058. var index = this._impostors.indexOf(impostor);
  74059. if (index > -1) {
  74060. var removed = this._impostors.splice(index, 1);
  74061. //Is it needed?
  74062. if (removed.length) {
  74063. //this will also remove it from the world.
  74064. removed[0].physicsBody = null;
  74065. }
  74066. }
  74067. };
  74068. /**
  74069. * Add a joint to the physics engine
  74070. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74071. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74072. * @param {PhysicsJoint} the joint that will connect both impostors.
  74073. */
  74074. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74075. var impostorJoint = {
  74076. mainImpostor: mainImpostor,
  74077. connectedImpostor: connectedImpostor,
  74078. joint: joint
  74079. };
  74080. joint.physicsPlugin = this._physicsPlugin;
  74081. this._joints.push(impostorJoint);
  74082. this._physicsPlugin.generateJoint(impostorJoint);
  74083. };
  74084. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74085. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74086. return (impostorJoint.connectedImpostor === connectedImpostor
  74087. && impostorJoint.joint === joint
  74088. && impostorJoint.mainImpostor === mainImpostor);
  74089. });
  74090. if (matchingJoints.length) {
  74091. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74092. //TODO remove it from the list as well
  74093. }
  74094. };
  74095. /**
  74096. * Called by the scene. no need to call it.
  74097. */
  74098. PhysicsEngine.prototype._step = function (delta) {
  74099. var _this = this;
  74100. //check if any mesh has no body / requires an update
  74101. this._impostors.forEach(function (impostor) {
  74102. if (impostor.isBodyInitRequired()) {
  74103. _this._physicsPlugin.generatePhysicsBody(impostor);
  74104. }
  74105. });
  74106. if (delta > 0.1) {
  74107. delta = 0.1;
  74108. }
  74109. else if (delta <= 0) {
  74110. delta = 1.0 / 60.0;
  74111. }
  74112. this._physicsPlugin.executeStep(delta, this._impostors);
  74113. };
  74114. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74115. return this._physicsPlugin;
  74116. };
  74117. PhysicsEngine.prototype.getImpostors = function () {
  74118. return this._impostors;
  74119. };
  74120. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74121. for (var i = 0; i < this._impostors.length; ++i) {
  74122. if (this._impostors[i].object === object) {
  74123. return this._impostors[i];
  74124. }
  74125. }
  74126. return null;
  74127. };
  74128. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74129. for (var i = 0; i < this._impostors.length; ++i) {
  74130. if (this._impostors[i].physicsBody === body) {
  74131. return this._impostors[i];
  74132. }
  74133. }
  74134. return null;
  74135. };
  74136. // Statics
  74137. PhysicsEngine.Epsilon = 0.001;
  74138. return PhysicsEngine;
  74139. }());
  74140. BABYLON.PhysicsEngine = PhysicsEngine;
  74141. })(BABYLON || (BABYLON = {}));
  74142. //# sourceMappingURL=babylon.physicsEngine.js.map
  74143. var BABYLON;
  74144. (function (BABYLON) {
  74145. var PhysicsHelper = /** @class */ (function () {
  74146. function PhysicsHelper(scene) {
  74147. this._scene = scene;
  74148. this._physicsEngine = this._scene.getPhysicsEngine();
  74149. if (!this._physicsEngine) {
  74150. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74151. }
  74152. }
  74153. /**
  74154. * @param {Vector3} origin the origin of the explosion
  74155. * @param {number} radius the explosion radius
  74156. * @param {number} strength the explosion strength
  74157. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74158. */
  74159. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74160. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74161. if (!this._physicsEngine) {
  74162. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74163. return null;
  74164. }
  74165. var impostors = this._physicsEngine.getImpostors();
  74166. if (impostors.length === 0) {
  74167. return null;
  74168. }
  74169. var event = new PhysicsRadialExplosionEvent(this._scene);
  74170. impostors.forEach(function (impostor) {
  74171. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74172. if (!impostorForceAndContactPoint) {
  74173. return;
  74174. }
  74175. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74176. });
  74177. event.dispose(false);
  74178. return event;
  74179. };
  74180. /**
  74181. * @param {Vector3} origin the origin of the explosion
  74182. * @param {number} radius the explosion radius
  74183. * @param {number} strength the explosion strength
  74184. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74185. */
  74186. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74187. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74188. if (!this._physicsEngine) {
  74189. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74190. return null;
  74191. }
  74192. var impostors = this._physicsEngine.getImpostors();
  74193. if (impostors.length === 0) {
  74194. return null;
  74195. }
  74196. var event = new PhysicsRadialExplosionEvent(this._scene);
  74197. impostors.forEach(function (impostor) {
  74198. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74199. if (!impostorForceAndContactPoint) {
  74200. return;
  74201. }
  74202. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74203. });
  74204. event.dispose(false);
  74205. return event;
  74206. };
  74207. /**
  74208. * @param {Vector3} origin the origin of the explosion
  74209. * @param {number} radius the explosion radius
  74210. * @param {number} strength the explosion strength
  74211. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74212. */
  74213. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74214. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74215. if (!this._physicsEngine) {
  74216. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74217. return null;
  74218. }
  74219. var impostors = this._physicsEngine.getImpostors();
  74220. if (impostors.length === 0) {
  74221. return null;
  74222. }
  74223. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74224. event.dispose(false);
  74225. return event;
  74226. };
  74227. /**
  74228. * @param {Vector3} origin the origin of the updraft
  74229. * @param {number} radius the radius of the updraft
  74230. * @param {number} strength the strength of the updraft
  74231. * @param {number} height the height of the updraft
  74232. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74233. */
  74234. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74235. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74236. if (!this._physicsEngine) {
  74237. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74238. return null;
  74239. }
  74240. if (this._physicsEngine.getImpostors().length === 0) {
  74241. return null;
  74242. }
  74243. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74244. event.dispose(false);
  74245. return event;
  74246. };
  74247. /**
  74248. * @param {Vector3} origin the of the vortex
  74249. * @param {number} radius the radius of the vortex
  74250. * @param {number} strength the strength of the vortex
  74251. * @param {number} height the height of the vortex
  74252. */
  74253. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74254. if (!this._physicsEngine) {
  74255. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74256. return null;
  74257. }
  74258. if (this._physicsEngine.getImpostors().length === 0) {
  74259. return null;
  74260. }
  74261. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74262. event.dispose(false);
  74263. return event;
  74264. };
  74265. return PhysicsHelper;
  74266. }());
  74267. BABYLON.PhysicsHelper = PhysicsHelper;
  74268. /***** Radial explosion *****/
  74269. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74270. function PhysicsRadialExplosionEvent(scene) {
  74271. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74272. this._rays = [];
  74273. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74274. this._scene = scene;
  74275. }
  74276. /**
  74277. * Returns the data related to the radial explosion event (sphere & rays).
  74278. * @returns {PhysicsRadialExplosionEventData}
  74279. */
  74280. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74281. this._dataFetched = true;
  74282. return {
  74283. sphere: this._sphere,
  74284. rays: this._rays,
  74285. };
  74286. };
  74287. /**
  74288. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74289. * @param impostor
  74290. * @param {Vector3} origin the origin of the explosion
  74291. * @param {number} radius the explosion radius
  74292. * @param {number} strength the explosion strength
  74293. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74294. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74295. */
  74296. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74297. if (impostor.mass === 0) {
  74298. return null;
  74299. }
  74300. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74301. return null;
  74302. }
  74303. if (impostor.object.getClassName() !== 'Mesh') {
  74304. return null;
  74305. }
  74306. var impostorObject = impostor.object;
  74307. var impostorObjectCenter = impostor.getObjectCenter();
  74308. var direction = impostorObjectCenter.subtract(origin);
  74309. var ray = new BABYLON.Ray(origin, direction, radius);
  74310. this._rays.push(ray);
  74311. var hit = ray.intersectsMesh(impostorObject);
  74312. var contactPoint = hit.pickedPoint;
  74313. if (!contactPoint) {
  74314. return null;
  74315. }
  74316. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74317. if (distanceFromOrigin > radius) {
  74318. return null;
  74319. }
  74320. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74321. ? strength
  74322. : strength * (1 - (distanceFromOrigin / radius));
  74323. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74324. return { force: force, contactPoint: contactPoint };
  74325. };
  74326. /**
  74327. * Disposes the sphere.
  74328. * @param {bolean} force
  74329. */
  74330. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74331. var _this = this;
  74332. if (force === void 0) { force = true; }
  74333. if (force) {
  74334. this._sphere.dispose();
  74335. }
  74336. else {
  74337. setTimeout(function () {
  74338. if (!_this._dataFetched) {
  74339. _this._sphere.dispose();
  74340. }
  74341. }, 0);
  74342. }
  74343. };
  74344. /*** Helpers ***/
  74345. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74346. if (!this._sphere) {
  74347. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74348. this._sphere.isVisible = false;
  74349. }
  74350. };
  74351. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74352. var impostorObject = impostor.object;
  74353. this._prepareSphere();
  74354. this._sphere.position = origin;
  74355. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74356. this._sphere._updateBoundingInfo();
  74357. this._sphere.computeWorldMatrix(true);
  74358. return this._sphere.intersectsMesh(impostorObject, true);
  74359. };
  74360. return PhysicsRadialExplosionEvent;
  74361. }());
  74362. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74363. /***** Gravitational Field *****/
  74364. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74365. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74366. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74367. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74368. this._physicsHelper = physicsHelper;
  74369. this._scene = scene;
  74370. this._origin = origin;
  74371. this._radius = radius;
  74372. this._strength = strength;
  74373. this._falloff = falloff;
  74374. this._tickCallback = this._tick.bind(this);
  74375. }
  74376. /**
  74377. * Returns the data related to the gravitational field event (sphere).
  74378. * @returns {PhysicsGravitationalFieldEventData}
  74379. */
  74380. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74381. this._dataFetched = true;
  74382. return {
  74383. sphere: this._sphere,
  74384. };
  74385. };
  74386. /**
  74387. * Enables the gravitational field.
  74388. */
  74389. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74390. this._tickCallback.call(this);
  74391. this._scene.registerBeforeRender(this._tickCallback);
  74392. };
  74393. /**
  74394. * Disables the gravitational field.
  74395. */
  74396. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74397. this._scene.unregisterBeforeRender(this._tickCallback);
  74398. };
  74399. /**
  74400. * Disposes the sphere.
  74401. * @param {bolean} force
  74402. */
  74403. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74404. var _this = this;
  74405. if (force === void 0) { force = true; }
  74406. if (force) {
  74407. this._sphere.dispose();
  74408. }
  74409. else {
  74410. setTimeout(function () {
  74411. if (!_this._dataFetched) {
  74412. _this._sphere.dispose();
  74413. }
  74414. }, 0);
  74415. }
  74416. };
  74417. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74418. // Since the params won't change, we fetch the event only once
  74419. if (this._sphere) {
  74420. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74421. }
  74422. else {
  74423. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74424. if (radialExplosionEvent) {
  74425. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74426. }
  74427. }
  74428. };
  74429. return PhysicsGravitationalFieldEvent;
  74430. }());
  74431. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74432. /***** Updraft *****/
  74433. var PhysicsUpdraftEvent = /** @class */ (function () {
  74434. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74435. this._scene = _scene;
  74436. this._origin = _origin;
  74437. this._radius = _radius;
  74438. this._strength = _strength;
  74439. this._height = _height;
  74440. this._updraftMode = _updraftMode;
  74441. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74442. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74443. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74444. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74445. this._physicsEngine = this._scene.getPhysicsEngine();
  74446. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74447. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74448. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74449. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74450. }
  74451. this._tickCallback = this._tick.bind(this);
  74452. }
  74453. /**
  74454. * Returns the data related to the updraft event (cylinder).
  74455. * @returns {PhysicsUpdraftEventData}
  74456. */
  74457. PhysicsUpdraftEvent.prototype.getData = function () {
  74458. this._dataFetched = true;
  74459. return {
  74460. cylinder: this._cylinder,
  74461. };
  74462. };
  74463. /**
  74464. * Enables the updraft.
  74465. */
  74466. PhysicsUpdraftEvent.prototype.enable = function () {
  74467. this._tickCallback.call(this);
  74468. this._scene.registerBeforeRender(this._tickCallback);
  74469. };
  74470. /**
  74471. * Disables the cortex.
  74472. */
  74473. PhysicsUpdraftEvent.prototype.disable = function () {
  74474. this._scene.unregisterBeforeRender(this._tickCallback);
  74475. };
  74476. /**
  74477. * Disposes the sphere.
  74478. * @param {bolean} force
  74479. */
  74480. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74481. var _this = this;
  74482. if (force === void 0) { force = true; }
  74483. if (force) {
  74484. this._cylinder.dispose();
  74485. }
  74486. else {
  74487. setTimeout(function () {
  74488. if (!_this._dataFetched) {
  74489. _this._cylinder.dispose();
  74490. }
  74491. }, 0);
  74492. }
  74493. };
  74494. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74495. if (impostor.mass === 0) {
  74496. return null;
  74497. }
  74498. if (!this._intersectsWithCylinder(impostor)) {
  74499. return null;
  74500. }
  74501. var impostorObjectCenter = impostor.getObjectCenter();
  74502. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74503. var direction = this._originDirection;
  74504. }
  74505. else {
  74506. var direction = impostorObjectCenter.subtract(this._originTop);
  74507. }
  74508. var multiplier = this._strength * -1;
  74509. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74510. return { force: force, contactPoint: impostorObjectCenter };
  74511. };
  74512. PhysicsUpdraftEvent.prototype._tick = function () {
  74513. var _this = this;
  74514. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74515. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74516. if (!impostorForceAndContactPoint) {
  74517. return;
  74518. }
  74519. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74520. });
  74521. };
  74522. /*** Helpers ***/
  74523. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74524. if (!this._cylinder) {
  74525. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74526. height: this._height,
  74527. diameter: this._radius * 2,
  74528. }, this._scene);
  74529. this._cylinder.isVisible = false;
  74530. }
  74531. };
  74532. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74533. var impostorObject = impostor.object;
  74534. this._prepareCylinder();
  74535. this._cylinder.position = this._cylinderPosition;
  74536. return this._cylinder.intersectsMesh(impostorObject, true);
  74537. };
  74538. return PhysicsUpdraftEvent;
  74539. }());
  74540. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74541. /***** Vortex *****/
  74542. var PhysicsVortexEvent = /** @class */ (function () {
  74543. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74544. this._scene = _scene;
  74545. this._origin = _origin;
  74546. this._radius = _radius;
  74547. this._strength = _strength;
  74548. this._height = _height;
  74549. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74550. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74551. this._updraftMultiplier = 0.02;
  74552. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74553. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74554. this._physicsEngine = this._scene.getPhysicsEngine();
  74555. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74556. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74557. this._tickCallback = this._tick.bind(this);
  74558. }
  74559. /**
  74560. * Returns the data related to the vortex event (cylinder).
  74561. * @returns {PhysicsVortexEventData}
  74562. */
  74563. PhysicsVortexEvent.prototype.getData = function () {
  74564. this._dataFetched = true;
  74565. return {
  74566. cylinder: this._cylinder,
  74567. };
  74568. };
  74569. /**
  74570. * Enables the vortex.
  74571. */
  74572. PhysicsVortexEvent.prototype.enable = function () {
  74573. this._tickCallback.call(this);
  74574. this._scene.registerBeforeRender(this._tickCallback);
  74575. };
  74576. /**
  74577. * Disables the cortex.
  74578. */
  74579. PhysicsVortexEvent.prototype.disable = function () {
  74580. this._scene.unregisterBeforeRender(this._tickCallback);
  74581. };
  74582. /**
  74583. * Disposes the sphere.
  74584. * @param {bolean} force
  74585. */
  74586. PhysicsVortexEvent.prototype.dispose = function (force) {
  74587. var _this = this;
  74588. if (force === void 0) { force = true; }
  74589. if (force) {
  74590. this._cylinder.dispose();
  74591. }
  74592. else {
  74593. setTimeout(function () {
  74594. if (!_this._dataFetched) {
  74595. _this._cylinder.dispose();
  74596. }
  74597. }, 0);
  74598. }
  74599. };
  74600. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74601. if (impostor.mass === 0) {
  74602. return null;
  74603. }
  74604. if (!this._intersectsWithCylinder(impostor)) {
  74605. return null;
  74606. }
  74607. if (impostor.object.getClassName() !== 'Mesh') {
  74608. return null;
  74609. }
  74610. var impostorObject = impostor.object;
  74611. var impostorObjectCenter = impostor.getObjectCenter();
  74612. 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)
  74613. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74614. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74615. var hit = ray.intersectsMesh(impostorObject);
  74616. var contactPoint = hit.pickedPoint;
  74617. if (!contactPoint) {
  74618. return null;
  74619. }
  74620. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74621. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74622. var directionToOrigin = contactPoint.normalize();
  74623. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74624. directionToOrigin = directionToOrigin.negate();
  74625. }
  74626. // TODO: find a more physically based solution
  74627. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74628. var forceX = directionToOrigin.x * this._strength / 8;
  74629. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74630. var forceZ = directionToOrigin.z * this._strength / 8;
  74631. }
  74632. else {
  74633. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74634. var forceY = this._originTop.y * this._updraftMultiplier;
  74635. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74636. }
  74637. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74638. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74639. return { force: force, contactPoint: impostorObjectCenter };
  74640. };
  74641. PhysicsVortexEvent.prototype._tick = function () {
  74642. var _this = this;
  74643. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74644. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74645. if (!impostorForceAndContactPoint) {
  74646. return;
  74647. }
  74648. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74649. });
  74650. };
  74651. /*** Helpers ***/
  74652. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74653. if (!this._cylinder) {
  74654. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74655. height: this._height,
  74656. diameter: this._radius * 2,
  74657. }, this._scene);
  74658. this._cylinder.isVisible = false;
  74659. }
  74660. };
  74661. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74662. var impostorObject = impostor.object;
  74663. this._prepareCylinder();
  74664. this._cylinder.position = this._cylinderPosition;
  74665. return this._cylinder.intersectsMesh(impostorObject, true);
  74666. };
  74667. return PhysicsVortexEvent;
  74668. }());
  74669. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74670. /***** Enums *****/
  74671. /**
  74672. * The strenght of the force in correspondence to the distance of the affected object
  74673. */
  74674. var PhysicsRadialImpulseFalloff;
  74675. (function (PhysicsRadialImpulseFalloff) {
  74676. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74677. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74678. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74679. /**
  74680. * The strenght of the force in correspondence to the distance of the affected object
  74681. */
  74682. var PhysicsUpdraftMode;
  74683. (function (PhysicsUpdraftMode) {
  74684. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74685. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74686. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74687. })(BABYLON || (BABYLON = {}));
  74688. //# sourceMappingURL=babylon.physicsHelper.js.map
  74689. var BABYLON;
  74690. (function (BABYLON) {
  74691. var CannonJSPlugin = /** @class */ (function () {
  74692. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74693. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74694. if (iterations === void 0) { iterations = 10; }
  74695. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74696. this.name = "CannonJSPlugin";
  74697. this._physicsMaterials = new Array();
  74698. this._fixedTimeStep = 1 / 60;
  74699. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74700. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74701. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74702. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74703. this._tmpPosition = BABYLON.Vector3.Zero();
  74704. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74705. this._tmpUnityRotation = new BABYLON.Quaternion();
  74706. if (!this.isSupported()) {
  74707. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74708. return;
  74709. }
  74710. this._extendNamespace();
  74711. this.world = new this.BJSCANNON.World();
  74712. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74713. this.world.solver.iterations = iterations;
  74714. }
  74715. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74716. this.world.gravity.copy(gravity);
  74717. };
  74718. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74719. this._fixedTimeStep = timeStep;
  74720. };
  74721. CannonJSPlugin.prototype.getTimeStep = function () {
  74722. return this._fixedTimeStep;
  74723. };
  74724. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74725. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74726. };
  74727. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74728. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74729. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74730. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74731. };
  74732. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74733. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74734. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74735. impostor.physicsBody.applyForce(impulse, worldPoint);
  74736. };
  74737. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74738. //parent-child relationship. Does this impostor has a parent impostor?
  74739. if (impostor.parent) {
  74740. if (impostor.physicsBody) {
  74741. this.removePhysicsBody(impostor);
  74742. //TODO is that needed?
  74743. impostor.forceUpdate();
  74744. }
  74745. return;
  74746. }
  74747. //should a new body be created for this impostor?
  74748. if (impostor.isBodyInitRequired()) {
  74749. var shape = this._createShape(impostor);
  74750. //unregister events, if body is being changed
  74751. var oldBody = impostor.physicsBody;
  74752. if (oldBody) {
  74753. this.removePhysicsBody(impostor);
  74754. }
  74755. //create the body and material
  74756. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74757. var bodyCreationObject = {
  74758. mass: impostor.getParam("mass"),
  74759. material: material
  74760. };
  74761. // A simple extend, in case native options were used.
  74762. var nativeOptions = impostor.getParam("nativeOptions");
  74763. for (var key in nativeOptions) {
  74764. if (nativeOptions.hasOwnProperty(key)) {
  74765. bodyCreationObject[key] = nativeOptions[key];
  74766. }
  74767. }
  74768. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74769. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74770. this.world.addEventListener("preStep", impostor.beforeStep);
  74771. this.world.addEventListener("postStep", impostor.afterStep);
  74772. impostor.physicsBody.addShape(shape);
  74773. this.world.add(impostor.physicsBody);
  74774. //try to keep the body moving in the right direction by taking old properties.
  74775. //Should be tested!
  74776. if (oldBody) {
  74777. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74778. impostor.physicsBody[param].copy(oldBody[param]);
  74779. });
  74780. }
  74781. this._processChildMeshes(impostor);
  74782. }
  74783. //now update the body's transformation
  74784. this._updatePhysicsBodyTransformation(impostor);
  74785. };
  74786. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74787. var _this = this;
  74788. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74789. var currentRotation = mainImpostor.object.rotationQuaternion;
  74790. if (meshChildren.length) {
  74791. var processMesh = function (localPosition, mesh) {
  74792. if (!currentRotation || !mesh.rotationQuaternion) {
  74793. return;
  74794. }
  74795. var childImpostor = mesh.getPhysicsImpostor();
  74796. if (childImpostor) {
  74797. var parent = childImpostor.parent;
  74798. if (parent !== mainImpostor) {
  74799. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74800. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74801. if (childImpostor.physicsBody) {
  74802. _this.removePhysicsBody(childImpostor);
  74803. childImpostor.physicsBody = null;
  74804. }
  74805. childImpostor.parent = mainImpostor;
  74806. childImpostor.resetUpdateFlags();
  74807. 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));
  74808. //Add the mass of the children.
  74809. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74810. }
  74811. }
  74812. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74813. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74814. };
  74815. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74816. }
  74817. };
  74818. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74819. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74820. this.world.removeEventListener("preStep", impostor.beforeStep);
  74821. this.world.removeEventListener("postStep", impostor.afterStep);
  74822. this.world.remove(impostor.physicsBody);
  74823. };
  74824. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74825. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74826. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74827. if (!mainBody || !connectedBody) {
  74828. return;
  74829. }
  74830. var constraint;
  74831. var jointData = impostorJoint.joint.jointData;
  74832. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74833. var constraintData = {
  74834. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74835. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74836. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74837. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74838. maxForce: jointData.nativeParams.maxForce,
  74839. collideConnected: !!jointData.collision
  74840. };
  74841. switch (impostorJoint.joint.type) {
  74842. case BABYLON.PhysicsJoint.HingeJoint:
  74843. case BABYLON.PhysicsJoint.Hinge2Joint:
  74844. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74845. break;
  74846. case BABYLON.PhysicsJoint.DistanceJoint:
  74847. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74848. break;
  74849. case BABYLON.PhysicsJoint.SpringJoint:
  74850. var springData = jointData;
  74851. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74852. restLength: springData.length,
  74853. stiffness: springData.stiffness,
  74854. damping: springData.damping,
  74855. localAnchorA: constraintData.pivotA,
  74856. localAnchorB: constraintData.pivotB
  74857. });
  74858. break;
  74859. case BABYLON.PhysicsJoint.LockJoint:
  74860. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74861. break;
  74862. case BABYLON.PhysicsJoint.PointToPointJoint:
  74863. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74864. default:
  74865. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74866. break;
  74867. }
  74868. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74869. constraint.collideConnected = !!jointData.collision;
  74870. impostorJoint.joint.physicsJoint = constraint;
  74871. //don't add spring as constraint, as it is not one.
  74872. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74873. this.world.addConstraint(constraint);
  74874. }
  74875. else {
  74876. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74877. constraint.applyForce();
  74878. });
  74879. }
  74880. };
  74881. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74882. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74883. };
  74884. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74885. var index;
  74886. var mat;
  74887. for (index = 0; index < this._physicsMaterials.length; index++) {
  74888. mat = this._physicsMaterials[index];
  74889. if (mat.friction === friction && mat.restitution === restitution) {
  74890. return mat;
  74891. }
  74892. }
  74893. var currentMat = new this.BJSCANNON.Material(name);
  74894. currentMat.friction = friction;
  74895. currentMat.restitution = restitution;
  74896. this._physicsMaterials.push(currentMat);
  74897. return currentMat;
  74898. };
  74899. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74900. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74901. };
  74902. CannonJSPlugin.prototype._createShape = function (impostor) {
  74903. var object = impostor.object;
  74904. var returnValue;
  74905. var extendSize = impostor.getObjectExtendSize();
  74906. switch (impostor.type) {
  74907. case BABYLON.PhysicsImpostor.SphereImpostor:
  74908. var radiusX = extendSize.x;
  74909. var radiusY = extendSize.y;
  74910. var radiusZ = extendSize.z;
  74911. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74912. break;
  74913. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74914. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74915. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74916. break;
  74917. case BABYLON.PhysicsImpostor.BoxImpostor:
  74918. var box = extendSize.scale(0.5);
  74919. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74920. break;
  74921. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74922. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74923. returnValue = new this.BJSCANNON.Plane();
  74924. break;
  74925. case BABYLON.PhysicsImpostor.MeshImpostor:
  74926. // should transform the vertex data to world coordinates!!
  74927. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74928. var rawFaces = object.getIndices ? object.getIndices() : [];
  74929. if (!rawVerts)
  74930. return;
  74931. // get only scale! so the object could transform correctly.
  74932. var oldPosition = object.position.clone();
  74933. var oldRotation = object.rotation && object.rotation.clone();
  74934. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74935. object.position.copyFromFloats(0, 0, 0);
  74936. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74937. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74938. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74939. var transform = object.computeWorldMatrix(true);
  74940. // convert rawVerts to object space
  74941. var temp = new Array();
  74942. var index;
  74943. for (index = 0; index < rawVerts.length; index += 3) {
  74944. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74945. }
  74946. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74947. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74948. //now set back the transformation!
  74949. object.position.copyFrom(oldPosition);
  74950. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74951. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74952. break;
  74953. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74954. var oldPosition2 = object.position.clone();
  74955. var oldRotation2 = object.rotation && object.rotation.clone();
  74956. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74957. object.position.copyFromFloats(0, 0, 0);
  74958. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74959. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74960. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74961. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74962. returnValue = this._createHeightmap(object);
  74963. object.position.copyFrom(oldPosition2);
  74964. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74965. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74966. object.computeWorldMatrix(true);
  74967. break;
  74968. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74969. returnValue = new this.BJSCANNON.Particle();
  74970. break;
  74971. }
  74972. return returnValue;
  74973. };
  74974. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74975. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74976. var transform = object.computeWorldMatrix(true);
  74977. // convert rawVerts to object space
  74978. var temp = new Array();
  74979. var index;
  74980. for (index = 0; index < pos.length; index += 3) {
  74981. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74982. }
  74983. pos = temp;
  74984. var matrix = new Array();
  74985. //For now pointDepth will not be used and will be automatically calculated.
  74986. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74987. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74988. var boundingInfo = object.getBoundingInfo();
  74989. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74990. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74991. var elementSize = dim * 2 / arraySize;
  74992. for (var i = 0; i < pos.length; i = i + 3) {
  74993. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74994. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74995. var y = -pos[i + 2] + minY;
  74996. if (!matrix[x]) {
  74997. matrix[x] = [];
  74998. }
  74999. if (!matrix[x][z]) {
  75000. matrix[x][z] = y;
  75001. }
  75002. matrix[x][z] = Math.max(y, matrix[x][z]);
  75003. }
  75004. for (var x = 0; x <= arraySize; ++x) {
  75005. if (!matrix[x]) {
  75006. var loc = 1;
  75007. while (!matrix[(x + loc) % arraySize]) {
  75008. loc++;
  75009. }
  75010. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75011. //console.log("missing x", x);
  75012. }
  75013. for (var z = 0; z <= arraySize; ++z) {
  75014. if (!matrix[x][z]) {
  75015. var loc = 1;
  75016. var newValue;
  75017. while (newValue === undefined) {
  75018. newValue = matrix[x][(z + loc++) % arraySize];
  75019. }
  75020. matrix[x][z] = newValue;
  75021. }
  75022. }
  75023. }
  75024. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75025. elementSize: elementSize
  75026. });
  75027. //For future reference, needed for body transformation
  75028. shape.minY = minY;
  75029. return shape;
  75030. };
  75031. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75032. var object = impostor.object;
  75033. //make sure it is updated...
  75034. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75035. // The delta between the mesh position and the mesh bounding box center
  75036. var bInfo = object.getBoundingInfo();
  75037. if (!bInfo)
  75038. return;
  75039. var center = impostor.getObjectCenter();
  75040. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75041. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75042. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75043. this._tmpPosition.copyFrom(center);
  75044. var quaternion = object.rotationQuaternion;
  75045. if (!quaternion) {
  75046. return;
  75047. }
  75048. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75049. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75050. //-90 DEG in X, precalculated
  75051. quaternion = quaternion.multiply(this._minus90X);
  75052. //Invert! (Precalculated, 90 deg in X)
  75053. //No need to clone. this will never change.
  75054. impostor.setDeltaRotation(this._plus90X);
  75055. }
  75056. //If it is a heightfield, if should be centered.
  75057. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75058. var mesh = object;
  75059. var boundingInfo = mesh.getBoundingInfo();
  75060. //calculate the correct body position:
  75061. var rotationQuaternion = mesh.rotationQuaternion;
  75062. mesh.rotationQuaternion = this._tmpUnityRotation;
  75063. mesh.computeWorldMatrix(true);
  75064. //get original center with no rotation
  75065. var c = center.clone();
  75066. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75067. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75068. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75069. mesh.setPreTransformMatrix(p);
  75070. mesh.computeWorldMatrix(true);
  75071. //calculate the translation
  75072. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75073. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75074. //add it inverted to the delta
  75075. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75076. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75077. //rotation is back
  75078. mesh.rotationQuaternion = rotationQuaternion;
  75079. mesh.setPreTransformMatrix(oldPivot);
  75080. mesh.computeWorldMatrix(true);
  75081. }
  75082. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75083. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75084. //this._tmpPosition.copyFrom(object.position);
  75085. }
  75086. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75087. //Now update the impostor object
  75088. impostor.physicsBody.position.copy(this._tmpPosition);
  75089. impostor.physicsBody.quaternion.copy(quaternion);
  75090. };
  75091. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75092. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75093. if (impostor.object.rotationQuaternion) {
  75094. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75095. }
  75096. };
  75097. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75098. impostor.physicsBody.position.copy(newPosition);
  75099. impostor.physicsBody.quaternion.copy(newRotation);
  75100. };
  75101. CannonJSPlugin.prototype.isSupported = function () {
  75102. return this.BJSCANNON !== undefined;
  75103. };
  75104. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75105. impostor.physicsBody.velocity.copy(velocity);
  75106. };
  75107. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75108. impostor.physicsBody.angularVelocity.copy(velocity);
  75109. };
  75110. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75111. var v = impostor.physicsBody.velocity;
  75112. if (!v) {
  75113. return null;
  75114. }
  75115. return new BABYLON.Vector3(v.x, v.y, v.z);
  75116. };
  75117. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75118. var v = impostor.physicsBody.angularVelocity;
  75119. if (!v) {
  75120. return null;
  75121. }
  75122. return new BABYLON.Vector3(v.x, v.y, v.z);
  75123. };
  75124. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75125. impostor.physicsBody.mass = mass;
  75126. impostor.physicsBody.updateMassProperties();
  75127. };
  75128. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75129. return impostor.physicsBody.mass;
  75130. };
  75131. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75132. return impostor.physicsBody.material.friction;
  75133. };
  75134. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75135. impostor.physicsBody.material.friction = friction;
  75136. };
  75137. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75138. return impostor.physicsBody.material.restitution;
  75139. };
  75140. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75141. impostor.physicsBody.material.restitution = restitution;
  75142. };
  75143. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75144. impostor.physicsBody.sleep();
  75145. };
  75146. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75147. impostor.physicsBody.wakeUp();
  75148. };
  75149. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75150. joint.physicsJoint.distance = maxDistance;
  75151. };
  75152. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75153. // if (!motorIndex) {
  75154. // joint.physicsJoint.enableMotor();
  75155. // }
  75156. // }
  75157. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75158. // if (!motorIndex) {
  75159. // joint.physicsJoint.disableMotor();
  75160. // }
  75161. // }
  75162. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75163. if (!motorIndex) {
  75164. joint.physicsJoint.enableMotor();
  75165. joint.physicsJoint.setMotorSpeed(speed);
  75166. if (maxForce) {
  75167. this.setLimit(joint, maxForce);
  75168. }
  75169. }
  75170. };
  75171. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75172. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75173. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75174. };
  75175. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75176. var body = impostor.physicsBody;
  75177. mesh.position.x = body.position.x;
  75178. mesh.position.y = body.position.y;
  75179. mesh.position.z = body.position.z;
  75180. if (mesh.rotationQuaternion) {
  75181. mesh.rotationQuaternion.x = body.quaternion.x;
  75182. mesh.rotationQuaternion.y = body.quaternion.y;
  75183. mesh.rotationQuaternion.z = body.quaternion.z;
  75184. mesh.rotationQuaternion.w = body.quaternion.w;
  75185. }
  75186. };
  75187. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75188. var shape = impostor.physicsBody.shapes[0];
  75189. return shape.boundingSphereRadius;
  75190. };
  75191. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75192. var shape = impostor.physicsBody.shapes[0];
  75193. result.x = shape.halfExtents.x * 2;
  75194. result.y = shape.halfExtents.y * 2;
  75195. result.z = shape.halfExtents.z * 2;
  75196. };
  75197. CannonJSPlugin.prototype.dispose = function () {
  75198. };
  75199. CannonJSPlugin.prototype._extendNamespace = function () {
  75200. //this will force cannon to execute at least one step when using interpolation
  75201. var step_tmp1 = new this.BJSCANNON.Vec3();
  75202. var Engine = this.BJSCANNON;
  75203. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75204. maxSubSteps = maxSubSteps || 10;
  75205. timeSinceLastCalled = timeSinceLastCalled || 0;
  75206. if (timeSinceLastCalled === 0) {
  75207. this.internalStep(dt);
  75208. this.time += dt;
  75209. }
  75210. else {
  75211. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75212. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75213. var t0 = performance.now();
  75214. for (var i = 0; i !== internalSteps; i++) {
  75215. this.internalStep(dt);
  75216. if (performance.now() - t0 > dt * 1000) {
  75217. break;
  75218. }
  75219. }
  75220. this.time += timeSinceLastCalled;
  75221. var h = this.time % dt;
  75222. var h_div_dt = h / dt;
  75223. var interpvelo = step_tmp1;
  75224. var bodies = this.bodies;
  75225. for (var j = 0; j !== bodies.length; j++) {
  75226. var b = bodies[j];
  75227. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75228. b.position.vsub(b.previousPosition, interpvelo);
  75229. interpvelo.scale(h_div_dt, interpvelo);
  75230. b.position.vadd(interpvelo, b.interpolatedPosition);
  75231. }
  75232. else {
  75233. b.interpolatedPosition.copy(b.position);
  75234. b.interpolatedQuaternion.copy(b.quaternion);
  75235. }
  75236. }
  75237. }
  75238. };
  75239. };
  75240. return CannonJSPlugin;
  75241. }());
  75242. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75243. })(BABYLON || (BABYLON = {}));
  75244. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75245. var BABYLON;
  75246. (function (BABYLON) {
  75247. var OimoJSPlugin = /** @class */ (function () {
  75248. function OimoJSPlugin(iterations) {
  75249. this.name = "OimoJSPlugin";
  75250. this._tmpImpostorsArray = [];
  75251. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75252. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75253. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75254. this.world.worldscale(1);
  75255. this.world.clear();
  75256. //making sure no stats are calculated
  75257. this.world.isNoStat = true;
  75258. }
  75259. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75260. this.world.gravity.copy(gravity);
  75261. };
  75262. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75263. this.world.timeStep = timeStep;
  75264. };
  75265. OimoJSPlugin.prototype.getTimeStep = function () {
  75266. return this.world.timeStep;
  75267. };
  75268. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75269. var _this = this;
  75270. impostors.forEach(function (impostor) {
  75271. impostor.beforeStep();
  75272. });
  75273. this.world.step();
  75274. impostors.forEach(function (impostor) {
  75275. impostor.afterStep();
  75276. //update the ordered impostors array
  75277. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75278. });
  75279. //check for collisions
  75280. var contact = this.world.contacts;
  75281. while (contact !== null) {
  75282. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75283. contact = contact.next;
  75284. continue;
  75285. }
  75286. //is this body colliding with any other? get the impostor
  75287. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75288. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75289. if (!mainImpostor || !collidingImpostor) {
  75290. contact = contact.next;
  75291. continue;
  75292. }
  75293. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75294. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75295. contact = contact.next;
  75296. }
  75297. };
  75298. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75299. var mass = impostor.physicsBody.massInfo.mass;
  75300. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75301. };
  75302. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75303. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75304. this.applyImpulse(impostor, force, contactPoint);
  75305. };
  75306. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75307. var _this = this;
  75308. //parent-child relationship. Does this impostor has a parent impostor?
  75309. if (impostor.parent) {
  75310. if (impostor.physicsBody) {
  75311. this.removePhysicsBody(impostor);
  75312. //TODO is that needed?
  75313. impostor.forceUpdate();
  75314. }
  75315. return;
  75316. }
  75317. if (impostor.isBodyInitRequired()) {
  75318. var bodyConfig = {
  75319. name: impostor.uniqueId,
  75320. //Oimo must have mass, also for static objects.
  75321. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75322. size: [],
  75323. type: [],
  75324. pos: [],
  75325. rot: [],
  75326. move: impostor.getParam("mass") !== 0,
  75327. //Supporting older versions of Oimo
  75328. world: this.world
  75329. };
  75330. var impostors = [impostor];
  75331. var addToArray = function (parent) {
  75332. if (!parent.getChildMeshes)
  75333. return;
  75334. parent.getChildMeshes().forEach(function (m) {
  75335. if (m.physicsImpostor) {
  75336. impostors.push(m.physicsImpostor);
  75337. //m.physicsImpostor._init();
  75338. }
  75339. });
  75340. };
  75341. addToArray(impostor.object);
  75342. var checkWithEpsilon_1 = function (value) {
  75343. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75344. };
  75345. impostors.forEach(function (i) {
  75346. if (!impostor.object.rotationQuaternion) {
  75347. return;
  75348. }
  75349. //get the correct bounding box
  75350. var oldQuaternion = i.object.rotationQuaternion;
  75351. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75352. x: impostor.object.rotationQuaternion.x,
  75353. y: impostor.object.rotationQuaternion.y,
  75354. z: impostor.object.rotationQuaternion.z,
  75355. s: impostor.object.rotationQuaternion.w
  75356. });
  75357. var extendSize = i.getObjectExtendSize();
  75358. if (i === impostor) {
  75359. var center = impostor.getObjectCenter();
  75360. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75361. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75362. //Can also use Array.prototype.push.apply
  75363. bodyConfig.pos.push(center.x);
  75364. bodyConfig.pos.push(center.y);
  75365. bodyConfig.pos.push(center.z);
  75366. //tmp solution
  75367. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75368. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75369. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75370. }
  75371. else {
  75372. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75373. bodyConfig.pos.push(localPosition.x);
  75374. bodyConfig.pos.push(localPosition.y);
  75375. bodyConfig.pos.push(localPosition.z);
  75376. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75377. bodyConfig.rot.push(0);
  75378. bodyConfig.rot.push(0);
  75379. bodyConfig.rot.push(0);
  75380. }
  75381. // register mesh
  75382. switch (i.type) {
  75383. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75384. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75385. case BABYLON.PhysicsImpostor.SphereImpostor:
  75386. var radiusX = extendSize.x;
  75387. var radiusY = extendSize.y;
  75388. var radiusZ = extendSize.z;
  75389. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75390. bodyConfig.type.push('sphere');
  75391. //due to the way oimo works with compounds, add 3 times
  75392. bodyConfig.size.push(size);
  75393. bodyConfig.size.push(size);
  75394. bodyConfig.size.push(size);
  75395. break;
  75396. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75397. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75398. var sizeY = checkWithEpsilon_1(extendSize.y);
  75399. bodyConfig.type.push('cylinder');
  75400. bodyConfig.size.push(sizeX);
  75401. bodyConfig.size.push(sizeY);
  75402. //due to the way oimo works with compounds, add one more value.
  75403. bodyConfig.size.push(sizeY);
  75404. break;
  75405. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75406. case BABYLON.PhysicsImpostor.BoxImpostor:
  75407. default:
  75408. var sizeX = checkWithEpsilon_1(extendSize.x);
  75409. var sizeY = checkWithEpsilon_1(extendSize.y);
  75410. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75411. bodyConfig.type.push('box');
  75412. bodyConfig.size.push(sizeX);
  75413. bodyConfig.size.push(sizeY);
  75414. bodyConfig.size.push(sizeZ);
  75415. break;
  75416. }
  75417. //actually not needed, but hey...
  75418. i.object.rotationQuaternion = oldQuaternion;
  75419. });
  75420. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75421. }
  75422. else {
  75423. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75424. }
  75425. impostor.setDeltaPosition(this._tmpPositionVector);
  75426. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75427. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75428. };
  75429. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75430. //impostor.physicsBody.dispose();
  75431. //Same as : (older oimo versions)
  75432. this.world.removeRigidBody(impostor.physicsBody);
  75433. };
  75434. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75435. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75436. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75437. if (!mainBody || !connectedBody) {
  75438. return;
  75439. }
  75440. var jointData = impostorJoint.joint.jointData;
  75441. var options = jointData.nativeParams || {};
  75442. var type;
  75443. var nativeJointData = {
  75444. body1: mainBody,
  75445. body2: connectedBody,
  75446. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75447. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75448. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75449. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75450. min: options.min,
  75451. max: options.max,
  75452. collision: options.collision || jointData.collision,
  75453. spring: options.spring,
  75454. //supporting older version of Oimo
  75455. world: this.world
  75456. };
  75457. switch (impostorJoint.joint.type) {
  75458. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75459. type = "jointBall";
  75460. break;
  75461. case BABYLON.PhysicsJoint.SpringJoint:
  75462. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75463. var springData = jointData;
  75464. nativeJointData.min = springData.length || nativeJointData.min;
  75465. //Max should also be set, just make sure it is at least min
  75466. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75467. case BABYLON.PhysicsJoint.DistanceJoint:
  75468. type = "jointDistance";
  75469. nativeJointData.max = jointData.maxDistance;
  75470. break;
  75471. case BABYLON.PhysicsJoint.PrismaticJoint:
  75472. type = "jointPrisme";
  75473. break;
  75474. case BABYLON.PhysicsJoint.SliderJoint:
  75475. type = "jointSlide";
  75476. break;
  75477. case BABYLON.PhysicsJoint.WheelJoint:
  75478. type = "jointWheel";
  75479. break;
  75480. case BABYLON.PhysicsJoint.HingeJoint:
  75481. default:
  75482. type = "jointHinge";
  75483. break;
  75484. }
  75485. nativeJointData.type = type;
  75486. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75487. };
  75488. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75489. //Bug in Oimo prevents us from disposing a joint in the playground
  75490. //joint.joint.physicsJoint.dispose();
  75491. //So we will bruteforce it!
  75492. try {
  75493. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75494. }
  75495. catch (e) {
  75496. BABYLON.Tools.Warn(e);
  75497. }
  75498. };
  75499. OimoJSPlugin.prototype.isSupported = function () {
  75500. return this.BJSOIMO !== undefined;
  75501. };
  75502. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75503. if (!impostor.physicsBody.sleeping) {
  75504. //TODO check that
  75505. if (impostor.physicsBody.shapes.next) {
  75506. var parentShape = this._getLastShape(impostor.physicsBody);
  75507. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75508. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75509. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75510. }
  75511. else {
  75512. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75513. }
  75514. if (impostor.object.rotationQuaternion) {
  75515. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75516. impostor.object.rotationQuaternion.normalize();
  75517. }
  75518. }
  75519. };
  75520. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75521. var body = impostor.physicsBody;
  75522. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75523. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75524. body.syncShapes();
  75525. body.awake();
  75526. };
  75527. OimoJSPlugin.prototype._getLastShape = function (body) {
  75528. var lastShape = body.shapes;
  75529. while (lastShape.next) {
  75530. lastShape = lastShape.next;
  75531. }
  75532. return lastShape;
  75533. };
  75534. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75535. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75536. };
  75537. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75538. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75539. };
  75540. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75541. var v = impostor.physicsBody.linearVelocity;
  75542. if (!v) {
  75543. return null;
  75544. }
  75545. return new BABYLON.Vector3(v.x, v.y, v.z);
  75546. };
  75547. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75548. var v = impostor.physicsBody.angularVelocity;
  75549. if (!v) {
  75550. return null;
  75551. }
  75552. return new BABYLON.Vector3(v.x, v.y, v.z);
  75553. };
  75554. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75555. var staticBody = mass === 0;
  75556. //this will actually set the body's density and not its mass.
  75557. //But this is how oimo treats the mass variable.
  75558. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75559. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75560. };
  75561. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75562. return impostor.physicsBody.shapes.density;
  75563. };
  75564. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75565. return impostor.physicsBody.shapes.friction;
  75566. };
  75567. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75568. impostor.physicsBody.shapes.friction = friction;
  75569. };
  75570. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75571. return impostor.physicsBody.shapes.restitution;
  75572. };
  75573. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75574. impostor.physicsBody.shapes.restitution = restitution;
  75575. };
  75576. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75577. impostor.physicsBody.sleep();
  75578. };
  75579. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75580. impostor.physicsBody.awake();
  75581. };
  75582. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75583. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75584. if (minDistance !== void 0) {
  75585. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75586. }
  75587. };
  75588. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75589. //TODO separate rotational and transational motors.
  75590. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75591. if (motor) {
  75592. motor.setMotor(speed, maxForce);
  75593. }
  75594. };
  75595. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75596. //TODO separate rotational and transational motors.
  75597. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75598. if (motor) {
  75599. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75600. }
  75601. };
  75602. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75603. var body = impostor.physicsBody;
  75604. mesh.position.x = body.position.x;
  75605. mesh.position.y = body.position.y;
  75606. mesh.position.z = body.position.z;
  75607. if (mesh.rotationQuaternion) {
  75608. mesh.rotationQuaternion.x = body.orientation.x;
  75609. mesh.rotationQuaternion.y = body.orientation.y;
  75610. mesh.rotationQuaternion.z = body.orientation.z;
  75611. mesh.rotationQuaternion.w = body.orientation.s;
  75612. }
  75613. };
  75614. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75615. return impostor.physicsBody.shapes.radius;
  75616. };
  75617. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75618. var shape = impostor.physicsBody.shapes;
  75619. result.x = shape.halfWidth * 2;
  75620. result.y = shape.halfHeight * 2;
  75621. result.z = shape.halfDepth * 2;
  75622. };
  75623. OimoJSPlugin.prototype.dispose = function () {
  75624. this.world.clear();
  75625. };
  75626. return OimoJSPlugin;
  75627. }());
  75628. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75629. })(BABYLON || (BABYLON = {}));
  75630. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75631. var BABYLON;
  75632. (function (BABYLON) {
  75633. /*
  75634. * Based on jsTGALoader - Javascript loader for TGA file
  75635. * By Vincent Thibault
  75636. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75637. */
  75638. var TGATools = /** @class */ (function () {
  75639. function TGATools() {
  75640. }
  75641. TGATools.GetTGAHeader = function (data) {
  75642. var offset = 0;
  75643. var header = {
  75644. id_length: data[offset++],
  75645. colormap_type: data[offset++],
  75646. image_type: data[offset++],
  75647. colormap_index: data[offset++] | data[offset++] << 8,
  75648. colormap_length: data[offset++] | data[offset++] << 8,
  75649. colormap_size: data[offset++],
  75650. origin: [
  75651. data[offset++] | data[offset++] << 8,
  75652. data[offset++] | data[offset++] << 8
  75653. ],
  75654. width: data[offset++] | data[offset++] << 8,
  75655. height: data[offset++] | data[offset++] << 8,
  75656. pixel_size: data[offset++],
  75657. flags: data[offset++]
  75658. };
  75659. return header;
  75660. };
  75661. TGATools.UploadContent = function (gl, data) {
  75662. // Not enough data to contain header ?
  75663. if (data.length < 19) {
  75664. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75665. return;
  75666. }
  75667. // Read Header
  75668. var offset = 18;
  75669. var header = TGATools.GetTGAHeader(data);
  75670. // Assume it's a valid Targa file.
  75671. if (header.id_length + offset > data.length) {
  75672. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75673. return;
  75674. }
  75675. // Skip not needed data
  75676. offset += header.id_length;
  75677. var use_rle = false;
  75678. var use_pal = false;
  75679. var use_grey = false;
  75680. // Get some informations.
  75681. switch (header.image_type) {
  75682. case TGATools._TYPE_RLE_INDEXED:
  75683. use_rle = true;
  75684. case TGATools._TYPE_INDEXED:
  75685. use_pal = true;
  75686. break;
  75687. case TGATools._TYPE_RLE_RGB:
  75688. use_rle = true;
  75689. case TGATools._TYPE_RGB:
  75690. // use_rgb = true;
  75691. break;
  75692. case TGATools._TYPE_RLE_GREY:
  75693. use_rle = true;
  75694. case TGATools._TYPE_GREY:
  75695. use_grey = true;
  75696. break;
  75697. }
  75698. var pixel_data;
  75699. // var numAlphaBits = header.flags & 0xf;
  75700. var pixel_size = header.pixel_size >> 3;
  75701. var pixel_total = header.width * header.height * pixel_size;
  75702. // Read palettes
  75703. var palettes;
  75704. if (use_pal) {
  75705. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75706. }
  75707. // Read LRE
  75708. if (use_rle) {
  75709. pixel_data = new Uint8Array(pixel_total);
  75710. var c, count, i;
  75711. var localOffset = 0;
  75712. var pixels = new Uint8Array(pixel_size);
  75713. while (offset < pixel_total && localOffset < pixel_total) {
  75714. c = data[offset++];
  75715. count = (c & 0x7f) + 1;
  75716. // RLE pixels
  75717. if (c & 0x80) {
  75718. // Bind pixel tmp array
  75719. for (i = 0; i < pixel_size; ++i) {
  75720. pixels[i] = data[offset++];
  75721. }
  75722. // Copy pixel array
  75723. for (i = 0; i < count; ++i) {
  75724. pixel_data.set(pixels, localOffset + i * pixel_size);
  75725. }
  75726. localOffset += pixel_size * count;
  75727. }
  75728. else {
  75729. count *= pixel_size;
  75730. for (i = 0; i < count; ++i) {
  75731. pixel_data[localOffset + i] = data[offset++];
  75732. }
  75733. localOffset += count;
  75734. }
  75735. }
  75736. }
  75737. else {
  75738. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75739. }
  75740. // Load to texture
  75741. var x_start, y_start, x_step, y_step, y_end, x_end;
  75742. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75743. default:
  75744. case TGATools._ORIGIN_UL:
  75745. x_start = 0;
  75746. x_step = 1;
  75747. x_end = header.width;
  75748. y_start = 0;
  75749. y_step = 1;
  75750. y_end = header.height;
  75751. break;
  75752. case TGATools._ORIGIN_BL:
  75753. x_start = 0;
  75754. x_step = 1;
  75755. x_end = header.width;
  75756. y_start = header.height - 1;
  75757. y_step = -1;
  75758. y_end = -1;
  75759. break;
  75760. case TGATools._ORIGIN_UR:
  75761. x_start = header.width - 1;
  75762. x_step = -1;
  75763. x_end = -1;
  75764. y_start = 0;
  75765. y_step = 1;
  75766. y_end = header.height;
  75767. break;
  75768. case TGATools._ORIGIN_BR:
  75769. x_start = header.width - 1;
  75770. x_step = -1;
  75771. x_end = -1;
  75772. y_start = header.height - 1;
  75773. y_step = -1;
  75774. y_end = -1;
  75775. break;
  75776. }
  75777. // Load the specify method
  75778. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75779. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75780. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75781. };
  75782. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75783. var image = pixel_data, colormap = palettes;
  75784. var width = header.width, height = header.height;
  75785. var color, i = 0, x, y;
  75786. var imageData = new Uint8Array(width * height * 4);
  75787. for (y = y_start; y !== y_end; y += y_step) {
  75788. for (x = x_start; x !== x_end; x += x_step, i++) {
  75789. color = image[i];
  75790. imageData[(x + width * y) * 4 + 3] = 255;
  75791. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75792. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75793. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75794. }
  75795. }
  75796. return imageData;
  75797. };
  75798. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75799. var image = pixel_data;
  75800. var width = header.width, height = header.height;
  75801. var color, i = 0, x, y;
  75802. var imageData = new Uint8Array(width * height * 4);
  75803. for (y = y_start; y !== y_end; y += y_step) {
  75804. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75805. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75806. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75807. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75808. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75809. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75810. }
  75811. }
  75812. return imageData;
  75813. };
  75814. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75815. var image = pixel_data;
  75816. var width = header.width, height = header.height;
  75817. var i = 0, x, y;
  75818. var imageData = new Uint8Array(width * height * 4);
  75819. for (y = y_start; y !== y_end; y += y_step) {
  75820. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75821. imageData[(x + width * y) * 4 + 3] = 255;
  75822. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75823. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75824. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75825. }
  75826. }
  75827. return imageData;
  75828. };
  75829. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75830. var image = pixel_data;
  75831. var width = header.width, height = header.height;
  75832. var i = 0, x, y;
  75833. var imageData = new Uint8Array(width * height * 4);
  75834. for (y = y_start; y !== y_end; y += y_step) {
  75835. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75836. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75837. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75838. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75839. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75840. }
  75841. }
  75842. return imageData;
  75843. };
  75844. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75845. var image = pixel_data;
  75846. var width = header.width, height = header.height;
  75847. var color, i = 0, x, y;
  75848. var imageData = new Uint8Array(width * height * 4);
  75849. for (y = y_start; y !== y_end; y += y_step) {
  75850. for (x = x_start; x !== x_end; x += x_step, i++) {
  75851. color = image[i];
  75852. imageData[(x + width * y) * 4 + 0] = color;
  75853. imageData[(x + width * y) * 4 + 1] = color;
  75854. imageData[(x + width * y) * 4 + 2] = color;
  75855. imageData[(x + width * y) * 4 + 3] = 255;
  75856. }
  75857. }
  75858. return imageData;
  75859. };
  75860. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75861. var image = pixel_data;
  75862. var width = header.width, height = header.height;
  75863. var i = 0, x, y;
  75864. var imageData = new Uint8Array(width * height * 4);
  75865. for (y = y_start; y !== y_end; y += y_step) {
  75866. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75867. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75868. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75869. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75870. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75871. }
  75872. }
  75873. return imageData;
  75874. };
  75875. //private static _TYPE_NO_DATA = 0;
  75876. TGATools._TYPE_INDEXED = 1;
  75877. TGATools._TYPE_RGB = 2;
  75878. TGATools._TYPE_GREY = 3;
  75879. TGATools._TYPE_RLE_INDEXED = 9;
  75880. TGATools._TYPE_RLE_RGB = 10;
  75881. TGATools._TYPE_RLE_GREY = 11;
  75882. TGATools._ORIGIN_MASK = 0x30;
  75883. TGATools._ORIGIN_SHIFT = 0x04;
  75884. TGATools._ORIGIN_BL = 0x00;
  75885. TGATools._ORIGIN_BR = 0x01;
  75886. TGATools._ORIGIN_UL = 0x02;
  75887. TGATools._ORIGIN_UR = 0x03;
  75888. return TGATools;
  75889. }());
  75890. BABYLON.TGATools = TGATools;
  75891. })(BABYLON || (BABYLON = {}));
  75892. //# sourceMappingURL=babylon.tga.js.map
  75893. var BABYLON;
  75894. (function (BABYLON) {
  75895. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75896. // All values and structures referenced from:
  75897. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75898. var DDS_MAGIC = 0x20534444;
  75899. var
  75900. //DDSD_CAPS = 0x1,
  75901. //DDSD_HEIGHT = 0x2,
  75902. //DDSD_WIDTH = 0x4,
  75903. //DDSD_PITCH = 0x8,
  75904. //DDSD_PIXELFORMAT = 0x1000,
  75905. DDSD_MIPMAPCOUNT = 0x20000;
  75906. //DDSD_LINEARSIZE = 0x80000,
  75907. //DDSD_DEPTH = 0x800000;
  75908. // var DDSCAPS_COMPLEX = 0x8,
  75909. // DDSCAPS_MIPMAP = 0x400000,
  75910. // DDSCAPS_TEXTURE = 0x1000;
  75911. var DDSCAPS2_CUBEMAP = 0x200;
  75912. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75913. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75914. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75915. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75916. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75917. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75918. // DDSCAPS2_VOLUME = 0x200000;
  75919. var
  75920. //DDPF_ALPHAPIXELS = 0x1,
  75921. //DDPF_ALPHA = 0x2,
  75922. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75923. //DDPF_YUV = 0x200,
  75924. DDPF_LUMINANCE = 0x20000;
  75925. function FourCCToInt32(value) {
  75926. return value.charCodeAt(0) +
  75927. (value.charCodeAt(1) << 8) +
  75928. (value.charCodeAt(2) << 16) +
  75929. (value.charCodeAt(3) << 24);
  75930. }
  75931. function Int32ToFourCC(value) {
  75932. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75933. }
  75934. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75935. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75936. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75937. var FOURCC_DX10 = FourCCToInt32("DX10");
  75938. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75939. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75940. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75941. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75942. var headerLengthInt = 31; // The header length in 32 bit ints
  75943. // Offsets into the header array
  75944. var off_magic = 0;
  75945. var off_size = 1;
  75946. var off_flags = 2;
  75947. var off_height = 3;
  75948. var off_width = 4;
  75949. var off_mipmapCount = 7;
  75950. var off_pfFlags = 20;
  75951. var off_pfFourCC = 21;
  75952. var off_RGBbpp = 22;
  75953. var off_RMask = 23;
  75954. var off_GMask = 24;
  75955. var off_BMask = 25;
  75956. var off_AMask = 26;
  75957. // var off_caps1 = 27;
  75958. var off_caps2 = 28;
  75959. // var off_caps3 = 29;
  75960. // var off_caps4 = 30;
  75961. var off_dxgiFormat = 32;
  75962. ;
  75963. var DDSTools = /** @class */ (function () {
  75964. function DDSTools() {
  75965. }
  75966. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75967. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75968. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75969. var mipmapCount = 1;
  75970. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75971. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75972. }
  75973. var fourCC = header[off_pfFourCC];
  75974. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75975. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75976. switch (fourCC) {
  75977. case FOURCC_D3DFMT_R16G16B16A16F:
  75978. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75979. break;
  75980. case FOURCC_D3DFMT_R32G32B32A32F:
  75981. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75982. break;
  75983. case FOURCC_DX10:
  75984. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75985. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75986. break;
  75987. }
  75988. }
  75989. return {
  75990. width: header[off_width],
  75991. height: header[off_height],
  75992. mipmapCount: mipmapCount,
  75993. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75994. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75995. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75996. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75997. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75998. dxgiFormat: dxgiFormat,
  75999. textureType: textureType
  76000. };
  76001. };
  76002. DDSTools._ToHalfFloat = function (value) {
  76003. if (!DDSTools._FloatView) {
  76004. DDSTools._FloatView = new Float32Array(1);
  76005. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76006. }
  76007. DDSTools._FloatView[0] = value;
  76008. var x = DDSTools._Int32View[0];
  76009. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76010. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76011. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76012. /* If zero, or denormal, or exponent underflows too much for a denormal
  76013. * half, return signed zero. */
  76014. if (e < 103) {
  76015. return bits;
  76016. }
  76017. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76018. if (e > 142) {
  76019. bits |= 0x7c00;
  76020. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76021. * not Inf, so make sure we set one mantissa bit too. */
  76022. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76023. return bits;
  76024. }
  76025. /* If exponent underflows but not too much, return a denormal */
  76026. if (e < 113) {
  76027. m |= 0x0800;
  76028. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76029. * to 1, which is OK. */
  76030. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76031. return bits;
  76032. }
  76033. bits |= ((e - 112) << 10) | (m >> 1);
  76034. bits += m & 1;
  76035. return bits;
  76036. };
  76037. DDSTools._FromHalfFloat = function (value) {
  76038. var s = (value & 0x8000) >> 15;
  76039. var e = (value & 0x7C00) >> 10;
  76040. var f = value & 0x03FF;
  76041. if (e === 0) {
  76042. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76043. }
  76044. else if (e == 0x1F) {
  76045. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76046. }
  76047. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76048. };
  76049. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76050. var destArray = new Float32Array(dataLength);
  76051. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76052. var index = 0;
  76053. for (var y = 0; y < height; y++) {
  76054. for (var x = 0; x < width; x++) {
  76055. var srcPos = (x + y * width) * 4;
  76056. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76057. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76058. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76059. if (DDSTools.StoreLODInAlphaChannel) {
  76060. destArray[index + 3] = lod;
  76061. }
  76062. else {
  76063. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76064. }
  76065. index += 4;
  76066. }
  76067. }
  76068. return destArray;
  76069. };
  76070. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76071. if (DDSTools.StoreLODInAlphaChannel) {
  76072. var destArray = new Uint16Array(dataLength);
  76073. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76074. var index = 0;
  76075. for (var y = 0; y < height; y++) {
  76076. for (var x = 0; x < width; x++) {
  76077. var srcPos = (x + y * width) * 4;
  76078. destArray[index] = srcData[srcPos];
  76079. destArray[index + 1] = srcData[srcPos + 1];
  76080. destArray[index + 2] = srcData[srcPos + 2];
  76081. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76082. index += 4;
  76083. }
  76084. }
  76085. return destArray;
  76086. }
  76087. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76088. };
  76089. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76090. if (DDSTools.StoreLODInAlphaChannel) {
  76091. var destArray = new Float32Array(dataLength);
  76092. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76093. var index = 0;
  76094. for (var y = 0; y < height; y++) {
  76095. for (var x = 0; x < width; x++) {
  76096. var srcPos = (x + y * width) * 4;
  76097. destArray[index] = srcData[srcPos];
  76098. destArray[index + 1] = srcData[srcPos + 1];
  76099. destArray[index + 2] = srcData[srcPos + 2];
  76100. destArray[index + 3] = lod;
  76101. index += 4;
  76102. }
  76103. }
  76104. return destArray;
  76105. }
  76106. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76107. };
  76108. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76109. var destArray = new Uint8Array(dataLength);
  76110. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76111. var index = 0;
  76112. for (var y = 0; y < height; y++) {
  76113. for (var x = 0; x < width; x++) {
  76114. var srcPos = (x + y * width) * 4;
  76115. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76116. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76117. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76118. if (DDSTools.StoreLODInAlphaChannel) {
  76119. destArray[index + 3] = lod;
  76120. }
  76121. else {
  76122. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76123. }
  76124. index += 4;
  76125. }
  76126. }
  76127. return destArray;
  76128. };
  76129. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76130. var destArray = new Uint8Array(dataLength);
  76131. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76132. var index = 0;
  76133. for (var y = 0; y < height; y++) {
  76134. for (var x = 0; x < width; x++) {
  76135. var srcPos = (x + y * width) * 4;
  76136. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76137. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76138. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76139. if (DDSTools.StoreLODInAlphaChannel) {
  76140. destArray[index + 3] = lod;
  76141. }
  76142. else {
  76143. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76144. }
  76145. index += 4;
  76146. }
  76147. }
  76148. return destArray;
  76149. };
  76150. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76151. var byteArray = new Uint8Array(dataLength);
  76152. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76153. var index = 0;
  76154. for (var y = 0; y < height; y++) {
  76155. for (var x = 0; x < width; x++) {
  76156. var srcPos = (x + y * width) * 4;
  76157. byteArray[index] = srcData[srcPos + rOffset];
  76158. byteArray[index + 1] = srcData[srcPos + gOffset];
  76159. byteArray[index + 2] = srcData[srcPos + bOffset];
  76160. byteArray[index + 3] = srcData[srcPos + aOffset];
  76161. index += 4;
  76162. }
  76163. }
  76164. return byteArray;
  76165. };
  76166. DDSTools._ExtractLongWordOrder = function (value) {
  76167. if (value === 0 || value === 255 || value === -16777216) {
  76168. return 0;
  76169. }
  76170. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76171. };
  76172. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76173. var byteArray = new Uint8Array(dataLength);
  76174. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76175. var index = 0;
  76176. for (var y = 0; y < height; y++) {
  76177. for (var x = 0; x < width; x++) {
  76178. var srcPos = (x + y * width) * 3;
  76179. byteArray[index] = srcData[srcPos + rOffset];
  76180. byteArray[index + 1] = srcData[srcPos + gOffset];
  76181. byteArray[index + 2] = srcData[srcPos + bOffset];
  76182. index += 3;
  76183. }
  76184. }
  76185. return byteArray;
  76186. };
  76187. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76188. var byteArray = new Uint8Array(dataLength);
  76189. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76190. var index = 0;
  76191. for (var y = 0; y < height; y++) {
  76192. for (var x = 0; x < width; x++) {
  76193. var srcPos = (x + y * width);
  76194. byteArray[index] = srcData[srcPos];
  76195. index++;
  76196. }
  76197. }
  76198. return byteArray;
  76199. };
  76200. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76201. if (lodIndex === void 0) { lodIndex = -1; }
  76202. var ext = engine.getCaps().s3tc;
  76203. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76204. var fourCC, width, height, dataLength = 0, dataOffset;
  76205. var byteArray, mipmapCount, mip;
  76206. var internalFormat = 0;
  76207. var format = 0;
  76208. var blockBytes = 1;
  76209. if (header[off_magic] !== DDS_MAGIC) {
  76210. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76211. return;
  76212. }
  76213. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76214. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76215. return;
  76216. }
  76217. if (info.isCompressed && !ext) {
  76218. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76219. return;
  76220. }
  76221. var bpp = header[off_RGBbpp];
  76222. dataOffset = header[off_size] + 4;
  76223. var computeFormats = false;
  76224. if (info.isFourCC) {
  76225. fourCC = header[off_pfFourCC];
  76226. switch (fourCC) {
  76227. case FOURCC_DXT1:
  76228. blockBytes = 8;
  76229. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76230. break;
  76231. case FOURCC_DXT3:
  76232. blockBytes = 16;
  76233. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76234. break;
  76235. case FOURCC_DXT5:
  76236. blockBytes = 16;
  76237. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76238. break;
  76239. case FOURCC_D3DFMT_R16G16B16A16F:
  76240. computeFormats = true;
  76241. break;
  76242. case FOURCC_D3DFMT_R32G32B32A32F:
  76243. computeFormats = true;
  76244. break;
  76245. case FOURCC_DX10:
  76246. // There is an additionnal header so dataOffset need to be changed
  76247. dataOffset += 5 * 4; // 5 uints
  76248. var supported = false;
  76249. switch (info.dxgiFormat) {
  76250. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76251. computeFormats = true;
  76252. supported = true;
  76253. break;
  76254. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76255. info.isRGB = true;
  76256. info.isFourCC = false;
  76257. bpp = 32;
  76258. supported = true;
  76259. break;
  76260. }
  76261. if (supported) {
  76262. break;
  76263. }
  76264. default:
  76265. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76266. return;
  76267. }
  76268. }
  76269. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76270. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76271. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76272. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76273. if (computeFormats) {
  76274. format = engine._getWebGLTextureType(info.textureType);
  76275. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76276. }
  76277. mipmapCount = 1;
  76278. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76279. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76280. }
  76281. for (var face = 0; face < faces; face++) {
  76282. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76283. width = header[off_width];
  76284. height = header[off_height];
  76285. for (mip = 0; mip < mipmapCount; ++mip) {
  76286. if (lodIndex === -1 || lodIndex === mip) {
  76287. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76288. var i = (lodIndex === -1) ? mip : 0;
  76289. if (!info.isCompressed && info.isFourCC) {
  76290. dataLength = width * height * 4;
  76291. var floatArray = null;
  76292. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76293. if (bpp === 128) {
  76294. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76295. }
  76296. else if (bpp === 64) {
  76297. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76298. }
  76299. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76300. format = engine._getWebGLTextureType(info.textureType);
  76301. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76302. }
  76303. else {
  76304. if (bpp === 128) {
  76305. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76306. }
  76307. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76308. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76309. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76310. format = engine._getWebGLTextureType(info.textureType);
  76311. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76312. }
  76313. else {
  76314. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76315. }
  76316. }
  76317. if (floatArray) {
  76318. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76319. }
  76320. }
  76321. else if (info.isRGB) {
  76322. if (bpp === 24) {
  76323. dataLength = width * height * 3;
  76324. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76325. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76326. }
  76327. else {
  76328. dataLength = width * height * 4;
  76329. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76330. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76331. }
  76332. }
  76333. else if (info.isLuminance) {
  76334. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76335. var unpaddedRowSize = width;
  76336. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76337. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76338. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76339. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76340. }
  76341. else {
  76342. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76343. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76344. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76345. }
  76346. }
  76347. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76348. width *= 0.5;
  76349. height *= 0.5;
  76350. width = Math.max(1.0, width);
  76351. height = Math.max(1.0, height);
  76352. }
  76353. if (currentFace !== undefined) {
  76354. // Loading a single face
  76355. break;
  76356. }
  76357. }
  76358. };
  76359. DDSTools.StoreLODInAlphaChannel = false;
  76360. return DDSTools;
  76361. }());
  76362. BABYLON.DDSTools = DDSTools;
  76363. })(BABYLON || (BABYLON = {}));
  76364. //# sourceMappingURL=babylon.dds.js.map
  76365. var BABYLON;
  76366. (function (BABYLON) {
  76367. /**
  76368. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76369. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76370. */
  76371. var KhronosTextureContainer = /** @class */ (function () {
  76372. /**
  76373. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76374. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76375. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76376. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76377. */
  76378. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76379. this.arrayBuffer = arrayBuffer;
  76380. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76381. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76382. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76383. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76384. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76385. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76386. BABYLON.Tools.Error("texture missing KTX identifier");
  76387. return;
  76388. }
  76389. // load the reset of the header in native 32 bit int
  76390. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76391. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76392. var oppositeEndianess = header[0] === 0x01020304;
  76393. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76394. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76395. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76396. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76397. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76398. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76399. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76400. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76401. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76402. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76403. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76404. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76405. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76406. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76407. if (this.glType !== 0) {
  76408. BABYLON.Tools.Error("only compressed formats currently supported");
  76409. return;
  76410. }
  76411. else {
  76412. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76413. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76414. }
  76415. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76416. BABYLON.Tools.Error("only 2D textures currently supported");
  76417. return;
  76418. }
  76419. if (this.numberOfArrayElements !== 0) {
  76420. BABYLON.Tools.Error("texture arrays not currently supported");
  76421. return;
  76422. }
  76423. if (this.numberOfFaces !== facesExpected) {
  76424. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76425. return;
  76426. }
  76427. // we now have a completely validated file, so could use existence of loadType as success
  76428. // would need to make this more elaborate & adjust checks above to support more than one load type
  76429. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76430. }
  76431. // not as fast hardware based, but will probably never need to use
  76432. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76433. return ((val & 0xFF) << 24)
  76434. | ((val & 0xFF00) << 8)
  76435. | ((val >> 8) & 0xFF00)
  76436. | ((val >> 24) & 0xFF);
  76437. };
  76438. /**
  76439. * It is assumed that the texture has already been created & is currently bound
  76440. */
  76441. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76442. switch (this.loadType) {
  76443. case KhronosTextureContainer.COMPRESSED_2D:
  76444. this._upload2DCompressedLevels(gl, loadMipmaps);
  76445. break;
  76446. case KhronosTextureContainer.TEX_2D:
  76447. case KhronosTextureContainer.COMPRESSED_3D:
  76448. case KhronosTextureContainer.TEX_3D:
  76449. }
  76450. };
  76451. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76452. // initialize width & height for level 1
  76453. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76454. var width = this.pixelWidth;
  76455. var height = this.pixelHeight;
  76456. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76457. for (var level = 0; level < mipmapCount; level++) {
  76458. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76459. for (var face = 0; face < this.numberOfFaces; face++) {
  76460. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76461. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76462. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76463. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76464. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76465. }
  76466. width = Math.max(1.0, width * 0.5);
  76467. height = Math.max(1.0, height * 0.5);
  76468. }
  76469. };
  76470. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76471. // load types
  76472. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76473. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76474. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76475. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76476. return KhronosTextureContainer;
  76477. }());
  76478. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76479. })(BABYLON || (BABYLON = {}));
  76480. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76481. var BABYLON;
  76482. (function (BABYLON) {
  76483. var Debug = /** @class */ (function () {
  76484. function Debug() {
  76485. }
  76486. Debug.AxesViewer = /** @class */ (function () {
  76487. function AxesViewer(scene, scaleLines) {
  76488. if (scaleLines === void 0) { scaleLines = 1; }
  76489. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76490. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76491. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76492. this.scaleLines = 1;
  76493. this.scaleLines = scaleLines;
  76494. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76495. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76496. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76497. this._xmesh.renderingGroupId = 2;
  76498. this._ymesh.renderingGroupId = 2;
  76499. this._zmesh.renderingGroupId = 2;
  76500. this._xmesh.material.checkReadyOnlyOnce = true;
  76501. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76502. this._ymesh.material.checkReadyOnlyOnce = true;
  76503. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76504. this._zmesh.material.checkReadyOnlyOnce = true;
  76505. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76506. this.scene = scene;
  76507. }
  76508. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76509. var scaleLines = this.scaleLines;
  76510. if (this._xmesh) {
  76511. this._xmesh.position.copyFrom(position);
  76512. }
  76513. if (this._ymesh) {
  76514. this._ymesh.position.copyFrom(position);
  76515. }
  76516. if (this._zmesh) {
  76517. this._zmesh.position.copyFrom(position);
  76518. }
  76519. var point2 = this._xline[1];
  76520. point2.x = xaxis.x * scaleLines;
  76521. point2.y = xaxis.y * scaleLines;
  76522. point2.z = xaxis.z * scaleLines;
  76523. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76524. point2 = this._yline[1];
  76525. point2.x = yaxis.x * scaleLines;
  76526. point2.y = yaxis.y * scaleLines;
  76527. point2.z = yaxis.z * scaleLines;
  76528. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76529. point2 = this._zline[1];
  76530. point2.x = zaxis.x * scaleLines;
  76531. point2.y = zaxis.y * scaleLines;
  76532. point2.z = zaxis.z * scaleLines;
  76533. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76534. };
  76535. AxesViewer.prototype.dispose = function () {
  76536. if (this._xmesh) {
  76537. this._xmesh.dispose();
  76538. }
  76539. if (this._ymesh) {
  76540. this._ymesh.dispose();
  76541. }
  76542. if (this._zmesh) {
  76543. this._zmesh.dispose();
  76544. }
  76545. this._xmesh = null;
  76546. this._ymesh = null;
  76547. this._zmesh = null;
  76548. this.scene = null;
  76549. };
  76550. return AxesViewer;
  76551. }());
  76552. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76553. __extends(BoneAxesViewer, _super);
  76554. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76555. if (scaleLines === void 0) { scaleLines = 1; }
  76556. var _this = _super.call(this, scene, scaleLines) || this;
  76557. _this.pos = BABYLON.Vector3.Zero();
  76558. _this.xaxis = BABYLON.Vector3.Zero();
  76559. _this.yaxis = BABYLON.Vector3.Zero();
  76560. _this.zaxis = BABYLON.Vector3.Zero();
  76561. _this.mesh = mesh;
  76562. _this.bone = bone;
  76563. return _this;
  76564. }
  76565. BoneAxesViewer.prototype.update = function () {
  76566. if (!this.mesh || !this.bone) {
  76567. return;
  76568. }
  76569. var bone = this.bone;
  76570. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76571. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76572. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76573. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76574. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76575. };
  76576. BoneAxesViewer.prototype.dispose = function () {
  76577. if (this.mesh) {
  76578. this.mesh = null;
  76579. this.bone = null;
  76580. _super.prototype.dispose.call(this);
  76581. }
  76582. };
  76583. return BoneAxesViewer;
  76584. }(Debug.AxesViewer));
  76585. Debug.PhysicsViewer = /** @class */ (function () {
  76586. function PhysicsViewer(scene) {
  76587. this._impostors = [];
  76588. this._meshes = [];
  76589. this._numMeshes = 0;
  76590. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76591. var physicEngine = this._scene.getPhysicsEngine();
  76592. if (physicEngine) {
  76593. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76594. }
  76595. }
  76596. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76597. var plugin = this._physicsEnginePlugin;
  76598. for (var i = 0; i < this._numMeshes; i++) {
  76599. var impostor = this._impostors[i];
  76600. if (!impostor) {
  76601. continue;
  76602. }
  76603. if (impostor.isDisposed) {
  76604. this.hideImpostor(this._impostors[i--]);
  76605. }
  76606. else {
  76607. var mesh = this._meshes[i];
  76608. if (mesh && plugin) {
  76609. plugin.syncMeshWithImpostor(mesh, impostor);
  76610. }
  76611. }
  76612. }
  76613. };
  76614. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76615. if (!this._scene) {
  76616. return;
  76617. }
  76618. for (var i = 0; i < this._numMeshes; i++) {
  76619. if (this._impostors[i] == impostor) {
  76620. return;
  76621. }
  76622. }
  76623. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76624. if (debugMesh) {
  76625. this._impostors[this._numMeshes] = impostor;
  76626. this._meshes[this._numMeshes] = debugMesh;
  76627. if (this._numMeshes === 0) {
  76628. this._renderFunction = this._updateDebugMeshes.bind(this);
  76629. this._scene.registerBeforeRender(this._renderFunction);
  76630. }
  76631. this._numMeshes++;
  76632. }
  76633. };
  76634. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76635. if (!impostor || !this._scene) {
  76636. return;
  76637. }
  76638. var removed = false;
  76639. for (var i = 0; i < this._numMeshes; i++) {
  76640. if (this._impostors[i] == impostor) {
  76641. var mesh = this._meshes[i];
  76642. if (!mesh) {
  76643. continue;
  76644. }
  76645. this._scene.removeMesh(mesh);
  76646. mesh.dispose();
  76647. this._numMeshes--;
  76648. if (this._numMeshes > 0) {
  76649. this._meshes[i] = this._meshes[this._numMeshes];
  76650. this._impostors[i] = this._impostors[this._numMeshes];
  76651. this._meshes[this._numMeshes] = null;
  76652. this._impostors[this._numMeshes] = null;
  76653. }
  76654. else {
  76655. this._meshes[0] = null;
  76656. this._impostors[0] = null;
  76657. }
  76658. removed = true;
  76659. break;
  76660. }
  76661. }
  76662. if (removed && this._numMeshes === 0) {
  76663. this._scene.unregisterBeforeRender(this._renderFunction);
  76664. }
  76665. };
  76666. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76667. if (!this._debugMaterial) {
  76668. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76669. this._debugMaterial.wireframe = true;
  76670. }
  76671. return this._debugMaterial;
  76672. };
  76673. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76674. if (!this._debugBoxMesh) {
  76675. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76676. this._debugBoxMesh.renderingGroupId = 1;
  76677. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76678. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76679. scene.removeMesh(this._debugBoxMesh);
  76680. }
  76681. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76682. };
  76683. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76684. if (!this._debugSphereMesh) {
  76685. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76686. this._debugSphereMesh.renderingGroupId = 1;
  76687. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76688. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76689. scene.removeMesh(this._debugSphereMesh);
  76690. }
  76691. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76692. };
  76693. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76694. var mesh = null;
  76695. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76696. mesh = this._getDebugBoxMesh(scene);
  76697. impostor.getBoxSizeToRef(mesh.scaling);
  76698. }
  76699. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76700. mesh = this._getDebugSphereMesh(scene);
  76701. var radius = impostor.getRadius();
  76702. mesh.scaling.x = radius * 2;
  76703. mesh.scaling.y = radius * 2;
  76704. mesh.scaling.z = radius * 2;
  76705. }
  76706. return mesh;
  76707. };
  76708. PhysicsViewer.prototype.dispose = function () {
  76709. for (var i = 0; i < this._numMeshes; i++) {
  76710. this.hideImpostor(this._impostors[i]);
  76711. }
  76712. if (this._debugBoxMesh) {
  76713. this._debugBoxMesh.dispose();
  76714. }
  76715. if (this._debugSphereMesh) {
  76716. this._debugSphereMesh.dispose();
  76717. }
  76718. if (this._debugMaterial) {
  76719. this._debugMaterial.dispose();
  76720. }
  76721. this._impostors.length = 0;
  76722. this._scene = null;
  76723. this._physicsEnginePlugin = null;
  76724. };
  76725. return PhysicsViewer;
  76726. }());
  76727. Debug.SkeletonViewer = /** @class */ (function () {
  76728. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76729. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76730. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76731. this.skeleton = skeleton;
  76732. this.mesh = mesh;
  76733. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76734. this.renderingGroupId = renderingGroupId;
  76735. this.color = BABYLON.Color3.White();
  76736. this._debugLines = new Array();
  76737. this._isEnabled = false;
  76738. this._scene = scene;
  76739. this.update();
  76740. this._renderFunction = this.update.bind(this);
  76741. }
  76742. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76743. get: function () {
  76744. return this._isEnabled;
  76745. },
  76746. set: function (value) {
  76747. if (this._isEnabled === value) {
  76748. return;
  76749. }
  76750. this._isEnabled = value;
  76751. if (value) {
  76752. this._scene.registerBeforeRender(this._renderFunction);
  76753. }
  76754. else {
  76755. this._scene.unregisterBeforeRender(this._renderFunction);
  76756. }
  76757. },
  76758. enumerable: true,
  76759. configurable: true
  76760. });
  76761. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76762. if (x === void 0) { x = 0; }
  76763. if (y === void 0) { y = 0; }
  76764. if (z === void 0) { z = 0; }
  76765. var tmat = BABYLON.Tmp.Matrix[0];
  76766. var parentBone = bone.getParent();
  76767. tmat.copyFrom(bone.getLocalMatrix());
  76768. if (x !== 0 || y !== 0 || z !== 0) {
  76769. var tmat2 = BABYLON.Tmp.Matrix[1];
  76770. BABYLON.Matrix.IdentityToRef(tmat2);
  76771. tmat2.m[12] = x;
  76772. tmat2.m[13] = y;
  76773. tmat2.m[14] = z;
  76774. tmat2.multiplyToRef(tmat, tmat);
  76775. }
  76776. if (parentBone) {
  76777. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76778. }
  76779. tmat.multiplyToRef(meshMat, tmat);
  76780. position.x = tmat.m[12];
  76781. position.y = tmat.m[13];
  76782. position.z = tmat.m[14];
  76783. };
  76784. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76785. var len = bones.length;
  76786. var meshPos = this.mesh.position;
  76787. for (var i = 0; i < len; i++) {
  76788. var bone = bones[i];
  76789. var points = this._debugLines[i];
  76790. if (!points) {
  76791. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76792. this._debugLines[i] = points;
  76793. }
  76794. this._getBonePosition(points[0], bone, meshMat);
  76795. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76796. points[0].subtractInPlace(meshPos);
  76797. points[1].subtractInPlace(meshPos);
  76798. }
  76799. };
  76800. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76801. var len = bones.length;
  76802. var boneNum = 0;
  76803. var meshPos = this.mesh.position;
  76804. for (var i = len - 1; i >= 0; i--) {
  76805. var childBone = bones[i];
  76806. var parentBone = childBone.getParent();
  76807. if (!parentBone) {
  76808. continue;
  76809. }
  76810. var points = this._debugLines[boneNum];
  76811. if (!points) {
  76812. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76813. this._debugLines[boneNum] = points;
  76814. }
  76815. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76816. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76817. points[0].subtractInPlace(meshPos);
  76818. points[1].subtractInPlace(meshPos);
  76819. boneNum++;
  76820. }
  76821. };
  76822. SkeletonViewer.prototype.update = function () {
  76823. if (this.autoUpdateBonesMatrices) {
  76824. this.skeleton.computeAbsoluteTransforms();
  76825. }
  76826. if (this.skeleton.bones[0].length === undefined) {
  76827. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76828. }
  76829. else {
  76830. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76831. }
  76832. if (!this._debugMesh) {
  76833. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76834. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76835. }
  76836. else {
  76837. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76838. }
  76839. this._debugMesh.position.copyFrom(this.mesh.position);
  76840. this._debugMesh.color = this.color;
  76841. };
  76842. SkeletonViewer.prototype.dispose = function () {
  76843. if (this._debugMesh) {
  76844. this.isEnabled = false;
  76845. this._debugMesh.dispose();
  76846. this._debugMesh = null;
  76847. }
  76848. };
  76849. return SkeletonViewer;
  76850. }());
  76851. return Debug;
  76852. }());
  76853. BABYLON.Debug = Debug;
  76854. })(BABYLON || (BABYLON = {}));
  76855. //# sourceMappingURL=babylon.debugModules.js.map
  76856. var BABYLON;
  76857. (function (BABYLON) {
  76858. var RayHelper = /** @class */ (function () {
  76859. function RayHelper(ray) {
  76860. this.ray = ray;
  76861. }
  76862. RayHelper.CreateAndShow = function (ray, scene, color) {
  76863. var helper = new RayHelper(ray);
  76864. helper.show(scene, color);
  76865. return helper;
  76866. };
  76867. RayHelper.prototype.show = function (scene, color) {
  76868. if (!this._renderFunction && this.ray) {
  76869. var ray = this.ray;
  76870. this._renderFunction = this._render.bind(this);
  76871. this._scene = scene;
  76872. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76873. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76874. if (this._renderFunction) {
  76875. this._scene.registerBeforeRender(this._renderFunction);
  76876. }
  76877. }
  76878. if (color && this._renderLine) {
  76879. this._renderLine.color.copyFrom(color);
  76880. }
  76881. };
  76882. RayHelper.prototype.hide = function () {
  76883. if (this._renderFunction && this._scene) {
  76884. this._scene.unregisterBeforeRender(this._renderFunction);
  76885. this._scene = null;
  76886. this._renderFunction = null;
  76887. if (this._renderLine) {
  76888. this._renderLine.dispose();
  76889. this._renderLine = null;
  76890. }
  76891. this._renderPoints = [];
  76892. }
  76893. };
  76894. RayHelper.prototype._render = function () {
  76895. var ray = this.ray;
  76896. if (!ray) {
  76897. return;
  76898. }
  76899. var point = this._renderPoints[1];
  76900. var len = Math.min(ray.length, 1000000);
  76901. point.copyFrom(ray.direction);
  76902. point.scaleInPlace(len);
  76903. point.addInPlace(ray.origin);
  76904. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76905. };
  76906. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76907. this._attachedToMesh = mesh;
  76908. var ray = this.ray;
  76909. if (!ray) {
  76910. return;
  76911. }
  76912. if (!ray.direction) {
  76913. ray.direction = BABYLON.Vector3.Zero();
  76914. }
  76915. if (!ray.origin) {
  76916. ray.origin = BABYLON.Vector3.Zero();
  76917. }
  76918. if (length) {
  76919. ray.length = length;
  76920. }
  76921. if (!meshSpaceOrigin) {
  76922. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76923. }
  76924. if (!meshSpaceDirection) {
  76925. // -1 so that this will work with Mesh.lookAt
  76926. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76927. }
  76928. if (!this._meshSpaceDirection) {
  76929. this._meshSpaceDirection = meshSpaceDirection.clone();
  76930. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76931. }
  76932. else {
  76933. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76934. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76935. }
  76936. if (!this._updateToMeshFunction) {
  76937. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76938. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76939. }
  76940. this._updateToMesh();
  76941. };
  76942. RayHelper.prototype.detachFromMesh = function () {
  76943. if (this._attachedToMesh) {
  76944. if (this._updateToMeshFunction) {
  76945. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76946. }
  76947. this._attachedToMesh = null;
  76948. this._updateToMeshFunction = null;
  76949. }
  76950. };
  76951. RayHelper.prototype._updateToMesh = function () {
  76952. var ray = this.ray;
  76953. if (!this._attachedToMesh || !ray) {
  76954. return;
  76955. }
  76956. if (this._attachedToMesh._isDisposed) {
  76957. this.detachFromMesh();
  76958. return;
  76959. }
  76960. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76961. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76962. };
  76963. RayHelper.prototype.dispose = function () {
  76964. this.hide();
  76965. this.detachFromMesh();
  76966. this.ray = null;
  76967. };
  76968. return RayHelper;
  76969. }());
  76970. BABYLON.RayHelper = RayHelper;
  76971. })(BABYLON || (BABYLON = {}));
  76972. //# sourceMappingURL=babylon.rayHelper.js.map
  76973. var BABYLON;
  76974. (function (BABYLON) {
  76975. // load the inspector using require, if not present in the global namespace.
  76976. var DebugLayer = /** @class */ (function () {
  76977. function DebugLayer(scene) {
  76978. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76979. this._scene = scene;
  76980. // load inspector using require, if it doesn't exist on the global namespace.
  76981. }
  76982. /** Creates the inspector window. */
  76983. DebugLayer.prototype._createInspector = function (config) {
  76984. if (config === void 0) { config = {}; }
  76985. var popup = config.popup || false;
  76986. var initialTab = config.initialTab || 0;
  76987. var parentElement = config.parentElement || null;
  76988. if (!this._inspector) {
  76989. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76990. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76991. } // else nothing to do,; instance is already existing
  76992. };
  76993. DebugLayer.prototype.isVisible = function () {
  76994. if (!this._inspector) {
  76995. return false;
  76996. }
  76997. return true;
  76998. };
  76999. DebugLayer.prototype.hide = function () {
  77000. if (this._inspector) {
  77001. try {
  77002. this._inspector.dispose();
  77003. }
  77004. catch (e) {
  77005. // If the inspector has been removed directly from the inspector tool
  77006. }
  77007. this._inspector = null;
  77008. }
  77009. };
  77010. DebugLayer.prototype.show = function (config) {
  77011. if (config === void 0) { config = {}; }
  77012. if (typeof this.BJSINSPECTOR == 'undefined') {
  77013. // Load inspector and add it to the DOM
  77014. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77015. }
  77016. else {
  77017. // Otherwise creates the inspector
  77018. this._createInspector(config);
  77019. }
  77020. };
  77021. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77022. return DebugLayer;
  77023. }());
  77024. BABYLON.DebugLayer = DebugLayer;
  77025. })(BABYLON || (BABYLON = {}));
  77026. //# sourceMappingURL=babylon.debugLayer.js.map
  77027. var BABYLON;
  77028. (function (BABYLON) {
  77029. var BoundingBoxRenderer = /** @class */ (function () {
  77030. function BoundingBoxRenderer(scene) {
  77031. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77032. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77033. this.showBackLines = true;
  77034. this.renderList = new BABYLON.SmartArray(32);
  77035. this._vertexBuffers = {};
  77036. this._scene = scene;
  77037. }
  77038. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77039. if (this._colorShader) {
  77040. return;
  77041. }
  77042. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77043. attributes: [BABYLON.VertexBuffer.PositionKind],
  77044. uniforms: ["world", "viewProjection", "color"]
  77045. });
  77046. var engine = this._scene.getEngine();
  77047. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77048. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77049. this._createIndexBuffer();
  77050. };
  77051. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77052. var engine = this._scene.getEngine();
  77053. 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]);
  77054. };
  77055. BoundingBoxRenderer.prototype._rebuild = function () {
  77056. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77057. if (vb) {
  77058. vb._rebuild();
  77059. }
  77060. this._createIndexBuffer();
  77061. };
  77062. BoundingBoxRenderer.prototype.reset = function () {
  77063. this.renderList.reset();
  77064. };
  77065. BoundingBoxRenderer.prototype.render = function () {
  77066. if (this.renderList.length === 0) {
  77067. return;
  77068. }
  77069. this._prepareRessources();
  77070. if (!this._colorShader.isReady()) {
  77071. return;
  77072. }
  77073. var engine = this._scene.getEngine();
  77074. engine.setDepthWrite(false);
  77075. this._colorShader._preBind();
  77076. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77077. var boundingBox = this.renderList.data[boundingBoxIndex];
  77078. var min = boundingBox.minimum;
  77079. var max = boundingBox.maximum;
  77080. var diff = max.subtract(min);
  77081. var median = min.add(diff.scale(0.5));
  77082. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77083. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77084. .multiply(boundingBox.getWorldMatrix());
  77085. // VBOs
  77086. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77087. if (this.showBackLines) {
  77088. // Back
  77089. engine.setDepthFunctionToGreaterOrEqual();
  77090. this._scene.resetCachedMaterial();
  77091. this._colorShader.setColor4("color", this.backColor.toColor4());
  77092. this._colorShader.bind(worldMatrix);
  77093. // Draw order
  77094. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77095. }
  77096. // Front
  77097. engine.setDepthFunctionToLess();
  77098. this._scene.resetCachedMaterial();
  77099. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77100. this._colorShader.bind(worldMatrix);
  77101. // Draw order
  77102. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77103. }
  77104. this._colorShader.unbind();
  77105. engine.setDepthFunctionToLessOrEqual();
  77106. engine.setDepthWrite(true);
  77107. };
  77108. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77109. this._prepareRessources();
  77110. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77111. return;
  77112. }
  77113. var engine = this._scene.getEngine();
  77114. engine.setDepthWrite(false);
  77115. engine.setColorWrite(false);
  77116. this._colorShader._preBind();
  77117. var boundingBox = mesh._boundingInfo.boundingBox;
  77118. var min = boundingBox.minimum;
  77119. var max = boundingBox.maximum;
  77120. var diff = max.subtract(min);
  77121. var median = min.add(diff.scale(0.5));
  77122. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77123. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77124. .multiply(boundingBox.getWorldMatrix());
  77125. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77126. engine.setDepthFunctionToLess();
  77127. this._scene.resetCachedMaterial();
  77128. this._colorShader.bind(worldMatrix);
  77129. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77130. this._colorShader.unbind();
  77131. engine.setDepthFunctionToLessOrEqual();
  77132. engine.setDepthWrite(true);
  77133. engine.setColorWrite(true);
  77134. };
  77135. BoundingBoxRenderer.prototype.dispose = function () {
  77136. if (!this._colorShader) {
  77137. return;
  77138. }
  77139. this.renderList.dispose();
  77140. this._colorShader.dispose();
  77141. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77142. if (buffer) {
  77143. buffer.dispose();
  77144. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77145. }
  77146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77147. };
  77148. return BoundingBoxRenderer;
  77149. }());
  77150. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77151. })(BABYLON || (BABYLON = {}));
  77152. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77153. var BABYLON;
  77154. (function (BABYLON) {
  77155. var MorphTarget = /** @class */ (function () {
  77156. function MorphTarget(name, influence) {
  77157. if (influence === void 0) { influence = 0; }
  77158. this.name = name;
  77159. this.animations = new Array();
  77160. this._positions = null;
  77161. this._normals = null;
  77162. this._tangents = null;
  77163. this.onInfluenceChanged = new BABYLON.Observable();
  77164. this.influence = influence;
  77165. }
  77166. Object.defineProperty(MorphTarget.prototype, "influence", {
  77167. get: function () {
  77168. return this._influence;
  77169. },
  77170. set: function (influence) {
  77171. if (this._influence === influence) {
  77172. return;
  77173. }
  77174. var previous = this._influence;
  77175. this._influence = influence;
  77176. if (this.onInfluenceChanged.hasObservers) {
  77177. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77178. }
  77179. },
  77180. enumerable: true,
  77181. configurable: true
  77182. });
  77183. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77184. get: function () {
  77185. return !!this._positions;
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77191. get: function () {
  77192. return !!this._normals;
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77198. get: function () {
  77199. return !!this._tangents;
  77200. },
  77201. enumerable: true,
  77202. configurable: true
  77203. });
  77204. MorphTarget.prototype.setPositions = function (data) {
  77205. this._positions = data;
  77206. };
  77207. MorphTarget.prototype.getPositions = function () {
  77208. return this._positions;
  77209. };
  77210. MorphTarget.prototype.setNormals = function (data) {
  77211. this._normals = data;
  77212. };
  77213. MorphTarget.prototype.getNormals = function () {
  77214. return this._normals;
  77215. };
  77216. MorphTarget.prototype.setTangents = function (data) {
  77217. this._tangents = data;
  77218. };
  77219. MorphTarget.prototype.getTangents = function () {
  77220. return this._tangents;
  77221. };
  77222. /**
  77223. * Serializes the current target into a Serialization object.
  77224. * Returns the serialized object.
  77225. */
  77226. MorphTarget.prototype.serialize = function () {
  77227. var serializationObject = {};
  77228. serializationObject.name = this.name;
  77229. serializationObject.influence = this.influence;
  77230. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77231. if (this.hasNormals) {
  77232. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77233. }
  77234. if (this.hasTangents) {
  77235. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77236. }
  77237. // Animations
  77238. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77239. return serializationObject;
  77240. };
  77241. // Statics
  77242. MorphTarget.Parse = function (serializationObject) {
  77243. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77244. result.setPositions(serializationObject.positions);
  77245. if (serializationObject.normals) {
  77246. result.setNormals(serializationObject.normals);
  77247. }
  77248. if (serializationObject.tangents) {
  77249. result.setTangents(serializationObject.tangents);
  77250. }
  77251. // Animations
  77252. if (serializationObject.animations) {
  77253. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77254. var parsedAnimation = serializationObject.animations[animationIndex];
  77255. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77256. }
  77257. }
  77258. return result;
  77259. };
  77260. MorphTarget.FromMesh = function (mesh, name, influence) {
  77261. if (!name) {
  77262. name = mesh.name;
  77263. }
  77264. var result = new MorphTarget(name, influence);
  77265. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77266. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77267. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77268. }
  77269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77270. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77271. }
  77272. return result;
  77273. };
  77274. return MorphTarget;
  77275. }());
  77276. BABYLON.MorphTarget = MorphTarget;
  77277. })(BABYLON || (BABYLON = {}));
  77278. //# sourceMappingURL=babylon.morphTarget.js.map
  77279. var BABYLON;
  77280. (function (BABYLON) {
  77281. var MorphTargetManager = /** @class */ (function () {
  77282. function MorphTargetManager(scene) {
  77283. if (scene === void 0) { scene = null; }
  77284. this._targets = new Array();
  77285. this._targetObservable = new Array();
  77286. this._activeTargets = new BABYLON.SmartArray(16);
  77287. this._supportsNormals = false;
  77288. this._supportsTangents = false;
  77289. this._vertexCount = 0;
  77290. this._uniqueId = 0;
  77291. this._tempInfluences = new Array();
  77292. if (!scene) {
  77293. scene = BABYLON.Engine.LastCreatedScene;
  77294. }
  77295. this._scene = scene;
  77296. if (this._scene) {
  77297. this._scene.morphTargetManagers.push(this);
  77298. this._uniqueId = this._scene.getUniqueId();
  77299. }
  77300. }
  77301. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77302. get: function () {
  77303. return this._uniqueId;
  77304. },
  77305. enumerable: true,
  77306. configurable: true
  77307. });
  77308. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77309. get: function () {
  77310. return this._vertexCount;
  77311. },
  77312. enumerable: true,
  77313. configurable: true
  77314. });
  77315. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77316. get: function () {
  77317. return this._supportsNormals;
  77318. },
  77319. enumerable: true,
  77320. configurable: true
  77321. });
  77322. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77323. get: function () {
  77324. return this._supportsTangents;
  77325. },
  77326. enumerable: true,
  77327. configurable: true
  77328. });
  77329. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77330. get: function () {
  77331. return this._targets.length;
  77332. },
  77333. enumerable: true,
  77334. configurable: true
  77335. });
  77336. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77337. get: function () {
  77338. return this._activeTargets.length;
  77339. },
  77340. enumerable: true,
  77341. configurable: true
  77342. });
  77343. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77344. get: function () {
  77345. return this._influences;
  77346. },
  77347. enumerable: true,
  77348. configurable: true
  77349. });
  77350. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77351. return this._activeTargets.data[index];
  77352. };
  77353. MorphTargetManager.prototype.getTarget = function (index) {
  77354. return this._targets[index];
  77355. };
  77356. MorphTargetManager.prototype.addTarget = function (target) {
  77357. var _this = this;
  77358. this._targets.push(target);
  77359. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77360. _this._syncActiveTargets(needUpdate);
  77361. }));
  77362. this._syncActiveTargets(true);
  77363. };
  77364. MorphTargetManager.prototype.removeTarget = function (target) {
  77365. var index = this._targets.indexOf(target);
  77366. if (index >= 0) {
  77367. this._targets.splice(index, 1);
  77368. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77369. this._syncActiveTargets(true);
  77370. }
  77371. };
  77372. /**
  77373. * Serializes the current manager into a Serialization object.
  77374. * Returns the serialized object.
  77375. */
  77376. MorphTargetManager.prototype.serialize = function () {
  77377. var serializationObject = {};
  77378. serializationObject.id = this.uniqueId;
  77379. serializationObject.targets = [];
  77380. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77381. var target = _a[_i];
  77382. serializationObject.targets.push(target.serialize());
  77383. }
  77384. return serializationObject;
  77385. };
  77386. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77387. var influenceCount = 0;
  77388. this._activeTargets.reset();
  77389. this._supportsNormals = true;
  77390. this._supportsTangents = true;
  77391. this._vertexCount = 0;
  77392. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77393. var target = _a[_i];
  77394. this._activeTargets.push(target);
  77395. this._tempInfluences[influenceCount++] = target.influence;
  77396. var positions = target.getPositions();
  77397. if (positions) {
  77398. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77399. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77400. var vertexCount = positions.length / 3;
  77401. if (this._vertexCount === 0) {
  77402. this._vertexCount = vertexCount;
  77403. }
  77404. else if (this._vertexCount !== vertexCount) {
  77405. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77406. return;
  77407. }
  77408. }
  77409. }
  77410. if (!this._influences || this._influences.length !== influenceCount) {
  77411. this._influences = new Float32Array(influenceCount);
  77412. }
  77413. for (var index = 0; index < influenceCount; index++) {
  77414. this._influences[index] = this._tempInfluences[index];
  77415. }
  77416. if (needUpdate && this._scene) {
  77417. // Flag meshes as dirty to resync with the active targets
  77418. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77419. var mesh = _c[_b];
  77420. if (mesh.morphTargetManager === this) {
  77421. mesh._syncGeometryWithMorphTargetManager();
  77422. }
  77423. }
  77424. }
  77425. };
  77426. // Statics
  77427. MorphTargetManager.Parse = function (serializationObject, scene) {
  77428. var result = new MorphTargetManager(scene);
  77429. result._uniqueId = serializationObject.id;
  77430. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77431. var targetData = _a[_i];
  77432. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77433. }
  77434. return result;
  77435. };
  77436. return MorphTargetManager;
  77437. }());
  77438. BABYLON.MorphTargetManager = MorphTargetManager;
  77439. })(BABYLON || (BABYLON = {}));
  77440. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77441. var BABYLON;
  77442. (function (BABYLON) {
  77443. var Octree = /** @class */ (function () {
  77444. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77445. if (maxDepth === void 0) { maxDepth = 2; }
  77446. this.maxDepth = maxDepth;
  77447. this.dynamicContent = new Array();
  77448. this._maxBlockCapacity = maxBlockCapacity || 64;
  77449. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77450. this._creationFunc = creationFunc;
  77451. }
  77452. // Methods
  77453. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77454. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77455. };
  77456. Octree.prototype.addMesh = function (entry) {
  77457. for (var index = 0; index < this.blocks.length; index++) {
  77458. var block = this.blocks[index];
  77459. block.addEntry(entry);
  77460. }
  77461. };
  77462. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77463. this._selectionContent.reset();
  77464. for (var index = 0; index < this.blocks.length; index++) {
  77465. var block = this.blocks[index];
  77466. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77467. }
  77468. if (allowDuplicate) {
  77469. this._selectionContent.concat(this.dynamicContent);
  77470. }
  77471. else {
  77472. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77473. }
  77474. return this._selectionContent;
  77475. };
  77476. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77477. this._selectionContent.reset();
  77478. for (var index = 0; index < this.blocks.length; index++) {
  77479. var block = this.blocks[index];
  77480. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77481. }
  77482. if (allowDuplicate) {
  77483. this._selectionContent.concat(this.dynamicContent);
  77484. }
  77485. else {
  77486. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77487. }
  77488. return this._selectionContent;
  77489. };
  77490. Octree.prototype.intersectsRay = function (ray) {
  77491. this._selectionContent.reset();
  77492. for (var index = 0; index < this.blocks.length; index++) {
  77493. var block = this.blocks[index];
  77494. block.intersectsRay(ray, this._selectionContent);
  77495. }
  77496. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77497. return this._selectionContent;
  77498. };
  77499. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77500. target.blocks = new Array();
  77501. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77502. // Segmenting space
  77503. for (var x = 0; x < 2; x++) {
  77504. for (var y = 0; y < 2; y++) {
  77505. for (var z = 0; z < 2; z++) {
  77506. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77507. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77508. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77509. block.addEntries(entries);
  77510. target.blocks.push(block);
  77511. }
  77512. }
  77513. }
  77514. };
  77515. Octree.CreationFuncForMeshes = function (entry, block) {
  77516. var boundingInfo = entry.getBoundingInfo();
  77517. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77518. block.entries.push(entry);
  77519. }
  77520. };
  77521. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77522. var boundingInfo = entry.getBoundingInfo();
  77523. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77524. block.entries.push(entry);
  77525. }
  77526. };
  77527. return Octree;
  77528. }());
  77529. BABYLON.Octree = Octree;
  77530. })(BABYLON || (BABYLON = {}));
  77531. //# sourceMappingURL=babylon.octree.js.map
  77532. var BABYLON;
  77533. (function (BABYLON) {
  77534. var OctreeBlock = /** @class */ (function () {
  77535. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77536. this.entries = new Array();
  77537. this._boundingVectors = new Array();
  77538. this._capacity = capacity;
  77539. this._depth = depth;
  77540. this._maxDepth = maxDepth;
  77541. this._creationFunc = creationFunc;
  77542. this._minPoint = minPoint;
  77543. this._maxPoint = maxPoint;
  77544. this._boundingVectors.push(minPoint.clone());
  77545. this._boundingVectors.push(maxPoint.clone());
  77546. this._boundingVectors.push(minPoint.clone());
  77547. this._boundingVectors[2].x = maxPoint.x;
  77548. this._boundingVectors.push(minPoint.clone());
  77549. this._boundingVectors[3].y = maxPoint.y;
  77550. this._boundingVectors.push(minPoint.clone());
  77551. this._boundingVectors[4].z = maxPoint.z;
  77552. this._boundingVectors.push(maxPoint.clone());
  77553. this._boundingVectors[5].z = minPoint.z;
  77554. this._boundingVectors.push(maxPoint.clone());
  77555. this._boundingVectors[6].x = minPoint.x;
  77556. this._boundingVectors.push(maxPoint.clone());
  77557. this._boundingVectors[7].y = minPoint.y;
  77558. }
  77559. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77560. // Property
  77561. get: function () {
  77562. return this._capacity;
  77563. },
  77564. enumerable: true,
  77565. configurable: true
  77566. });
  77567. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77568. get: function () {
  77569. return this._minPoint;
  77570. },
  77571. enumerable: true,
  77572. configurable: true
  77573. });
  77574. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77575. get: function () {
  77576. return this._maxPoint;
  77577. },
  77578. enumerable: true,
  77579. configurable: true
  77580. });
  77581. // Methods
  77582. OctreeBlock.prototype.addEntry = function (entry) {
  77583. if (this.blocks) {
  77584. for (var index = 0; index < this.blocks.length; index++) {
  77585. var block = this.blocks[index];
  77586. block.addEntry(entry);
  77587. }
  77588. return;
  77589. }
  77590. this._creationFunc(entry, this);
  77591. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77592. this.createInnerBlocks();
  77593. }
  77594. };
  77595. OctreeBlock.prototype.addEntries = function (entries) {
  77596. for (var index = 0; index < entries.length; index++) {
  77597. var mesh = entries[index];
  77598. this.addEntry(mesh);
  77599. }
  77600. };
  77601. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77602. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77603. if (this.blocks) {
  77604. for (var index = 0; index < this.blocks.length; index++) {
  77605. var block = this.blocks[index];
  77606. block.select(frustumPlanes, selection, allowDuplicate);
  77607. }
  77608. return;
  77609. }
  77610. if (allowDuplicate) {
  77611. selection.concat(this.entries);
  77612. }
  77613. else {
  77614. selection.concatWithNoDuplicate(this.entries);
  77615. }
  77616. }
  77617. };
  77618. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77619. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77620. if (this.blocks) {
  77621. for (var index = 0; index < this.blocks.length; index++) {
  77622. var block = this.blocks[index];
  77623. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77624. }
  77625. return;
  77626. }
  77627. if (allowDuplicate) {
  77628. selection.concat(this.entries);
  77629. }
  77630. else {
  77631. selection.concatWithNoDuplicate(this.entries);
  77632. }
  77633. }
  77634. };
  77635. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77636. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77637. if (this.blocks) {
  77638. for (var index = 0; index < this.blocks.length; index++) {
  77639. var block = this.blocks[index];
  77640. block.intersectsRay(ray, selection);
  77641. }
  77642. return;
  77643. }
  77644. selection.concatWithNoDuplicate(this.entries);
  77645. }
  77646. };
  77647. OctreeBlock.prototype.createInnerBlocks = function () {
  77648. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77649. };
  77650. return OctreeBlock;
  77651. }());
  77652. BABYLON.OctreeBlock = OctreeBlock;
  77653. })(BABYLON || (BABYLON = {}));
  77654. //# sourceMappingURL=babylon.octreeBlock.js.map
  77655. var BABYLON;
  77656. (function (BABYLON) {
  77657. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77658. __extends(VRDistortionCorrectionPostProcess, _super);
  77659. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77660. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77661. 'LensCenter',
  77662. 'Scale',
  77663. 'ScaleIn',
  77664. 'HmdWarpParam'
  77665. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77666. _this._isRightEye = isRightEye;
  77667. _this._distortionFactors = vrMetrics.distortionK;
  77668. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77669. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77670. _this.adaptScaleToCurrentViewport = true;
  77671. _this.onSizeChangedObservable.add(function () {
  77672. _this.aspectRatio = _this.width * .5 / _this.height;
  77673. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77674. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77675. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77676. });
  77677. _this.onApplyObservable.add(function (effect) {
  77678. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77679. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77680. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77681. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77682. });
  77683. return _this;
  77684. }
  77685. return VRDistortionCorrectionPostProcess;
  77686. }(BABYLON.PostProcess));
  77687. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77688. })(BABYLON || (BABYLON = {}));
  77689. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77690. var BABYLON;
  77691. (function (BABYLON) {
  77692. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77693. __extends(AnaglyphPostProcess, _super);
  77694. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77695. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77696. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77697. _this.onApplyObservable.add(function (effect) {
  77698. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77699. });
  77700. return _this;
  77701. }
  77702. return AnaglyphPostProcess;
  77703. }(BABYLON.PostProcess));
  77704. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77705. })(BABYLON || (BABYLON = {}));
  77706. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77707. var BABYLON;
  77708. (function (BABYLON) {
  77709. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77710. __extends(StereoscopicInterlacePostProcess, _super);
  77711. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77712. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77713. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77714. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77715. _this.onSizeChangedObservable.add(function () {
  77716. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77717. });
  77718. _this.onApplyObservable.add(function (effect) {
  77719. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77720. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77721. });
  77722. return _this;
  77723. }
  77724. return StereoscopicInterlacePostProcess;
  77725. }(BABYLON.PostProcess));
  77726. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77727. })(BABYLON || (BABYLON = {}));
  77728. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77729. var BABYLON;
  77730. (function (BABYLON) {
  77731. /**
  77732. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77733. * Screen rotation is taken into account.
  77734. */
  77735. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77736. function FreeCameraDeviceOrientationInput() {
  77737. var _this = this;
  77738. this._screenOrientationAngle = 0;
  77739. this._screenQuaternion = new BABYLON.Quaternion();
  77740. this._alpha = 0;
  77741. this._beta = 0;
  77742. this._gamma = 0;
  77743. this._orientationChanged = function () {
  77744. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77745. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77746. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77747. };
  77748. this._deviceOrientation = function (evt) {
  77749. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77750. _this._beta = evt.beta !== null ? evt.beta : 0;
  77751. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77752. };
  77753. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77754. this._orientationChanged();
  77755. }
  77756. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77757. get: function () {
  77758. return this._camera;
  77759. },
  77760. set: function (camera) {
  77761. this._camera = camera;
  77762. if (this._camera != null && !this._camera.rotationQuaternion) {
  77763. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77764. }
  77765. },
  77766. enumerable: true,
  77767. configurable: true
  77768. });
  77769. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77770. window.addEventListener("orientationchange", this._orientationChanged);
  77771. window.addEventListener("deviceorientation", this._deviceOrientation);
  77772. //In certain cases, the attach control is called AFTER orientation was changed,
  77773. //So this is needed.
  77774. this._orientationChanged();
  77775. };
  77776. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77777. window.removeEventListener("orientationchange", this._orientationChanged);
  77778. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77779. };
  77780. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77781. //if no device orientation provided, don't update the rotation.
  77782. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77783. if (!this._alpha)
  77784. return;
  77785. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77786. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77787. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77788. //Mirror on XY Plane
  77789. this._camera.rotationQuaternion.z *= -1;
  77790. this._camera.rotationQuaternion.w *= -1;
  77791. };
  77792. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77793. return "FreeCameraDeviceOrientationInput";
  77794. };
  77795. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77796. return "deviceOrientation";
  77797. };
  77798. return FreeCameraDeviceOrientationInput;
  77799. }());
  77800. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77801. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77802. })(BABYLON || (BABYLON = {}));
  77803. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77804. var BABYLON;
  77805. (function (BABYLON) {
  77806. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77807. function ArcRotateCameraVRDeviceOrientationInput() {
  77808. this.alphaCorrection = 1;
  77809. this.betaCorrection = 1;
  77810. this.gammaCorrection = 1;
  77811. this._alpha = 0;
  77812. this._gamma = 0;
  77813. this._dirty = false;
  77814. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77815. }
  77816. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77817. this.camera.attachControl(element, noPreventDefault);
  77818. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77819. };
  77820. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77821. if (evt.alpha !== null) {
  77822. this._alpha = +evt.alpha | 0;
  77823. }
  77824. if (evt.gamma !== null) {
  77825. this._gamma = +evt.gamma | 0;
  77826. }
  77827. this._dirty = true;
  77828. };
  77829. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77830. if (this._dirty) {
  77831. this._dirty = false;
  77832. if (this._gamma < 0) {
  77833. this._gamma = 180 + this._gamma;
  77834. }
  77835. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77836. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77837. }
  77838. };
  77839. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77840. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77841. };
  77842. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77843. return "ArcRotateCameraVRDeviceOrientationInput";
  77844. };
  77845. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77846. return "VRDeviceOrientation";
  77847. };
  77848. return ArcRotateCameraVRDeviceOrientationInput;
  77849. }());
  77850. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77851. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77852. })(BABYLON || (BABYLON = {}));
  77853. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77854. var BABYLON;
  77855. (function (BABYLON) {
  77856. var VRCameraMetrics = /** @class */ (function () {
  77857. function VRCameraMetrics() {
  77858. this.compensateDistortion = true;
  77859. }
  77860. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77861. get: function () {
  77862. return this.hResolution / (2 * this.vResolution);
  77863. },
  77864. enumerable: true,
  77865. configurable: true
  77866. });
  77867. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77868. get: function () {
  77869. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77870. },
  77871. enumerable: true,
  77872. configurable: true
  77873. });
  77874. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77875. get: function () {
  77876. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77877. var h = (4 * meters) / this.hScreenSize;
  77878. return BABYLON.Matrix.Translation(h, 0, 0);
  77879. },
  77880. enumerable: true,
  77881. configurable: true
  77882. });
  77883. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77884. get: function () {
  77885. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77886. var h = (4 * meters) / this.hScreenSize;
  77887. return BABYLON.Matrix.Translation(-h, 0, 0);
  77888. },
  77889. enumerable: true,
  77890. configurable: true
  77891. });
  77892. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77893. get: function () {
  77894. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77895. },
  77896. enumerable: true,
  77897. configurable: true
  77898. });
  77899. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77900. get: function () {
  77901. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77902. },
  77903. enumerable: true,
  77904. configurable: true
  77905. });
  77906. VRCameraMetrics.GetDefault = function () {
  77907. var result = new VRCameraMetrics();
  77908. result.hResolution = 1280;
  77909. result.vResolution = 800;
  77910. result.hScreenSize = 0.149759993;
  77911. result.vScreenSize = 0.0935999975;
  77912. result.vScreenCenter = 0.0467999987;
  77913. result.eyeToScreenDistance = 0.0410000011;
  77914. result.lensSeparationDistance = 0.0635000020;
  77915. result.interpupillaryDistance = 0.0640000030;
  77916. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77917. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77918. result.postProcessScaleFactor = 1.714605507808412;
  77919. result.lensCenterOffset = 0.151976421;
  77920. return result;
  77921. };
  77922. return VRCameraMetrics;
  77923. }());
  77924. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77925. })(BABYLON || (BABYLON = {}));
  77926. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77927. var BABYLON;
  77928. (function (BABYLON) {
  77929. /**
  77930. * This represents a WebVR camera.
  77931. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77932. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77933. */
  77934. var WebVRFreeCamera = /** @class */ (function (_super) {
  77935. __extends(WebVRFreeCamera, _super);
  77936. /**
  77937. * Instantiates a WebVRFreeCamera.
  77938. * @param name The name of the WebVRFreeCamera
  77939. * @param position The starting anchor position for the camera
  77940. * @param scene The scene the camera belongs to
  77941. * @param webVROptions a set of customizable options for the webVRCamera
  77942. */
  77943. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77944. if (webVROptions === void 0) { webVROptions = {}; }
  77945. var _this = _super.call(this, name, position, scene) || this;
  77946. _this.webVROptions = webVROptions;
  77947. /**
  77948. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77949. */
  77950. _this._vrDevice = null;
  77951. /**
  77952. * The rawPose of the vrDevice.
  77953. */
  77954. _this.rawPose = null;
  77955. _this._specsVersion = "1.1";
  77956. _this._attached = false;
  77957. _this._descendants = [];
  77958. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77959. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77960. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77961. _this._standingMatrix = null;
  77962. /**
  77963. * Represents device position in babylon space.
  77964. */
  77965. _this.devicePosition = BABYLON.Vector3.Zero();
  77966. /**
  77967. * Represents device rotation in babylon space.
  77968. */
  77969. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77970. /**
  77971. * The scale of the device to be used when translating from device space to babylon space.
  77972. */
  77973. _this.deviceScaleFactor = 1;
  77974. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77975. _this._worldToDevice = BABYLON.Matrix.Identity();
  77976. /**
  77977. * References to the webVR controllers for the vrDevice.
  77978. */
  77979. _this.controllers = [];
  77980. /**
  77981. * Emits an event when a controller is attached.
  77982. */
  77983. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77984. /**
  77985. * Emits an event when a controller's mesh has been loaded;
  77986. */
  77987. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77988. /**
  77989. * If the rig cameras be used as parent instead of this camera.
  77990. */
  77991. _this.rigParenting = true;
  77992. _this._defaultHeight = undefined;
  77993. _this._workingVector = BABYLON.Vector3.Zero();
  77994. _this._oneVector = BABYLON.Vector3.One();
  77995. _this._workingMatrix = BABYLON.Matrix.Identity();
  77996. _this._cache.position = BABYLON.Vector3.Zero();
  77997. if (webVROptions.defaultHeight) {
  77998. _this._defaultHeight = webVROptions.defaultHeight;
  77999. _this.position.y = _this._defaultHeight;
  78000. }
  78001. _this.minZ = 0.1;
  78002. //legacy support - the compensation boolean was removed.
  78003. if (arguments.length === 5) {
  78004. _this.webVROptions = arguments[4];
  78005. }
  78006. // default webVR options
  78007. if (_this.webVROptions.trackPosition == undefined) {
  78008. _this.webVROptions.trackPosition = true;
  78009. }
  78010. if (_this.webVROptions.controllerMeshes == undefined) {
  78011. _this.webVROptions.controllerMeshes = true;
  78012. }
  78013. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78014. _this.webVROptions.defaultLightingOnControllers = true;
  78015. }
  78016. _this.rotationQuaternion = new BABYLON.Quaternion();
  78017. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78018. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78019. }
  78020. //enable VR
  78021. var engine = _this.getEngine();
  78022. _this._onVREnabled = function (success) { if (success) {
  78023. _this.initControllers();
  78024. } };
  78025. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78026. engine.initWebVR().add(function (event) {
  78027. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78028. return;
  78029. }
  78030. _this._vrDevice = event.vrDisplay;
  78031. //reset the rig parameters.
  78032. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78033. if (_this._attached) {
  78034. _this.getEngine().enableVR();
  78035. }
  78036. });
  78037. if (typeof (VRFrameData) !== "undefined")
  78038. _this._frameData = new VRFrameData();
  78039. /**
  78040. * The idea behind the following lines:
  78041. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78042. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78043. * the second will not show it correctly.
  78044. *
  78045. * To solve this - each object that has the camera as parent will be added to a protected array.
  78046. * When the rig camera renders, it will take this array and set all of those to be its children.
  78047. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78048. * Amazing!
  78049. */
  78050. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78051. if (camera.parent === _this && _this.rigParenting) {
  78052. _this._descendants = _this.getDescendants(true, function (n) {
  78053. // don't take the cameras or the controllers!
  78054. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78055. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78056. return !isController && !isRigCamera;
  78057. });
  78058. _this._descendants.forEach(function (node) {
  78059. node.parent = camera;
  78060. });
  78061. }
  78062. });
  78063. scene.onAfterCameraRenderObservable.add(function (camera) {
  78064. if (camera.parent === _this && _this.rigParenting) {
  78065. _this._descendants.forEach(function (node) {
  78066. node.parent = _this;
  78067. });
  78068. }
  78069. });
  78070. return _this;
  78071. }
  78072. /**
  78073. * Gets the device distance from the ground.
  78074. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  78075. */
  78076. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78077. if (this._standingMatrix && this._defaultHeight === undefined) {
  78078. // Add standing matrix offset to get real offset from ground in room
  78079. this._standingMatrix.getTranslationToRef(this._workingVector);
  78080. return this._deviceRoomPosition.y + this._workingVector.y;
  78081. }
  78082. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78083. return this._defaultHeight || 0;
  78084. };
  78085. /**
  78086. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78087. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78088. */
  78089. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78090. var _this = this;
  78091. if (callback === void 0) { callback = function (bool) { }; }
  78092. // Use standing matrix if available
  78093. if (!navigator || !navigator.getVRDisplays) {
  78094. callback(false);
  78095. }
  78096. else {
  78097. navigator.getVRDisplays().then(function (displays) {
  78098. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  78099. callback(false);
  78100. }
  78101. else {
  78102. _this._standingMatrix = new BABYLON.Matrix();
  78103. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78104. if (!_this.getScene().useRightHandedSystem) {
  78105. [2, 6, 8, 9, 14].forEach(function (num) {
  78106. if (_this._standingMatrix) {
  78107. _this._standingMatrix.m[num] *= -1;
  78108. }
  78109. });
  78110. }
  78111. callback(true);
  78112. }
  78113. });
  78114. }
  78115. };
  78116. /**
  78117. * Disposes the camera
  78118. */
  78119. WebVRFreeCamera.prototype.dispose = function () {
  78120. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78121. _super.prototype.dispose.call(this);
  78122. };
  78123. /**
  78124. * Gets a vrController by name.
  78125. * @param name The name of the controller to retreive
  78126. * @returns the controller matching the name specified or null if not found
  78127. */
  78128. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78129. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78130. var gp = _a[_i];
  78131. if (gp.hand === name) {
  78132. return gp;
  78133. }
  78134. }
  78135. return null;
  78136. };
  78137. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78138. /**
  78139. * The controller corrisponding to the users left hand.
  78140. */
  78141. get: function () {
  78142. if (!this._leftController) {
  78143. this._leftController = this.getControllerByName("left");
  78144. }
  78145. return this._leftController;
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. ;
  78151. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78152. /**
  78153. * The controller corrisponding to the users right hand.
  78154. */
  78155. get: function () {
  78156. if (!this._rightController) {
  78157. this._rightController = this.getControllerByName("right");
  78158. }
  78159. return this._rightController;
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. ;
  78165. /**
  78166. * Casts a ray forward from the vrCamera's gaze.
  78167. * @param length Length of the ray (default: 100)
  78168. * @returns the ray corrisponding to the gaze
  78169. */
  78170. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78171. if (length === void 0) { length = 100; }
  78172. if (this.leftCamera) {
  78173. // Use left eye to avoid computation to compute center on every call
  78174. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78175. }
  78176. else {
  78177. return _super.prototype.getForwardRay.call(this, length);
  78178. }
  78179. };
  78180. /**
  78181. * Updates the camera based on device's frame data
  78182. */
  78183. WebVRFreeCamera.prototype._checkInputs = function () {
  78184. if (this._vrDevice && this._vrDevice.isPresenting) {
  78185. this._vrDevice.getFrameData(this._frameData);
  78186. this.updateFromDevice(this._frameData.pose);
  78187. }
  78188. _super.prototype._checkInputs.call(this);
  78189. };
  78190. /**
  78191. * Updates the poseControlled values based on the input device pose.
  78192. * @param poseData Pose coming from the device
  78193. */
  78194. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78195. if (poseData && poseData.orientation) {
  78196. this.rawPose = poseData;
  78197. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78198. if (this.getScene().useRightHandedSystem) {
  78199. this._deviceRoomRotationQuaternion.z *= -1;
  78200. this._deviceRoomRotationQuaternion.w *= -1;
  78201. }
  78202. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78203. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78204. if (this.getScene().useRightHandedSystem) {
  78205. this._deviceRoomPosition.z *= -1;
  78206. }
  78207. }
  78208. }
  78209. };
  78210. /**
  78211. * WebVR's attach control will start broadcasting frames to the device.
  78212. * Note that in certain browsers (chrome for example) this function must be called
  78213. * within a user-interaction callback. Example:
  78214. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78215. *
  78216. * @param element html element to attach the vrDevice to
  78217. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78218. */
  78219. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78220. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78221. this._attached = true;
  78222. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78223. if (this._vrDevice) {
  78224. this.getEngine().enableVR();
  78225. }
  78226. };
  78227. /**
  78228. * Detaches the camera from the html element and disables VR
  78229. *
  78230. * @param element html element to detach from
  78231. */
  78232. WebVRFreeCamera.prototype.detachControl = function (element) {
  78233. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78234. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78235. _super.prototype.detachControl.call(this, element);
  78236. this._attached = false;
  78237. this.getEngine().disableVR();
  78238. };
  78239. /**
  78240. * @returns the name of this class
  78241. */
  78242. WebVRFreeCamera.prototype.getClassName = function () {
  78243. return "WebVRFreeCamera";
  78244. };
  78245. /**
  78246. * Calls resetPose on the vrDisplay
  78247. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78248. */
  78249. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78250. //uses the vrDisplay's "resetPose()".
  78251. //pitch and roll won't be affected.
  78252. this._vrDevice.resetPose();
  78253. };
  78254. /**
  78255. * Updates the rig cameras (left and right eye)
  78256. */
  78257. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78258. var camLeft = this._rigCameras[0];
  78259. var camRight = this._rigCameras[1];
  78260. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78261. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78262. camLeft.position.copyFrom(this._deviceRoomPosition);
  78263. camRight.position.copyFrom(this._deviceRoomPosition);
  78264. };
  78265. /**
  78266. * Updates the cached values of the camera
  78267. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78268. */
  78269. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78270. var _this = this;
  78271. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78272. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78273. if (!this.updateCacheCalled) {
  78274. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78275. this.updateCacheCalled = true;
  78276. this.update();
  78277. }
  78278. // Set working vector to the device position in room space rotated by the new rotation
  78279. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78280. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78281. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78282. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78283. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78284. // Add translation from anchor position
  78285. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78286. this._workingVector.addInPlace(this.position);
  78287. this._workingVector.subtractInPlace(this._cache.position);
  78288. this._deviceToWorld.setTranslation(this._workingVector);
  78289. // Set an inverted matrix to be used when updating the camera
  78290. this._deviceToWorld.invertToRef(this._worldToDevice);
  78291. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78292. this.controllers.forEach(function (controller) {
  78293. controller._deviceToWorld = _this._deviceToWorld;
  78294. controller.update();
  78295. });
  78296. }
  78297. if (!ignoreParentClass) {
  78298. _super.prototype._updateCache.call(this);
  78299. }
  78300. this.updateCacheCalled = false;
  78301. };
  78302. /**
  78303. * Updates the current device position and rotation in the babylon world
  78304. */
  78305. WebVRFreeCamera.prototype.update = function () {
  78306. // Get current device position in babylon world
  78307. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78308. // Get current device rotation in babylon world
  78309. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78310. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78311. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78312. _super.prototype.update.call(this);
  78313. };
  78314. /**
  78315. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78316. * @returns an identity matrix
  78317. */
  78318. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78319. return BABYLON.Matrix.Identity();
  78320. };
  78321. /**
  78322. * This function is called by the two RIG cameras.
  78323. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78324. */
  78325. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78326. var _this = this;
  78327. //WebVR 1.1
  78328. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78329. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78330. if (!this.getScene().useRightHandedSystem) {
  78331. [2, 6, 8, 9, 14].forEach(function (num) {
  78332. _this._webvrViewMatrix.m[num] *= -1;
  78333. });
  78334. }
  78335. // update the camera rotation matrix
  78336. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78337. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78338. // Computing target and final matrix
  78339. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78340. var parentCamera = this._cameraRigParams["parentCamera"];
  78341. // should the view matrix be updated with scale and position offset?
  78342. if (parentCamera.deviceScaleFactor !== 1) {
  78343. this._webvrViewMatrix.invert();
  78344. // scale the position, if set
  78345. if (parentCamera.deviceScaleFactor) {
  78346. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78347. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78348. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78349. }
  78350. this._webvrViewMatrix.invert();
  78351. }
  78352. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78353. return this._webvrViewMatrix;
  78354. };
  78355. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78356. var _this = this;
  78357. var parentCamera = this.parent;
  78358. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78359. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78360. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78361. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78362. //babylon compatible matrix
  78363. if (!this.getScene().useRightHandedSystem) {
  78364. [8, 9, 10, 11].forEach(function (num) {
  78365. _this._projectionMatrix.m[num] *= -1;
  78366. });
  78367. }
  78368. return this._projectionMatrix;
  78369. };
  78370. /**
  78371. * Initializes the controllers and their meshes
  78372. */
  78373. WebVRFreeCamera.prototype.initControllers = function () {
  78374. var _this = this;
  78375. this.controllers = [];
  78376. var manager = this.getScene().gamepadManager;
  78377. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78378. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78379. var webVrController = gamepad;
  78380. if (webVrController.defaultModel) {
  78381. webVrController.defaultModel.setEnabled(false);
  78382. }
  78383. if (webVrController.hand === "right") {
  78384. _this._rightController = null;
  78385. }
  78386. if (webVrController.hand === "left") {
  78387. _this._rightController = null;
  78388. }
  78389. var controllerIndex = _this.controllers.indexOf(webVrController);
  78390. if (controllerIndex !== -1) {
  78391. _this.controllers.splice(controllerIndex, 1);
  78392. }
  78393. }
  78394. });
  78395. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78396. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78397. var webVrController_1 = gamepad;
  78398. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78399. if (_this.webVROptions.controllerMeshes) {
  78400. if (webVrController_1.defaultModel) {
  78401. webVrController_1.defaultModel.setEnabled(true);
  78402. }
  78403. else {
  78404. // Load the meshes
  78405. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78406. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78407. if (_this.webVROptions.defaultLightingOnControllers) {
  78408. if (!_this._lightOnControllers) {
  78409. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78410. }
  78411. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78412. var children = mesh.getChildren();
  78413. if (children.length !== 0) {
  78414. children.forEach(function (mesh) {
  78415. light.includedOnlyMeshes.push(mesh);
  78416. activateLightOnSubMeshes_1(mesh, light);
  78417. });
  78418. }
  78419. };
  78420. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78421. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78422. }
  78423. });
  78424. }
  78425. }
  78426. webVrController_1.attachToPoseControlledCamera(_this);
  78427. // since this is async - sanity check. Is the controller already stored?
  78428. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78429. //add to the controllers array
  78430. _this.controllers.push(webVrController_1);
  78431. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78432. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78433. // So we're overriding setting left & right manually to be sure
  78434. var firstViveWandDetected = false;
  78435. for (var i = 0; i < _this.controllers.length; i++) {
  78436. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78437. if (!firstViveWandDetected) {
  78438. firstViveWandDetected = true;
  78439. _this.controllers[i].hand = "left";
  78440. }
  78441. else {
  78442. _this.controllers[i].hand = "right";
  78443. }
  78444. }
  78445. }
  78446. //did we find enough controllers? Great! let the developer know.
  78447. if (_this.controllers.length >= 2) {
  78448. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78449. }
  78450. }
  78451. }
  78452. });
  78453. };
  78454. return WebVRFreeCamera;
  78455. }(BABYLON.FreeCamera));
  78456. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78457. })(BABYLON || (BABYLON = {}));
  78458. //# sourceMappingURL=babylon.webVRCamera.js.map
  78459. var BABYLON;
  78460. (function (BABYLON) {
  78461. // We're mainly based on the logic defined into the FreeCamera code
  78462. /**
  78463. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78464. * being tilted forward or back and left or right.
  78465. */
  78466. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78467. __extends(DeviceOrientationCamera, _super);
  78468. /**
  78469. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78470. * @param name The name of the camera
  78471. * @param position The start position camera
  78472. * @param scene The scene the camera belongs to
  78473. */
  78474. function DeviceOrientationCamera(name, position, scene) {
  78475. var _this = _super.call(this, name, position, scene) || this;
  78476. _this._quaternionCache = new BABYLON.Quaternion();
  78477. _this.inputs.addDeviceOrientation();
  78478. return _this;
  78479. }
  78480. /**
  78481. * Gets the current instance class name ("DeviceOrientationCamera").
  78482. * This helps avoiding instanceof at run time.
  78483. * @returns the class name
  78484. */
  78485. DeviceOrientationCamera.prototype.getClassName = function () {
  78486. return "DeviceOrientationCamera";
  78487. };
  78488. /**
  78489. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78490. */
  78491. DeviceOrientationCamera.prototype._checkInputs = function () {
  78492. _super.prototype._checkInputs.call(this);
  78493. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78494. if (this._initialQuaternion) {
  78495. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78496. }
  78497. };
  78498. /**
  78499. * Reset the camera to its default orientation on the specified axis only.
  78500. * @param axis The axis to reset
  78501. */
  78502. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78503. var _this = this;
  78504. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78505. //can only work if this camera has a rotation quaternion already.
  78506. if (!this.rotationQuaternion)
  78507. return;
  78508. if (!this._initialQuaternion) {
  78509. this._initialQuaternion = new BABYLON.Quaternion();
  78510. }
  78511. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78512. ['x', 'y', 'z'].forEach(function (axisName) {
  78513. if (!axis[axisName]) {
  78514. _this._initialQuaternion[axisName] = 0;
  78515. }
  78516. else {
  78517. _this._initialQuaternion[axisName] *= -1;
  78518. }
  78519. });
  78520. this._initialQuaternion.normalize();
  78521. //force rotation update
  78522. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78523. };
  78524. return DeviceOrientationCamera;
  78525. }(BABYLON.FreeCamera));
  78526. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78527. })(BABYLON || (BABYLON = {}));
  78528. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78529. var BABYLON;
  78530. (function (BABYLON) {
  78531. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78532. __extends(VRDeviceOrientationFreeCamera, _super);
  78533. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78534. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78535. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78536. var _this = _super.call(this, name, position, scene) || this;
  78537. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78538. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78539. return _this;
  78540. }
  78541. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78542. return "VRDeviceOrientationFreeCamera";
  78543. };
  78544. return VRDeviceOrientationFreeCamera;
  78545. }(BABYLON.DeviceOrientationCamera));
  78546. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78547. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78548. __extends(VRDeviceOrientationGamepadCamera, _super);
  78549. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78550. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78551. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78552. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78553. _this.inputs.addGamepad();
  78554. return _this;
  78555. }
  78556. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78557. return "VRDeviceOrientationGamepadCamera";
  78558. };
  78559. return VRDeviceOrientationGamepadCamera;
  78560. }(VRDeviceOrientationFreeCamera));
  78561. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78562. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78563. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78564. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78565. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78566. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78567. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78568. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78569. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78570. _this.inputs.addVRDeviceOrientation();
  78571. return _this;
  78572. }
  78573. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78574. return "VRDeviceOrientationArcRotateCamera";
  78575. };
  78576. return VRDeviceOrientationArcRotateCamera;
  78577. }(BABYLON.ArcRotateCamera));
  78578. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78579. })(BABYLON || (BABYLON = {}));
  78580. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78581. var BABYLON;
  78582. (function (BABYLON) {
  78583. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78584. __extends(AnaglyphFreeCamera, _super);
  78585. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78586. var _this = _super.call(this, name, position, scene) || this;
  78587. _this.interaxialDistance = interaxialDistance;
  78588. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78589. return _this;
  78590. }
  78591. AnaglyphFreeCamera.prototype.getClassName = function () {
  78592. return "AnaglyphFreeCamera";
  78593. };
  78594. return AnaglyphFreeCamera;
  78595. }(BABYLON.FreeCamera));
  78596. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78597. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78598. __extends(AnaglyphArcRotateCamera, _super);
  78599. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78600. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78601. _this.interaxialDistance = interaxialDistance;
  78602. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78603. return _this;
  78604. }
  78605. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78606. return "AnaglyphArcRotateCamera";
  78607. };
  78608. return AnaglyphArcRotateCamera;
  78609. }(BABYLON.ArcRotateCamera));
  78610. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78611. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78612. __extends(AnaglyphGamepadCamera, _super);
  78613. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78614. var _this = _super.call(this, name, position, scene) || this;
  78615. _this.interaxialDistance = interaxialDistance;
  78616. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78617. return _this;
  78618. }
  78619. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78620. return "AnaglyphGamepadCamera";
  78621. };
  78622. return AnaglyphGamepadCamera;
  78623. }(BABYLON.GamepadCamera));
  78624. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78625. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78626. __extends(AnaglyphUniversalCamera, _super);
  78627. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78628. var _this = _super.call(this, name, position, scene) || this;
  78629. _this.interaxialDistance = interaxialDistance;
  78630. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78631. return _this;
  78632. }
  78633. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78634. return "AnaglyphUniversalCamera";
  78635. };
  78636. return AnaglyphUniversalCamera;
  78637. }(BABYLON.UniversalCamera));
  78638. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78639. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78640. __extends(StereoscopicFreeCamera, _super);
  78641. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78642. var _this = _super.call(this, name, position, scene) || this;
  78643. _this.interaxialDistance = interaxialDistance;
  78644. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78645. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78646. return _this;
  78647. }
  78648. StereoscopicFreeCamera.prototype.getClassName = function () {
  78649. return "StereoscopicFreeCamera";
  78650. };
  78651. return StereoscopicFreeCamera;
  78652. }(BABYLON.FreeCamera));
  78653. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78654. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78655. __extends(StereoscopicArcRotateCamera, _super);
  78656. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78657. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78658. _this.interaxialDistance = interaxialDistance;
  78659. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78660. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78661. return _this;
  78662. }
  78663. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78664. return "StereoscopicArcRotateCamera";
  78665. };
  78666. return StereoscopicArcRotateCamera;
  78667. }(BABYLON.ArcRotateCamera));
  78668. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78669. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78670. __extends(StereoscopicGamepadCamera, _super);
  78671. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78672. var _this = _super.call(this, name, position, scene) || this;
  78673. _this.interaxialDistance = interaxialDistance;
  78674. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78675. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78676. return _this;
  78677. }
  78678. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78679. return "StereoscopicGamepadCamera";
  78680. };
  78681. return StereoscopicGamepadCamera;
  78682. }(BABYLON.GamepadCamera));
  78683. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78684. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78685. __extends(StereoscopicUniversalCamera, _super);
  78686. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78687. var _this = _super.call(this, name, position, scene) || this;
  78688. _this.interaxialDistance = interaxialDistance;
  78689. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78690. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78691. return _this;
  78692. }
  78693. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78694. return "StereoscopicUniversalCamera";
  78695. };
  78696. return StereoscopicUniversalCamera;
  78697. }(BABYLON.UniversalCamera));
  78698. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78699. })(BABYLON || (BABYLON = {}));
  78700. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78701. var BABYLON;
  78702. (function (BABYLON) {
  78703. /**
  78704. * Helps to quickly add VR support to an existing scene.
  78705. * See http://doc.babylonjs.com/how_to/webvr_helper
  78706. */
  78707. var VRExperienceHelper = /** @class */ (function () {
  78708. /**
  78709. * Instantiates a VRExperienceHelper.
  78710. * Helps to quickly add VR support to an existing scene.
  78711. * @param scene The scene the VRExperienceHelper belongs to.
  78712. * @param webVROptions Options to modify the vr experience helper's behavior.
  78713. */
  78714. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78715. if (webVROptions === void 0) { webVROptions = {}; }
  78716. var _this = this;
  78717. this.webVROptions = webVROptions;
  78718. // Can the system support WebVR, even if a headset isn't plugged in?
  78719. this._webVRsupported = false;
  78720. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78721. this._webVRready = false;
  78722. // Are we waiting for the requestPresent callback to complete?
  78723. this._webVRrequesting = false;
  78724. // Are we presenting to the headset right now?
  78725. this._webVRpresenting = false;
  78726. // Are we presenting in the fullscreen fallback?
  78727. this._fullscreenVRpresenting = false;
  78728. /**
  78729. * Observable raised when entering VR.
  78730. */
  78731. this.onEnteringVRObservable = new BABYLON.Observable();
  78732. /**
  78733. * Observable raised when exiting VR.
  78734. */
  78735. this.onExitingVRObservable = new BABYLON.Observable();
  78736. /**
  78737. * Observable raised when controller mesh is loaded.
  78738. */
  78739. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78740. this._useCustomVRButton = false;
  78741. this._teleportationRequested = false;
  78742. this._teleportationEnabledOnLeftController = false;
  78743. this._teleportationEnabledOnRightController = false;
  78744. this._interactionsEnabledOnLeftController = false;
  78745. this._interactionsEnabledOnRightController = false;
  78746. this._leftControllerReady = false;
  78747. this._rightControllerReady = false;
  78748. this._floorMeshesCollection = [];
  78749. this._teleportationAllowed = false;
  78750. this._rotationAllowed = true;
  78751. this._teleportationRequestInitiated = false;
  78752. this._teleportationBackRequestInitiated = false;
  78753. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78754. this._rotationRightAsked = false;
  78755. this._rotationLeftAsked = false;
  78756. this._isDefaultTeleportationTarget = true;
  78757. this._teleportationFillColor = "#444444";
  78758. this._teleportationBorderColor = "#FFFFFF";
  78759. this._rotationAngle = 0;
  78760. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78761. this._padSensibilityUp = 0.65;
  78762. this._padSensibilityDown = 0.35;
  78763. /**
  78764. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78765. */
  78766. this.onNewMeshSelected = new BABYLON.Observable();
  78767. /**
  78768. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78769. */
  78770. this.onNewMeshPicked = new BABYLON.Observable();
  78771. /**
  78772. * Observable raised before camera teleportation
  78773. */
  78774. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78775. /**
  78776. * Observable raised after camera teleportation
  78777. */
  78778. this.onAfterCameraTeleport = new BABYLON.Observable();
  78779. /**
  78780. * Observable raised when current selected mesh gets unselected
  78781. */
  78782. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78783. /**
  78784. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78785. */
  78786. this.teleportationEnabled = true;
  78787. this._pointerDownOnMeshAsked = false;
  78788. this._isActionableMesh = false;
  78789. this._teleportationInitialized = false;
  78790. this._interactionsEnabled = false;
  78791. this._interactionsRequested = false;
  78792. this._displayGaze = true;
  78793. this._displayLaserPointer = true;
  78794. this._dpadPressed = true;
  78795. this._onResize = function () {
  78796. _this.moveButtonToBottomRight();
  78797. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78798. _this.exitVR();
  78799. }
  78800. };
  78801. this._onFullscreenChange = function () {
  78802. if (document.fullscreen !== undefined) {
  78803. _this._fullscreenVRpresenting = document.fullscreen;
  78804. }
  78805. else if (document.mozFullScreen !== undefined) {
  78806. _this._fullscreenVRpresenting = document.mozFullScreen;
  78807. }
  78808. else if (document.webkitIsFullScreen !== undefined) {
  78809. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78810. }
  78811. else if (document.msIsFullScreen !== undefined) {
  78812. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78813. }
  78814. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78815. _this.exitVR();
  78816. if (!_this._useCustomVRButton) {
  78817. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78818. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78819. }
  78820. }
  78821. };
  78822. this.beforeRender = function () {
  78823. _this._castRayAndSelectObject();
  78824. };
  78825. this._onNewGamepadConnected = function (gamepad) {
  78826. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78827. if (gamepad.leftStick) {
  78828. gamepad.onleftstickchanged(function (stickValues) {
  78829. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78830. // Listening to classic/xbox gamepad only if no VR controller is active
  78831. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78832. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78833. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78834. _this._checkTeleportWithRay(stickValues);
  78835. _this._checkTeleportBackwards(stickValues);
  78836. }
  78837. }
  78838. });
  78839. }
  78840. if (gamepad.rightStick) {
  78841. gamepad.onrightstickchanged(function (stickValues) {
  78842. if (_this._teleportationInitialized) {
  78843. _this._checkRotate(stickValues);
  78844. }
  78845. });
  78846. }
  78847. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78848. gamepad.onbuttondown(function (buttonPressed) {
  78849. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78850. _this._selectionPointerDown();
  78851. }
  78852. });
  78853. gamepad.onbuttonup(function (buttonPressed) {
  78854. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78855. _this._selectionPointerUp();
  78856. }
  78857. });
  78858. }
  78859. }
  78860. else {
  78861. var webVRController = gamepad;
  78862. _this._tryEnableInteractionOnController(webVRController);
  78863. }
  78864. };
  78865. // 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
  78866. this._tryEnableInteractionOnController = function (webVRController) {
  78867. if (webVRController.hand === "left") {
  78868. _this._leftControllerReady = true;
  78869. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78870. _this._enableInteractionOnController(webVRController);
  78871. }
  78872. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78873. _this._enableTeleportationOnController(webVRController);
  78874. }
  78875. }
  78876. if (webVRController.hand === "right") {
  78877. _this._rightControllerReady = true;
  78878. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78879. _this._enableInteractionOnController(webVRController);
  78880. }
  78881. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78882. _this._enableTeleportationOnController(webVRController);
  78883. }
  78884. }
  78885. };
  78886. this._onNewGamepadDisconnected = function (gamepad) {
  78887. if (gamepad instanceof BABYLON.WebVRController) {
  78888. if (gamepad.hand === "left") {
  78889. _this._interactionsEnabledOnLeftController = false;
  78890. _this._teleportationEnabledOnLeftController = false;
  78891. _this._leftControllerReady = false;
  78892. if (_this._leftLaserPointer) {
  78893. _this._leftLaserPointer.dispose();
  78894. }
  78895. }
  78896. if (gamepad.hand === "right") {
  78897. _this._interactionsEnabledOnRightController = false;
  78898. _this._teleportationEnabledOnRightController = false;
  78899. _this._rightControllerReady = false;
  78900. if (_this._rightLaserPointer) {
  78901. _this._rightLaserPointer.dispose();
  78902. }
  78903. }
  78904. }
  78905. };
  78906. this._workingVector = BABYLON.Vector3.Zero();
  78907. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78908. this._workingMatrix = BABYLON.Matrix.Identity();
  78909. this._scene = scene;
  78910. this._canvas = scene.getEngine().getRenderingCanvas();
  78911. // Parse options
  78912. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78913. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78914. }
  78915. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78916. webVROptions.createDeviceOrientationCamera = true;
  78917. }
  78918. if (webVROptions.defaultHeight === undefined) {
  78919. webVROptions.defaultHeight = 1.7;
  78920. }
  78921. if (webVROptions.useCustomVRButton) {
  78922. this._useCustomVRButton = true;
  78923. if (webVROptions.customVRButton) {
  78924. this._btnVR = webVROptions.customVRButton;
  78925. }
  78926. }
  78927. if (webVROptions.rayLength) {
  78928. this._rayLength = webVROptions.rayLength;
  78929. }
  78930. this._defaultHeight = webVROptions.defaultHeight;
  78931. // Set position
  78932. if (this._scene.activeCamera) {
  78933. this._position = this._scene.activeCamera.position.clone();
  78934. }
  78935. else {
  78936. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78937. }
  78938. // Set non-vr camera
  78939. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78940. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78941. // Copy data from existing camera
  78942. if (this._scene.activeCamera) {
  78943. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78944. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78945. // Set rotation from previous camera
  78946. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78947. var targetCamera = this._scene.activeCamera;
  78948. if (targetCamera.rotationQuaternion) {
  78949. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78950. }
  78951. else {
  78952. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78953. }
  78954. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78955. }
  78956. }
  78957. this._scene.activeCamera = this._deviceOrientationCamera;
  78958. if (this._canvas) {
  78959. this._scene.activeCamera.attachControl(this._canvas);
  78960. }
  78961. }
  78962. else {
  78963. this._existingCamera = this._scene.activeCamera;
  78964. }
  78965. // Create VR cameras
  78966. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78967. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78968. }
  78969. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78970. this._webVRCamera.useStandingMatrix();
  78971. // Create default button
  78972. if (!this._useCustomVRButton) {
  78973. this._btnVR = document.createElement("BUTTON");
  78974. this._btnVR.className = "babylonVRicon";
  78975. this._btnVR.id = "babylonVRiconbtn";
  78976. this._btnVR.title = "Click to switch to VR";
  78977. 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) }";
  78978. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78979. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78980. // css += ".babylonVRicon.vrdisplaysupported { }";
  78981. // css += ".babylonVRicon.vrdisplayready { }";
  78982. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78983. var style = document.createElement('style');
  78984. style.appendChild(document.createTextNode(css));
  78985. document.getElementsByTagName('head')[0].appendChild(style);
  78986. this.moveButtonToBottomRight();
  78987. }
  78988. // VR button click event
  78989. if (this._btnVR) {
  78990. this._btnVR.addEventListener("click", function () {
  78991. if (!_this.isInVRMode) {
  78992. _this.enterVR();
  78993. }
  78994. else {
  78995. _this.exitVR();
  78996. }
  78997. });
  78998. }
  78999. // Window events
  79000. window.addEventListener("resize", this._onResize);
  79001. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79002. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79003. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79004. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79005. // Display vr button when headset is connected
  79006. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79007. this.displayVRButton();
  79008. }
  79009. else {
  79010. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79011. if (e.vrDisplay) {
  79012. _this.displayVRButton();
  79013. }
  79014. });
  79015. }
  79016. // Exiting VR mode using 'ESC' key on desktop
  79017. this._onKeyDown = function (event) {
  79018. if (event.keyCode === 27 && _this.isInVRMode) {
  79019. _this.exitVR();
  79020. }
  79021. };
  79022. document.addEventListener("keydown", this._onKeyDown);
  79023. // Exiting VR mode double tapping the touch screen
  79024. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79025. if (_this.isInVRMode) {
  79026. _this.exitVR();
  79027. if (_this._fullscreenVRpresenting) {
  79028. _this._scene.getEngine().switchFullscreen(true);
  79029. }
  79030. }
  79031. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79032. // Listen for WebVR display changes
  79033. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79034. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79035. this._onVRRequestPresentStart = function () {
  79036. _this._webVRrequesting = true;
  79037. _this.updateButtonVisibility();
  79038. };
  79039. this._onVRRequestPresentComplete = function (success) {
  79040. _this._webVRrequesting = false;
  79041. _this.updateButtonVisibility();
  79042. };
  79043. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  79044. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  79045. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  79046. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79047. scene.onDisposeObservable.add(function () {
  79048. _this.dispose();
  79049. });
  79050. // Gamepad connection events
  79051. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  79052. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  79053. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  79054. this.updateButtonVisibility();
  79055. //create easing functions
  79056. this._circleEase = new BABYLON.CircleEase();
  79057. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79058. }
  79059. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  79060. /** Return this.onEnteringVRObservable
  79061. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  79062. */
  79063. get: function () {
  79064. return this.onEnteringVRObservable;
  79065. },
  79066. enumerable: true,
  79067. configurable: true
  79068. });
  79069. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  79070. /** Return this.onExitingVRObservable
  79071. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  79072. */
  79073. get: function () {
  79074. return this.onExitingVRObservable;
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  79080. /** Return this.onControllerMeshLoadedObservable
  79081. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  79082. */
  79083. get: function () {
  79084. return this.onControllerMeshLoadedObservable;
  79085. },
  79086. enumerable: true,
  79087. configurable: true
  79088. });
  79089. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  79090. /**
  79091. * The mesh used to display where the user is going to teleport.
  79092. */
  79093. get: function () {
  79094. return this._teleportationTarget;
  79095. },
  79096. /**
  79097. * Sets the mesh to be used to display where the user is going to teleport.
  79098. */
  79099. set: function (value) {
  79100. if (value) {
  79101. value.name = "teleportationTarget";
  79102. this._isDefaultTeleportationTarget = false;
  79103. this._teleportationTarget = value;
  79104. }
  79105. },
  79106. enumerable: true,
  79107. configurable: true
  79108. });
  79109. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79110. /**
  79111. * The mesh used to display where the user is selecting.
  79112. */
  79113. get: function () {
  79114. return this._gazeTracker;
  79115. },
  79116. /**
  79117. * Sets the mesh to be used to display where the user is selecting.
  79118. */
  79119. set: function (value) {
  79120. if (value) {
  79121. this._gazeTracker = value;
  79122. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79123. this._gazeTracker.isPickable = false;
  79124. this._gazeTracker.isVisible = false;
  79125. }
  79126. },
  79127. enumerable: true,
  79128. configurable: true
  79129. });
  79130. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79131. /**
  79132. * If the ray of the gaze should be displayed.
  79133. */
  79134. get: function () {
  79135. return this._displayGaze;
  79136. },
  79137. /**
  79138. * Sets if the ray of the gaze should be displayed.
  79139. */
  79140. set: function (value) {
  79141. this._displayGaze = value;
  79142. if (!value) {
  79143. this._gazeTracker.isVisible = false;
  79144. }
  79145. },
  79146. enumerable: true,
  79147. configurable: true
  79148. });
  79149. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79150. /**
  79151. * If the ray of the LaserPointer should be displayed.
  79152. */
  79153. get: function () {
  79154. return this._displayLaserPointer;
  79155. },
  79156. /**
  79157. * Sets if the ray of the LaserPointer should be displayed.
  79158. */
  79159. set: function (value) {
  79160. this._displayLaserPointer = value;
  79161. if (!value) {
  79162. if (this._rightLaserPointer) {
  79163. this._rightLaserPointer.isVisible = false;
  79164. }
  79165. if (this._leftLaserPointer) {
  79166. this._leftLaserPointer.isVisible = false;
  79167. }
  79168. }
  79169. else {
  79170. if (this._rightLaserPointer) {
  79171. this._rightLaserPointer.isVisible = true;
  79172. }
  79173. else if (this._leftLaserPointer) {
  79174. this._leftLaserPointer.isVisible = true;
  79175. }
  79176. }
  79177. },
  79178. enumerable: true,
  79179. configurable: true
  79180. });
  79181. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79182. /**
  79183. * The deviceOrientationCamera used as the camera when not in VR.
  79184. */
  79185. get: function () {
  79186. return this._deviceOrientationCamera;
  79187. },
  79188. enumerable: true,
  79189. configurable: true
  79190. });
  79191. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79192. /**
  79193. * Based on the current WebVR support, returns the current VR camera used.
  79194. */
  79195. get: function () {
  79196. if (this._webVRready) {
  79197. return this._webVRCamera;
  79198. }
  79199. else {
  79200. return this._scene.activeCamera;
  79201. }
  79202. },
  79203. enumerable: true,
  79204. configurable: true
  79205. });
  79206. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79207. /**
  79208. * The webVRCamera which is used when in VR.
  79209. */
  79210. get: function () {
  79211. return this._webVRCamera;
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79217. /**
  79218. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79219. */
  79220. get: function () {
  79221. return this._vrDeviceOrientationCamera;
  79222. },
  79223. enumerable: true,
  79224. configurable: true
  79225. });
  79226. // Raised when one of the controller has loaded successfully its associated default mesh
  79227. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79228. this._tryEnableInteractionOnController(webVRController);
  79229. try {
  79230. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79231. }
  79232. catch (err) {
  79233. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79234. }
  79235. };
  79236. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79237. /**
  79238. * Gets a value indicating if we are currently in VR mode.
  79239. */
  79240. get: function () {
  79241. return this._webVRpresenting || this._fullscreenVRpresenting;
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79247. var vrDisplay = this._scene.getEngine().getVRDevice();
  79248. if (vrDisplay) {
  79249. var wasPresenting = this._webVRpresenting;
  79250. // A VR display is connected
  79251. this._webVRpresenting = vrDisplay.isPresenting;
  79252. if (wasPresenting && !this._webVRpresenting)
  79253. this.exitVR();
  79254. }
  79255. else {
  79256. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79257. }
  79258. this.updateButtonVisibility();
  79259. };
  79260. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79261. this._webVRsupported = eventArgs.vrSupported;
  79262. this._webVRready = !!eventArgs.vrDisplay;
  79263. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79264. this.updateButtonVisibility();
  79265. };
  79266. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79267. if (this._canvas && !this._useCustomVRButton) {
  79268. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79269. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79270. }
  79271. };
  79272. VRExperienceHelper.prototype.displayVRButton = function () {
  79273. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79274. document.body.appendChild(this._btnVR);
  79275. this._btnVRDisplayed = true;
  79276. }
  79277. };
  79278. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79279. if (!this._btnVR || this._useCustomVRButton) {
  79280. return;
  79281. }
  79282. this._btnVR.className = "babylonVRicon";
  79283. if (this.isInVRMode) {
  79284. this._btnVR.className += " vrdisplaypresenting";
  79285. }
  79286. else {
  79287. if (this._webVRready)
  79288. this._btnVR.className += " vrdisplayready";
  79289. if (this._webVRsupported)
  79290. this._btnVR.className += " vrdisplaysupported";
  79291. if (this._webVRrequesting)
  79292. this._btnVR.className += " vrdisplayrequesting";
  79293. }
  79294. };
  79295. /**
  79296. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79297. * Otherwise, will use the fullscreen API.
  79298. */
  79299. VRExperienceHelper.prototype.enterVR = function () {
  79300. if (this.onEnteringVRObservable) {
  79301. try {
  79302. this.onEnteringVRObservable.notifyObservers(this);
  79303. }
  79304. catch (err) {
  79305. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79306. }
  79307. }
  79308. if (this._scene.activeCamera) {
  79309. this._position = this._scene.activeCamera.position.clone();
  79310. // make sure that we return to the last active camera
  79311. this._existingCamera = this._scene.activeCamera;
  79312. }
  79313. if (this._webVRrequesting)
  79314. return;
  79315. // If WebVR is supported and a headset is connected
  79316. if (this._webVRready) {
  79317. if (!this._webVRpresenting) {
  79318. this._webVRCamera.position = this._position;
  79319. this._scene.activeCamera = this._webVRCamera;
  79320. }
  79321. }
  79322. else if (this._vrDeviceOrientationCamera) {
  79323. this._vrDeviceOrientationCamera.position = this._position;
  79324. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79325. this._scene.getEngine().switchFullscreen(true);
  79326. this.updateButtonVisibility();
  79327. }
  79328. if (this._scene.activeCamera && this._canvas) {
  79329. this._scene.activeCamera.attachControl(this._canvas);
  79330. }
  79331. if (this._interactionsEnabled) {
  79332. this._scene.registerBeforeRender(this.beforeRender);
  79333. }
  79334. };
  79335. /**
  79336. * Attempt to exit VR, or fullscreen.
  79337. */
  79338. VRExperienceHelper.prototype.exitVR = function () {
  79339. if (this.onExitingVRObservable) {
  79340. try {
  79341. this.onExitingVRObservable.notifyObservers(this);
  79342. }
  79343. catch (err) {
  79344. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79345. }
  79346. }
  79347. if (this._webVRpresenting) {
  79348. this._scene.getEngine().disableVR();
  79349. }
  79350. if (this._scene.activeCamera) {
  79351. this._position = this._scene.activeCamera.position.clone();
  79352. }
  79353. if (this._deviceOrientationCamera) {
  79354. this._deviceOrientationCamera.position = this._position;
  79355. this._scene.activeCamera = this._deviceOrientationCamera;
  79356. if (this._canvas) {
  79357. this._scene.activeCamera.attachControl(this._canvas);
  79358. }
  79359. }
  79360. else if (this._existingCamera) {
  79361. this._existingCamera.position = this._position;
  79362. this._scene.activeCamera = this._existingCamera;
  79363. }
  79364. this.updateButtonVisibility();
  79365. if (this._interactionsEnabled) {
  79366. this._scene.unregisterBeforeRender(this.beforeRender);
  79367. }
  79368. };
  79369. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79370. /**
  79371. * The position of the vr experience helper.
  79372. */
  79373. get: function () {
  79374. return this._position;
  79375. },
  79376. /**
  79377. * Sets the position of the vr experience helper.
  79378. */
  79379. set: function (value) {
  79380. this._position = value;
  79381. if (this._scene.activeCamera) {
  79382. this._scene.activeCamera.position = value;
  79383. }
  79384. },
  79385. enumerable: true,
  79386. configurable: true
  79387. });
  79388. /**
  79389. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79390. */
  79391. VRExperienceHelper.prototype.enableInteractions = function () {
  79392. var _this = this;
  79393. if (!this._interactionsEnabled) {
  79394. this._interactionsRequested = true;
  79395. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79396. this._enableInteractionOnController(this._webVRCamera.leftController);
  79397. }
  79398. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79399. this._enableInteractionOnController(this._webVRCamera.rightController);
  79400. }
  79401. if (!this._gazeTracker) {
  79402. this._createGazeTracker();
  79403. }
  79404. this.raySelectionPredicate = function (mesh) {
  79405. return mesh.isVisible;
  79406. };
  79407. this.meshSelectionPredicate = function (mesh) {
  79408. return true;
  79409. };
  79410. this._raySelectionPredicate = function (mesh) {
  79411. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79412. && mesh.name.indexOf("teleportationTarget") === -1
  79413. && mesh.name.indexOf("torusTeleportation") === -1
  79414. && mesh.name.indexOf("laserPointer") === -1)) {
  79415. return _this.raySelectionPredicate(mesh);
  79416. }
  79417. return false;
  79418. };
  79419. this._interactionsEnabled = true;
  79420. }
  79421. };
  79422. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79423. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79424. if (this._floorMeshesCollection[i].id === mesh.id) {
  79425. return true;
  79426. }
  79427. }
  79428. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79429. return true;
  79430. }
  79431. return false;
  79432. };
  79433. /**
  79434. * Adds a floor mesh to be used for teleportation.
  79435. * @param floorMesh the mesh to be used for teleportation.
  79436. */
  79437. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79438. if (!this._floorMeshesCollection) {
  79439. return;
  79440. }
  79441. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79442. return;
  79443. }
  79444. this._floorMeshesCollection.push(floorMesh);
  79445. };
  79446. /**
  79447. * Removes a floor mesh from being used for teleportation.
  79448. * @param floorMesh the mesh to be removed.
  79449. */
  79450. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79451. if (!this._floorMeshesCollection) {
  79452. return;
  79453. }
  79454. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79455. if (meshIndex !== -1) {
  79456. this._floorMeshesCollection.splice(meshIndex, 1);
  79457. }
  79458. };
  79459. /**
  79460. * Enables interactions and teleportation using the VR controllers and gaze.
  79461. * @param vrTeleportationOptions options to modify teleportation behavior.
  79462. */
  79463. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79464. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79465. if (!this._teleportationInitialized) {
  79466. this._teleportationRequested = true;
  79467. this.enableInteractions();
  79468. if (vrTeleportationOptions.floorMeshName) {
  79469. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79470. }
  79471. if (vrTeleportationOptions.floorMeshes) {
  79472. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79473. }
  79474. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79475. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79476. }
  79477. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79478. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79479. }
  79480. // Creates an image processing post process for the vignette not relying
  79481. // on the main scene configuration for image processing to reduce setup and spaces
  79482. // (gamma/linear) conflicts.
  79483. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79484. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79485. imageProcessingConfiguration.vignetteEnabled = true;
  79486. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79487. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79488. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79489. this._teleportationInitialized = true;
  79490. if (this._isDefaultTeleportationTarget) {
  79491. this._createTeleportationCircles();
  79492. }
  79493. }
  79494. };
  79495. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79496. var _this = this;
  79497. var controllerMesh = webVRController.mesh;
  79498. if (controllerMesh) {
  79499. var makeNotPick = function (root) {
  79500. root.name += " laserPointer";
  79501. root.getChildMeshes().forEach(function (c) {
  79502. makeNotPick(c);
  79503. });
  79504. };
  79505. makeNotPick(controllerMesh);
  79506. var childMeshes = controllerMesh.getChildMeshes();
  79507. for (var i = 0; i < childMeshes.length; i++) {
  79508. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79509. controllerMesh = childMeshes[i];
  79510. break;
  79511. }
  79512. }
  79513. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79514. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79515. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79516. laserPointerMaterial.alpha = 0.6;
  79517. laserPointer.material = laserPointerMaterial;
  79518. laserPointer.rotation.x = Math.PI / 2;
  79519. laserPointer.parent = controllerMesh;
  79520. laserPointer.position.z = -0.5;
  79521. laserPointer.isVisible = false;
  79522. if (webVRController.hand === "left") {
  79523. this._leftLaserPointer = laserPointer;
  79524. this._interactionsEnabledOnLeftController = true;
  79525. if (!this._rightLaserPointer) {
  79526. this._leftLaserPointer.isVisible = true;
  79527. }
  79528. }
  79529. else {
  79530. this._rightLaserPointer = laserPointer;
  79531. this._interactionsEnabledOnRightController = true;
  79532. if (!this._leftLaserPointer) {
  79533. this._rightLaserPointer.isVisible = true;
  79534. }
  79535. }
  79536. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79537. // Enabling / disabling laserPointer
  79538. if (_this._displayLaserPointer && stateObject.value === 1) {
  79539. laserPointer.isVisible = !laserPointer.isVisible;
  79540. // Laser pointer can only be active on left or right, not both at the same time
  79541. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79542. _this._rightLaserPointer.isVisible = false;
  79543. }
  79544. else if (_this._leftLaserPointer) {
  79545. _this._leftLaserPointer.isVisible = false;
  79546. }
  79547. }
  79548. });
  79549. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79550. if (!_this._pointerDownOnMeshAsked) {
  79551. if (stateObject.value > _this._padSensibilityUp) {
  79552. _this._selectionPointerDown();
  79553. }
  79554. }
  79555. else if (stateObject.value < _this._padSensibilityDown) {
  79556. _this._selectionPointerUp();
  79557. }
  79558. });
  79559. }
  79560. };
  79561. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79562. if (webVRController === void 0) { webVRController = null; }
  79563. if (!this._teleportationRequestInitiated) {
  79564. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79565. if (webVRController) {
  79566. // If laser pointer wasn't enabled yet
  79567. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79568. this._leftLaserPointer.isVisible = true;
  79569. if (this._rightLaserPointer) {
  79570. this._rightLaserPointer.isVisible = false;
  79571. }
  79572. }
  79573. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79574. this._rightLaserPointer.isVisible = true;
  79575. if (this._leftLaserPointer) {
  79576. this._leftLaserPointer.isVisible = false;
  79577. }
  79578. }
  79579. }
  79580. this._teleportationRequestInitiated = true;
  79581. }
  79582. }
  79583. else {
  79584. // Listening to the proper controller values changes to confirm teleportation
  79585. if (webVRController == null
  79586. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79587. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79588. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79589. if (this._teleportationAllowed) {
  79590. this._teleportationAllowed = false;
  79591. this._teleportCamera();
  79592. }
  79593. this._teleportationRequestInitiated = false;
  79594. }
  79595. }
  79596. }
  79597. };
  79598. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79599. this._pointerDownOnMeshAsked = true;
  79600. if (this._currentMeshSelected && this._currentHit) {
  79601. this._scene.simulatePointerDown(this._currentHit);
  79602. }
  79603. };
  79604. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79605. if (this._currentMeshSelected && this._currentHit) {
  79606. this._scene.simulatePointerUp(this._currentHit);
  79607. }
  79608. this._pointerDownOnMeshAsked = false;
  79609. };
  79610. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79611. // Only rotate when user is not currently selecting a teleportation location
  79612. if (this._teleportationRequestInitiated) {
  79613. return;
  79614. }
  79615. if (!this._rotationLeftAsked) {
  79616. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79617. this._rotationLeftAsked = true;
  79618. if (this._rotationAllowed) {
  79619. this._rotateCamera(false);
  79620. }
  79621. }
  79622. }
  79623. else {
  79624. if (stateObject.x > -this._padSensibilityDown) {
  79625. this._rotationLeftAsked = false;
  79626. }
  79627. }
  79628. if (!this._rotationRightAsked) {
  79629. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79630. this._rotationRightAsked = true;
  79631. if (this._rotationAllowed) {
  79632. this._rotateCamera(true);
  79633. }
  79634. }
  79635. }
  79636. else {
  79637. if (stateObject.x < this._padSensibilityDown) {
  79638. this._rotationRightAsked = false;
  79639. }
  79640. }
  79641. };
  79642. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79643. // Only teleport backwards when user is not currently selecting a teleportation location
  79644. if (this._teleportationRequestInitiated) {
  79645. return;
  79646. }
  79647. // Teleport backwards
  79648. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79649. if (!this._teleportationBackRequestInitiated) {
  79650. if (!this.currentVRCamera) {
  79651. return;
  79652. }
  79653. // Get rotation and position of the current camera
  79654. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79655. var position = this.currentVRCamera.position;
  79656. // If the camera has device position, use that instead
  79657. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79658. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79659. position = this.currentVRCamera.devicePosition;
  79660. }
  79661. // Get matrix with only the y rotation of the device rotation
  79662. rotation.toEulerAnglesToRef(this._workingVector);
  79663. this._workingVector.z = 0;
  79664. this._workingVector.x = 0;
  79665. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79666. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79667. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79668. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79669. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79670. var ray = new BABYLON.Ray(position, this._workingVector);
  79671. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79672. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79673. this._teleportCamera(hit.pickedPoint);
  79674. }
  79675. this._teleportationBackRequestInitiated = true;
  79676. }
  79677. }
  79678. else {
  79679. this._teleportationBackRequestInitiated = false;
  79680. }
  79681. };
  79682. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79683. var _this = this;
  79684. var controllerMesh = webVRController.mesh;
  79685. if (controllerMesh) {
  79686. if (webVRController.hand === "left") {
  79687. if (!this._interactionsEnabledOnLeftController) {
  79688. this._enableInteractionOnController(webVRController);
  79689. }
  79690. this._teleportationEnabledOnLeftController = true;
  79691. }
  79692. else {
  79693. if (!this._interactionsEnabledOnRightController) {
  79694. this._enableInteractionOnController(webVRController);
  79695. }
  79696. this._teleportationEnabledOnRightController = true;
  79697. }
  79698. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79699. this._dpadPressed = false;
  79700. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79701. _this._dpadPressed = stateObject.pressed;
  79702. if (!_this._dpadPressed) {
  79703. _this._rotationLeftAsked = false;
  79704. _this._rotationRightAsked = false;
  79705. _this._teleportationBackRequestInitiated = false;
  79706. }
  79707. });
  79708. }
  79709. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79710. if (_this.teleportationEnabled) {
  79711. _this._checkTeleportBackwards(stateObject);
  79712. _this._checkTeleportWithRay(stateObject, webVRController);
  79713. }
  79714. _this._checkRotate(stateObject);
  79715. });
  79716. }
  79717. };
  79718. // Gaze support used to point to teleport or to interact with an object
  79719. VRExperienceHelper.prototype._createGazeTracker = function () {
  79720. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79721. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79722. this._gazeTracker.isPickable = false;
  79723. this._gazeTracker.isVisible = false;
  79724. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79725. targetMat.specularColor = BABYLON.Color3.Black();
  79726. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79727. targetMat.backFaceCulling = false;
  79728. this._gazeTracker.material = targetMat;
  79729. };
  79730. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79731. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79732. this._teleportationTarget.isPickable = false;
  79733. var length = 512;
  79734. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79735. dynamicTexture.hasAlpha = true;
  79736. var context = dynamicTexture.getContext();
  79737. var centerX = length / 2;
  79738. var centerY = length / 2;
  79739. var radius = 200;
  79740. context.beginPath();
  79741. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79742. context.fillStyle = this._teleportationFillColor;
  79743. context.fill();
  79744. context.lineWidth = 10;
  79745. context.strokeStyle = this._teleportationBorderColor;
  79746. context.stroke();
  79747. context.closePath();
  79748. dynamicTexture.update();
  79749. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79750. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79751. this._teleportationTarget.material = teleportationCircleMaterial;
  79752. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79753. torus.isPickable = false;
  79754. torus.parent = this._teleportationTarget;
  79755. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79756. var keys = [];
  79757. keys.push({
  79758. frame: 0,
  79759. value: 0
  79760. });
  79761. keys.push({
  79762. frame: 30,
  79763. value: 0.4
  79764. });
  79765. keys.push({
  79766. frame: 60,
  79767. value: 0
  79768. });
  79769. animationInnerCircle.setKeys(keys);
  79770. var easingFunction = new BABYLON.SineEase();
  79771. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79772. animationInnerCircle.setEasingFunction(easingFunction);
  79773. torus.animations = [];
  79774. torus.animations.push(animationInnerCircle);
  79775. this._scene.beginAnimation(torus, 0, 60, true);
  79776. this._hideTeleportationTarget();
  79777. };
  79778. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79779. if (this._teleportationInitialized) {
  79780. this._teleportationTarget.isVisible = true;
  79781. if (this._isDefaultTeleportationTarget) {
  79782. this._teleportationTarget.getChildren()[0].isVisible = true;
  79783. }
  79784. }
  79785. };
  79786. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79787. if (this._teleportationInitialized) {
  79788. this._teleportationTarget.isVisible = false;
  79789. if (this._isDefaultTeleportationTarget) {
  79790. this._teleportationTarget.getChildren()[0].isVisible = false;
  79791. }
  79792. }
  79793. };
  79794. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79795. var _this = this;
  79796. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79797. return;
  79798. }
  79799. if (right) {
  79800. this._rotationAngle++;
  79801. }
  79802. else {
  79803. this._rotationAngle--;
  79804. }
  79805. this.currentVRCamera.animations = [];
  79806. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79807. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79808. var animationRotationKeys = [];
  79809. animationRotationKeys.push({
  79810. frame: 0,
  79811. value: this.currentVRCamera.rotationQuaternion
  79812. });
  79813. animationRotationKeys.push({
  79814. frame: 6,
  79815. value: target
  79816. });
  79817. animationRotation.setKeys(animationRotationKeys);
  79818. animationRotation.setEasingFunction(this._circleEase);
  79819. this.currentVRCamera.animations.push(animationRotation);
  79820. this._postProcessMove.animations = [];
  79821. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79822. var vignetteWeightKeys = [];
  79823. vignetteWeightKeys.push({
  79824. frame: 0,
  79825. value: 0
  79826. });
  79827. vignetteWeightKeys.push({
  79828. frame: 3,
  79829. value: 4
  79830. });
  79831. vignetteWeightKeys.push({
  79832. frame: 6,
  79833. value: 0
  79834. });
  79835. animationPP.setKeys(vignetteWeightKeys);
  79836. animationPP.setEasingFunction(this._circleEase);
  79837. this._postProcessMove.animations.push(animationPP);
  79838. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79839. var vignetteStretchKeys = [];
  79840. vignetteStretchKeys.push({
  79841. frame: 0,
  79842. value: 0
  79843. });
  79844. vignetteStretchKeys.push({
  79845. frame: 3,
  79846. value: 10
  79847. });
  79848. vignetteStretchKeys.push({
  79849. frame: 6,
  79850. value: 0
  79851. });
  79852. animationPP2.setKeys(vignetteStretchKeys);
  79853. animationPP2.setEasingFunction(this._circleEase);
  79854. this._postProcessMove.animations.push(animationPP2);
  79855. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79856. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79857. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79858. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79859. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79860. });
  79861. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79862. };
  79863. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79864. if (hit.pickedPoint) {
  79865. this._teleportationAllowed = true;
  79866. if (this._teleportationRequestInitiated) {
  79867. this._displayTeleportationTarget();
  79868. }
  79869. else {
  79870. this._hideTeleportationTarget();
  79871. }
  79872. this._haloCenter.copyFrom(hit.pickedPoint);
  79873. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79874. var pickNormal = hit.getNormal(true, false);
  79875. if (pickNormal) {
  79876. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79877. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79878. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79879. }
  79880. this._teleportationTarget.position.y += 0.1;
  79881. }
  79882. };
  79883. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79884. var _this = this;
  79885. if (location === void 0) { location = null; }
  79886. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79887. return;
  79888. }
  79889. if (!location) {
  79890. location = this._haloCenter;
  79891. }
  79892. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79893. // offset of the headset from the anchor.
  79894. if (this.webVRCamera.leftCamera) {
  79895. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79896. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79897. location.subtractToRef(this._workingVector, this._workingVector);
  79898. }
  79899. else {
  79900. this._workingVector.copyFrom(location);
  79901. }
  79902. // Add height to account for user's height offset
  79903. if (this.isInVRMode) {
  79904. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79905. }
  79906. else {
  79907. this._workingVector.y += this._defaultHeight;
  79908. }
  79909. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79910. // Create animation from the camera's position to the new location
  79911. this.currentVRCamera.animations = [];
  79912. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79913. var animationCameraTeleportationKeys = [{
  79914. frame: 0,
  79915. value: this.currentVRCamera.position
  79916. },
  79917. {
  79918. frame: 11,
  79919. value: this._workingVector
  79920. }
  79921. ];
  79922. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79923. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79924. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79925. this._postProcessMove.animations = [];
  79926. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79927. var vignetteWeightKeys = [];
  79928. vignetteWeightKeys.push({
  79929. frame: 0,
  79930. value: 0
  79931. });
  79932. vignetteWeightKeys.push({
  79933. frame: 5,
  79934. value: 8
  79935. });
  79936. vignetteWeightKeys.push({
  79937. frame: 11,
  79938. value: 0
  79939. });
  79940. animationPP.setKeys(vignetteWeightKeys);
  79941. this._postProcessMove.animations.push(animationPP);
  79942. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79943. var vignetteStretchKeys = [];
  79944. vignetteStretchKeys.push({
  79945. frame: 0,
  79946. value: 0
  79947. });
  79948. vignetteStretchKeys.push({
  79949. frame: 5,
  79950. value: 10
  79951. });
  79952. vignetteStretchKeys.push({
  79953. frame: 11,
  79954. value: 0
  79955. });
  79956. animationPP2.setKeys(vignetteStretchKeys);
  79957. this._postProcessMove.animations.push(animationPP2);
  79958. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79959. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79960. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79961. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79962. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79963. });
  79964. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79965. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79966. });
  79967. };
  79968. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79969. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79970. return;
  79971. }
  79972. var ray;
  79973. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79974. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79975. }
  79976. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79977. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79978. }
  79979. else {
  79980. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79981. }
  79982. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79983. // Moving the gazeTracker on the mesh face targetted
  79984. if (hit && hit.pickedPoint) {
  79985. if (this._displayGaze) {
  79986. var multiplier = 1;
  79987. this._gazeTracker.isVisible = true;
  79988. if (this._isActionableMesh) {
  79989. multiplier = 3;
  79990. }
  79991. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79992. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79993. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79994. var pickNormal = hit.getNormal();
  79995. // To avoid z-fighting
  79996. var deltaFighting = 0.002;
  79997. if (pickNormal) {
  79998. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79999. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80000. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  80001. }
  80002. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  80003. if (this._gazeTracker.position.x < 0) {
  80004. this._gazeTracker.position.x += deltaFighting;
  80005. }
  80006. else {
  80007. this._gazeTracker.position.x -= deltaFighting;
  80008. }
  80009. if (this._gazeTracker.position.y < 0) {
  80010. this._gazeTracker.position.y += deltaFighting;
  80011. }
  80012. else {
  80013. this._gazeTracker.position.y -= deltaFighting;
  80014. }
  80015. if (this._gazeTracker.position.z < 0) {
  80016. this._gazeTracker.position.z += deltaFighting;
  80017. }
  80018. else {
  80019. this._gazeTracker.position.z -= deltaFighting;
  80020. }
  80021. }
  80022. // Changing the size of the laser pointer based on the distance from the targetted point
  80023. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  80024. this._rightLaserPointer.scaling.y = hit.distance;
  80025. this._rightLaserPointer.position.z = -hit.distance / 2;
  80026. }
  80027. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  80028. this._leftLaserPointer.scaling.y = hit.distance;
  80029. this._leftLaserPointer.position.z = -hit.distance / 2;
  80030. }
  80031. }
  80032. else {
  80033. this._gazeTracker.isVisible = false;
  80034. }
  80035. if (hit && hit.pickedMesh) {
  80036. this._currentHit = hit;
  80037. if (this._pointerDownOnMeshAsked) {
  80038. this._scene.simulatePointerMove(this._currentHit);
  80039. }
  80040. // The object selected is the floor, we're in a teleportation scenario
  80041. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80042. // Moving the teleportation area to this targetted point
  80043. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80044. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  80045. this._notifySelectedMeshUnselected();
  80046. }
  80047. this._currentMeshSelected = null;
  80048. this._moveTeleportationSelectorTo(hit);
  80049. return;
  80050. }
  80051. // If not, we're in a selection scenario
  80052. this._hideTeleportationTarget();
  80053. this._teleportationAllowed = false;
  80054. if (hit.pickedMesh !== this._currentMeshSelected) {
  80055. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80056. this.onNewMeshPicked.notifyObservers(hit);
  80057. this._currentMeshSelected = hit.pickedMesh;
  80058. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80059. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80060. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80061. this._isActionableMesh = true;
  80062. }
  80063. else {
  80064. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80065. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80066. this._isActionableMesh = false;
  80067. }
  80068. try {
  80069. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  80070. }
  80071. catch (err) {
  80072. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80073. }
  80074. }
  80075. else {
  80076. this._notifySelectedMeshUnselected();
  80077. this._currentMeshSelected = null;
  80078. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80079. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80080. }
  80081. }
  80082. }
  80083. else {
  80084. this._currentHit = null;
  80085. this._notifySelectedMeshUnselected();
  80086. this._currentMeshSelected = null;
  80087. this._teleportationAllowed = false;
  80088. this._hideTeleportationTarget();
  80089. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80090. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80091. }
  80092. };
  80093. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80094. if (this._currentMeshSelected) {
  80095. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80096. }
  80097. };
  80098. /**
  80099. * Sets the color of the laser ray from the vr controllers.
  80100. * @param color new color for the ray.
  80101. */
  80102. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80103. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80104. this._leftLaserPointer.material.emissiveColor = color;
  80105. }
  80106. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80107. this._rightLaserPointer.material.emissiveColor = color;
  80108. }
  80109. };
  80110. /**
  80111. * Sets the color of the ray from the vr headsets gaze.
  80112. * @param color new color for the ray.
  80113. */
  80114. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80115. if (this._gazeTracker.material) {
  80116. this._gazeTracker.material.emissiveColor = color;
  80117. }
  80118. };
  80119. /**
  80120. * Exits VR and disposes of the vr experience helper
  80121. */
  80122. VRExperienceHelper.prototype.dispose = function () {
  80123. if (this.isInVRMode) {
  80124. this.exitVR();
  80125. }
  80126. if (this._passProcessMove) {
  80127. this._passProcessMove.dispose();
  80128. }
  80129. if (this._postProcessMove) {
  80130. this._postProcessMove.dispose();
  80131. }
  80132. if (this._webVRCamera) {
  80133. this._webVRCamera.dispose();
  80134. }
  80135. if (this._vrDeviceOrientationCamera) {
  80136. this._vrDeviceOrientationCamera.dispose();
  80137. }
  80138. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80139. document.body.removeChild(this._btnVR);
  80140. }
  80141. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80142. this._deviceOrientationCamera.dispose();
  80143. }
  80144. if (this._gazeTracker) {
  80145. this._gazeTracker.dispose();
  80146. }
  80147. if (this._teleportationTarget) {
  80148. this._teleportationTarget.dispose();
  80149. }
  80150. this._floorMeshesCollection = [];
  80151. document.removeEventListener("keydown", this._onKeyDown);
  80152. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80153. window.removeEventListener("resize", this._onResize);
  80154. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80155. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80156. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80157. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80158. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80159. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80160. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80161. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80162. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80163. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80164. this._scene.unregisterBeforeRender(this.beforeRender);
  80165. };
  80166. /**
  80167. * Gets the name of the VRExperienceHelper class
  80168. * @returns "VRExperienceHelper"
  80169. */
  80170. VRExperienceHelper.prototype.getClassName = function () {
  80171. return "VRExperienceHelper";
  80172. };
  80173. return VRExperienceHelper;
  80174. }());
  80175. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80176. })(BABYLON || (BABYLON = {}));
  80177. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80178. // Mainly based on these 2 articles :
  80179. // 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
  80180. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80181. var BABYLON;
  80182. (function (BABYLON) {
  80183. var JoystickAxis;
  80184. (function (JoystickAxis) {
  80185. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80186. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80187. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80188. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80189. var VirtualJoystick = /** @class */ (function () {
  80190. function VirtualJoystick(leftJoystick) {
  80191. var _this = this;
  80192. if (leftJoystick) {
  80193. this._leftJoystick = true;
  80194. }
  80195. else {
  80196. this._leftJoystick = false;
  80197. }
  80198. VirtualJoystick._globalJoystickIndex++;
  80199. // By default left & right arrow keys are moving the X
  80200. // and up & down keys are moving the Y
  80201. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80202. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80203. this.reverseLeftRight = false;
  80204. this.reverseUpDown = false;
  80205. // collections of pointers
  80206. this._touches = new BABYLON.StringDictionary();
  80207. this.deltaPosition = BABYLON.Vector3.Zero();
  80208. this._joystickSensibility = 25;
  80209. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80210. this._onResize = function (evt) {
  80211. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80212. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80213. if (VirtualJoystick.vjCanvas) {
  80214. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80215. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80216. }
  80217. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80218. };
  80219. // injecting a canvas element on top of the canvas 3D game
  80220. if (!VirtualJoystick.vjCanvas) {
  80221. window.addEventListener("resize", this._onResize, false);
  80222. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80223. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80224. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80225. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80226. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80227. VirtualJoystick.vjCanvas.style.width = "100%";
  80228. VirtualJoystick.vjCanvas.style.height = "100%";
  80229. VirtualJoystick.vjCanvas.style.position = "absolute";
  80230. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80231. VirtualJoystick.vjCanvas.style.top = "0px";
  80232. VirtualJoystick.vjCanvas.style.left = "0px";
  80233. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80234. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80235. // Support for jQuery PEP polyfill
  80236. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80237. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80238. if (!context) {
  80239. throw new Error("Unable to create canvas for virtual joystick");
  80240. }
  80241. VirtualJoystick.vjCanvasContext = context;
  80242. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80243. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80244. document.body.appendChild(VirtualJoystick.vjCanvas);
  80245. }
  80246. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80247. this.pressed = false;
  80248. // default joystick color
  80249. this._joystickColor = "cyan";
  80250. this._joystickPointerID = -1;
  80251. // current joystick position
  80252. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80253. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80254. // origin joystick position
  80255. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80256. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80257. this._onPointerDownHandlerRef = function (evt) {
  80258. _this._onPointerDown(evt);
  80259. };
  80260. this._onPointerMoveHandlerRef = function (evt) {
  80261. _this._onPointerMove(evt);
  80262. };
  80263. this._onPointerUpHandlerRef = function (evt) {
  80264. _this._onPointerUp(evt);
  80265. };
  80266. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80267. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80268. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80269. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80270. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80271. evt.preventDefault(); // Disables system menu
  80272. }, false);
  80273. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80274. }
  80275. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80276. this._joystickSensibility = newJoystickSensibility;
  80277. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80278. };
  80279. VirtualJoystick.prototype._onPointerDown = function (e) {
  80280. var positionOnScreenCondition;
  80281. e.preventDefault();
  80282. if (this._leftJoystick === true) {
  80283. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80284. }
  80285. else {
  80286. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80287. }
  80288. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80289. // First contact will be dedicated to the virtual joystick
  80290. this._joystickPointerID = e.pointerId;
  80291. this._joystickPointerStartPos.x = e.clientX;
  80292. this._joystickPointerStartPos.y = e.clientY;
  80293. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80294. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80295. this._deltaJoystickVector.x = 0;
  80296. this._deltaJoystickVector.y = 0;
  80297. this.pressed = true;
  80298. this._touches.add(e.pointerId.toString(), e);
  80299. }
  80300. else {
  80301. // You can only trigger the action buttons with a joystick declared
  80302. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80303. this._action();
  80304. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80305. }
  80306. }
  80307. };
  80308. VirtualJoystick.prototype._onPointerMove = function (e) {
  80309. // If the current pointer is the one associated to the joystick (first touch contact)
  80310. if (this._joystickPointerID == e.pointerId) {
  80311. this._joystickPointerPos.x = e.clientX;
  80312. this._joystickPointerPos.y = e.clientY;
  80313. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80314. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80315. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80316. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80317. switch (this._axisTargetedByLeftAndRight) {
  80318. case JoystickAxis.X:
  80319. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80320. break;
  80321. case JoystickAxis.Y:
  80322. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80323. break;
  80324. case JoystickAxis.Z:
  80325. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80326. break;
  80327. }
  80328. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80329. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80330. switch (this._axisTargetedByUpAndDown) {
  80331. case JoystickAxis.X:
  80332. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80333. break;
  80334. case JoystickAxis.Y:
  80335. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80336. break;
  80337. case JoystickAxis.Z:
  80338. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80339. break;
  80340. }
  80341. }
  80342. else {
  80343. var data = this._touches.get(e.pointerId.toString());
  80344. if (data) {
  80345. data.x = e.clientX;
  80346. data.y = e.clientY;
  80347. }
  80348. }
  80349. };
  80350. VirtualJoystick.prototype._onPointerUp = function (e) {
  80351. if (this._joystickPointerID == e.pointerId) {
  80352. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80353. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80354. this._joystickPointerID = -1;
  80355. this.pressed = false;
  80356. }
  80357. else {
  80358. var touch = this._touches.get(e.pointerId.toString());
  80359. if (touch) {
  80360. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80361. }
  80362. }
  80363. this._deltaJoystickVector.x = 0;
  80364. this._deltaJoystickVector.y = 0;
  80365. this._touches.remove(e.pointerId.toString());
  80366. };
  80367. /**
  80368. * Change the color of the virtual joystick
  80369. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80370. */
  80371. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80372. this._joystickColor = newColor;
  80373. };
  80374. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80375. this._action = action;
  80376. };
  80377. // Define which axis you'd like to control for left & right
  80378. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80379. switch (axis) {
  80380. case JoystickAxis.X:
  80381. case JoystickAxis.Y:
  80382. case JoystickAxis.Z:
  80383. this._axisTargetedByLeftAndRight = axis;
  80384. break;
  80385. default:
  80386. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80387. break;
  80388. }
  80389. };
  80390. // Define which axis you'd like to control for up & down
  80391. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80392. switch (axis) {
  80393. case JoystickAxis.X:
  80394. case JoystickAxis.Y:
  80395. case JoystickAxis.Z:
  80396. this._axisTargetedByUpAndDown = axis;
  80397. break;
  80398. default:
  80399. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80400. break;
  80401. }
  80402. };
  80403. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80404. var _this = this;
  80405. if (this.pressed) {
  80406. this._touches.forEach(function (key, touch) {
  80407. if (touch.pointerId === _this._joystickPointerID) {
  80408. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80409. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80410. VirtualJoystick.vjCanvasContext.beginPath();
  80411. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80412. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80413. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80414. VirtualJoystick.vjCanvasContext.stroke();
  80415. VirtualJoystick.vjCanvasContext.closePath();
  80416. VirtualJoystick.vjCanvasContext.beginPath();
  80417. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80418. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80419. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80420. VirtualJoystick.vjCanvasContext.stroke();
  80421. VirtualJoystick.vjCanvasContext.closePath();
  80422. VirtualJoystick.vjCanvasContext.beginPath();
  80423. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80424. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80425. VirtualJoystick.vjCanvasContext.stroke();
  80426. VirtualJoystick.vjCanvasContext.closePath();
  80427. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80428. }
  80429. else {
  80430. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80431. VirtualJoystick.vjCanvasContext.beginPath();
  80432. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80433. VirtualJoystick.vjCanvasContext.beginPath();
  80434. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80435. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80436. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80437. VirtualJoystick.vjCanvasContext.stroke();
  80438. VirtualJoystick.vjCanvasContext.closePath();
  80439. touch.prevX = touch.x;
  80440. touch.prevY = touch.y;
  80441. }
  80442. ;
  80443. });
  80444. }
  80445. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80446. };
  80447. VirtualJoystick.prototype.releaseCanvas = function () {
  80448. if (VirtualJoystick.vjCanvas) {
  80449. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80450. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80451. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80452. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80453. window.removeEventListener("resize", this._onResize);
  80454. document.body.removeChild(VirtualJoystick.vjCanvas);
  80455. VirtualJoystick.vjCanvas = null;
  80456. }
  80457. };
  80458. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80459. VirtualJoystick._globalJoystickIndex = 0;
  80460. return VirtualJoystick;
  80461. }());
  80462. BABYLON.VirtualJoystick = VirtualJoystick;
  80463. })(BABYLON || (BABYLON = {}));
  80464. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80465. var BABYLON;
  80466. (function (BABYLON) {
  80467. // We're mainly based on the logic defined into the FreeCamera code
  80468. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80469. __extends(VirtualJoysticksCamera, _super);
  80470. function VirtualJoysticksCamera(name, position, scene) {
  80471. var _this = _super.call(this, name, position, scene) || this;
  80472. _this.inputs.addVirtualJoystick();
  80473. return _this;
  80474. }
  80475. VirtualJoysticksCamera.prototype.getClassName = function () {
  80476. return "VirtualJoysticksCamera";
  80477. };
  80478. return VirtualJoysticksCamera;
  80479. }(BABYLON.FreeCamera));
  80480. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80481. })(BABYLON || (BABYLON = {}));
  80482. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80483. var BABYLON;
  80484. (function (BABYLON) {
  80485. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80486. function FreeCameraVirtualJoystickInput() {
  80487. }
  80488. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80489. return this._leftjoystick;
  80490. };
  80491. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80492. return this._rightjoystick;
  80493. };
  80494. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80495. if (this._leftjoystick) {
  80496. var camera = this.camera;
  80497. var speed = camera._computeLocalCameraSpeed() * 50;
  80498. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80499. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80500. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80501. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80502. if (!this._leftjoystick.pressed) {
  80503. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80504. }
  80505. if (!this._rightjoystick.pressed) {
  80506. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80507. }
  80508. }
  80509. };
  80510. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80511. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80512. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80513. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80514. this._leftjoystick.setJoystickSensibility(0.15);
  80515. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80516. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80517. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80518. this._rightjoystick.reverseUpDown = true;
  80519. this._rightjoystick.setJoystickSensibility(0.05);
  80520. this._rightjoystick.setJoystickColor("yellow");
  80521. };
  80522. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80523. this._leftjoystick.releaseCanvas();
  80524. this._rightjoystick.releaseCanvas();
  80525. };
  80526. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80527. return "FreeCameraVirtualJoystickInput";
  80528. };
  80529. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80530. return "virtualJoystick";
  80531. };
  80532. return FreeCameraVirtualJoystickInput;
  80533. }());
  80534. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80535. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80536. })(BABYLON || (BABYLON = {}));
  80537. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80538. var BABYLON;
  80539. (function (BABYLON) {
  80540. var SimplificationSettings = /** @class */ (function () {
  80541. function SimplificationSettings(quality, distance, optimizeMesh) {
  80542. this.quality = quality;
  80543. this.distance = distance;
  80544. this.optimizeMesh = optimizeMesh;
  80545. }
  80546. return SimplificationSettings;
  80547. }());
  80548. BABYLON.SimplificationSettings = SimplificationSettings;
  80549. var SimplificationQueue = /** @class */ (function () {
  80550. function SimplificationQueue() {
  80551. this.running = false;
  80552. this._simplificationArray = [];
  80553. }
  80554. SimplificationQueue.prototype.addTask = function (task) {
  80555. this._simplificationArray.push(task);
  80556. };
  80557. SimplificationQueue.prototype.executeNext = function () {
  80558. var task = this._simplificationArray.pop();
  80559. if (task) {
  80560. this.running = true;
  80561. this.runSimplification(task);
  80562. }
  80563. else {
  80564. this.running = false;
  80565. }
  80566. };
  80567. SimplificationQueue.prototype.runSimplification = function (task) {
  80568. var _this = this;
  80569. if (task.parallelProcessing) {
  80570. //parallel simplifier
  80571. task.settings.forEach(function (setting) {
  80572. var simplifier = _this.getSimplifier(task);
  80573. simplifier.simplify(setting, function (newMesh) {
  80574. task.mesh.addLODLevel(setting.distance, newMesh);
  80575. newMesh.isVisible = true;
  80576. //check if it is the last
  80577. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80578. //all done, run the success callback.
  80579. task.successCallback();
  80580. }
  80581. _this.executeNext();
  80582. });
  80583. });
  80584. }
  80585. else {
  80586. //single simplifier.
  80587. var simplifier = this.getSimplifier(task);
  80588. var runDecimation = function (setting, callback) {
  80589. simplifier.simplify(setting, function (newMesh) {
  80590. task.mesh.addLODLevel(setting.distance, newMesh);
  80591. newMesh.isVisible = true;
  80592. //run the next quality level
  80593. callback();
  80594. });
  80595. };
  80596. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80597. runDecimation(task.settings[loop.index], function () {
  80598. loop.executeNext();
  80599. });
  80600. }, function () {
  80601. //execution ended, run the success callback.
  80602. if (task.successCallback) {
  80603. task.successCallback();
  80604. }
  80605. _this.executeNext();
  80606. });
  80607. }
  80608. };
  80609. SimplificationQueue.prototype.getSimplifier = function (task) {
  80610. switch (task.simplificationType) {
  80611. case SimplificationType.QUADRATIC:
  80612. default:
  80613. return new QuadraticErrorSimplification(task.mesh);
  80614. }
  80615. };
  80616. return SimplificationQueue;
  80617. }());
  80618. BABYLON.SimplificationQueue = SimplificationQueue;
  80619. /**
  80620. * The implemented types of simplification.
  80621. * At the moment only Quadratic Error Decimation is implemented.
  80622. */
  80623. var SimplificationType;
  80624. (function (SimplificationType) {
  80625. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80626. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80627. var DecimationTriangle = /** @class */ (function () {
  80628. function DecimationTriangle(vertices) {
  80629. this.vertices = vertices;
  80630. this.error = new Array(4);
  80631. this.deleted = false;
  80632. this.isDirty = false;
  80633. this.deletePending = false;
  80634. this.borderFactor = 0;
  80635. }
  80636. return DecimationTriangle;
  80637. }());
  80638. BABYLON.DecimationTriangle = DecimationTriangle;
  80639. var DecimationVertex = /** @class */ (function () {
  80640. function DecimationVertex(position, id) {
  80641. this.position = position;
  80642. this.id = id;
  80643. this.isBorder = true;
  80644. this.q = new QuadraticMatrix();
  80645. this.triangleCount = 0;
  80646. this.triangleStart = 0;
  80647. this.originalOffsets = [];
  80648. }
  80649. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80650. this.position.copyFrom(newPosition);
  80651. };
  80652. return DecimationVertex;
  80653. }());
  80654. BABYLON.DecimationVertex = DecimationVertex;
  80655. var QuadraticMatrix = /** @class */ (function () {
  80656. function QuadraticMatrix(data) {
  80657. this.data = new Array(10);
  80658. for (var i = 0; i < 10; ++i) {
  80659. if (data && data[i]) {
  80660. this.data[i] = data[i];
  80661. }
  80662. else {
  80663. this.data[i] = 0;
  80664. }
  80665. }
  80666. }
  80667. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80668. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80669. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80670. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80671. return det;
  80672. };
  80673. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80674. for (var i = 0; i < 10; ++i) {
  80675. this.data[i] += matrix.data[i];
  80676. }
  80677. };
  80678. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80679. for (var i = 0; i < 10; ++i) {
  80680. this.data[i] += data[i];
  80681. }
  80682. };
  80683. QuadraticMatrix.prototype.add = function (matrix) {
  80684. var m = new QuadraticMatrix();
  80685. for (var i = 0; i < 10; ++i) {
  80686. m.data[i] = this.data[i] + matrix.data[i];
  80687. }
  80688. return m;
  80689. };
  80690. QuadraticMatrix.FromData = function (a, b, c, d) {
  80691. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80692. };
  80693. //returning an array to avoid garbage collection
  80694. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80695. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80696. };
  80697. return QuadraticMatrix;
  80698. }());
  80699. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80700. var Reference = /** @class */ (function () {
  80701. function Reference(vertexId, triangleId) {
  80702. this.vertexId = vertexId;
  80703. this.triangleId = triangleId;
  80704. }
  80705. return Reference;
  80706. }());
  80707. BABYLON.Reference = Reference;
  80708. /**
  80709. * An implementation of the Quadratic Error simplification algorithm.
  80710. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80711. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80712. * @author RaananW
  80713. */
  80714. var QuadraticErrorSimplification = /** @class */ (function () {
  80715. function QuadraticErrorSimplification(_mesh) {
  80716. this._mesh = _mesh;
  80717. this.syncIterations = 5000;
  80718. this.aggressiveness = 7;
  80719. this.decimationIterations = 100;
  80720. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80721. }
  80722. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80723. var _this = this;
  80724. this.initDecimatedMesh();
  80725. //iterating through the submeshes array, one after the other.
  80726. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80727. _this.initWithMesh(loop.index, function () {
  80728. _this.runDecimation(settings, loop.index, function () {
  80729. loop.executeNext();
  80730. });
  80731. }, settings.optimizeMesh);
  80732. }, function () {
  80733. setTimeout(function () {
  80734. successCallback(_this._reconstructedMesh);
  80735. }, 0);
  80736. });
  80737. };
  80738. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80739. var _this = this;
  80740. var targetCount = ~~(this.triangles.length * settings.quality);
  80741. var deletedTriangles = 0;
  80742. var triangleCount = this.triangles.length;
  80743. var iterationFunction = function (iteration, callback) {
  80744. setTimeout(function () {
  80745. if (iteration % 5 === 0) {
  80746. _this.updateMesh(iteration === 0);
  80747. }
  80748. for (var i = 0; i < _this.triangles.length; ++i) {
  80749. _this.triangles[i].isDirty = false;
  80750. }
  80751. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80752. var trianglesIterator = function (i) {
  80753. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80754. var t = _this.triangles[tIdx];
  80755. if (!t)
  80756. return;
  80757. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80758. return;
  80759. }
  80760. for (var j = 0; j < 3; ++j) {
  80761. if (t.error[j] < threshold) {
  80762. var deleted0 = [];
  80763. var deleted1 = [];
  80764. var v0 = t.vertices[j];
  80765. var v1 = t.vertices[(j + 1) % 3];
  80766. if (v0.isBorder || v1.isBorder)
  80767. continue;
  80768. var p = BABYLON.Vector3.Zero();
  80769. var n = BABYLON.Vector3.Zero();
  80770. var uv = BABYLON.Vector2.Zero();
  80771. var color = new BABYLON.Color4(0, 0, 0, 1);
  80772. _this.calculateError(v0, v1, p, n, uv, color);
  80773. var delTr = new Array();
  80774. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80775. continue;
  80776. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80777. continue;
  80778. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80779. continue;
  80780. var uniqueArray = new Array();
  80781. delTr.forEach(function (deletedT) {
  80782. if (uniqueArray.indexOf(deletedT) === -1) {
  80783. deletedT.deletePending = true;
  80784. uniqueArray.push(deletedT);
  80785. }
  80786. });
  80787. if (uniqueArray.length % 2 !== 0) {
  80788. continue;
  80789. }
  80790. v0.q = v1.q.add(v0.q);
  80791. v0.updatePosition(p);
  80792. var tStart = _this.references.length;
  80793. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80794. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80795. var tCount = _this.references.length - tStart;
  80796. if (tCount <= v0.triangleCount) {
  80797. if (tCount) {
  80798. for (var c = 0; c < tCount; c++) {
  80799. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80800. }
  80801. }
  80802. }
  80803. else {
  80804. v0.triangleStart = tStart;
  80805. }
  80806. v0.triangleCount = tCount;
  80807. break;
  80808. }
  80809. }
  80810. };
  80811. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80812. }, 0);
  80813. };
  80814. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80815. if (triangleCount - deletedTriangles <= targetCount)
  80816. loop.breakLoop();
  80817. else {
  80818. iterationFunction(loop.index, function () {
  80819. loop.executeNext();
  80820. });
  80821. }
  80822. }, function () {
  80823. setTimeout(function () {
  80824. //reconstruct this part of the mesh
  80825. _this.reconstructMesh(submeshIndex);
  80826. successCallback();
  80827. }, 0);
  80828. });
  80829. };
  80830. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80831. var _this = this;
  80832. this.vertices = [];
  80833. this.triangles = [];
  80834. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80835. var indices = this._mesh.getIndices();
  80836. var submesh = this._mesh.subMeshes[submeshIndex];
  80837. var findInVertices = function (positionToSearch) {
  80838. if (optimizeMesh) {
  80839. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80840. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80841. return _this.vertices[ii];
  80842. }
  80843. }
  80844. }
  80845. return null;
  80846. };
  80847. var vertexReferences = [];
  80848. var vertexInit = function (i) {
  80849. if (!positionData) {
  80850. return;
  80851. }
  80852. var offset = i + submesh.verticesStart;
  80853. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80854. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80855. vertex.originalOffsets.push(offset);
  80856. if (vertex.id === _this.vertices.length) {
  80857. _this.vertices.push(vertex);
  80858. }
  80859. vertexReferences.push(vertex.id);
  80860. };
  80861. //var totalVertices = mesh.getTotalVertices();
  80862. var totalVertices = submesh.verticesCount;
  80863. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80864. var indicesInit = function (i) {
  80865. if (!indices) {
  80866. return;
  80867. }
  80868. var offset = (submesh.indexStart / 3) + i;
  80869. var pos = (offset * 3);
  80870. var i0 = indices[pos + 0];
  80871. var i1 = indices[pos + 1];
  80872. var i2 = indices[pos + 2];
  80873. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80874. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80875. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80876. var triangle = new DecimationTriangle([v0, v1, v2]);
  80877. triangle.originalOffset = pos;
  80878. _this.triangles.push(triangle);
  80879. };
  80880. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80881. _this.init(callback);
  80882. });
  80883. });
  80884. };
  80885. QuadraticErrorSimplification.prototype.init = function (callback) {
  80886. var _this = this;
  80887. var triangleInit1 = function (i) {
  80888. var t = _this.triangles[i];
  80889. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80890. for (var j = 0; j < 3; j++) {
  80891. 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))));
  80892. }
  80893. };
  80894. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80895. var triangleInit2 = function (i) {
  80896. var t = _this.triangles[i];
  80897. for (var j = 0; j < 3; ++j) {
  80898. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80899. }
  80900. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80901. };
  80902. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80903. callback();
  80904. });
  80905. });
  80906. };
  80907. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80908. var newTriangles = [];
  80909. var i;
  80910. for (i = 0; i < this.vertices.length; ++i) {
  80911. this.vertices[i].triangleCount = 0;
  80912. }
  80913. var t;
  80914. var j;
  80915. for (i = 0; i < this.triangles.length; ++i) {
  80916. if (!this.triangles[i].deleted) {
  80917. t = this.triangles[i];
  80918. for (j = 0; j < 3; ++j) {
  80919. t.vertices[j].triangleCount = 1;
  80920. }
  80921. newTriangles.push(t);
  80922. }
  80923. }
  80924. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80925. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80926. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80927. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80928. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80929. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80930. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80931. var vertexCount = 0;
  80932. for (i = 0; i < this.vertices.length; ++i) {
  80933. var vertex = this.vertices[i];
  80934. vertex.id = vertexCount;
  80935. if (vertex.triangleCount) {
  80936. vertex.originalOffsets.forEach(function (originalOffset) {
  80937. if (!normalData) {
  80938. return;
  80939. }
  80940. newPositionData.push(vertex.position.x);
  80941. newPositionData.push(vertex.position.y);
  80942. newPositionData.push(vertex.position.z);
  80943. newNormalData.push(normalData[originalOffset * 3]);
  80944. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80945. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80946. if (uvs && uvs.length) {
  80947. newUVsData.push(uvs[(originalOffset * 2)]);
  80948. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80949. }
  80950. else if (colorsData && colorsData.length) {
  80951. newColorsData.push(colorsData[(originalOffset * 4)]);
  80952. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80953. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80954. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80955. }
  80956. ++vertexCount;
  80957. });
  80958. }
  80959. }
  80960. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80961. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80962. var submeshesArray = this._reconstructedMesh.subMeshes;
  80963. this._reconstructedMesh.subMeshes = [];
  80964. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80965. var originalIndices = this._mesh.getIndices();
  80966. for (i = 0; i < newTriangles.length; ++i) {
  80967. t = newTriangles[i]; //now get the new referencing point for each vertex
  80968. [0, 1, 2].forEach(function (idx) {
  80969. var id = originalIndices[t.originalOffset + idx];
  80970. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80971. if (offset < 0)
  80972. offset = 0;
  80973. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80974. });
  80975. }
  80976. //overwriting the old vertex buffers and indices.
  80977. this._reconstructedMesh.setIndices(newIndicesArray);
  80978. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80979. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80980. if (newUVsData.length > 0)
  80981. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80982. if (newColorsData.length > 0)
  80983. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80984. //create submesh
  80985. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80986. if (submeshIndex > 0) {
  80987. this._reconstructedMesh.subMeshes = [];
  80988. submeshesArray.forEach(function (submesh) {
  80989. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80990. });
  80991. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80992. }
  80993. };
  80994. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80995. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80996. this._reconstructedMesh.material = this._mesh.material;
  80997. this._reconstructedMesh.parent = this._mesh.parent;
  80998. this._reconstructedMesh.isVisible = false;
  80999. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81000. };
  81001. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81002. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81003. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81004. if (t.deleted)
  81005. continue;
  81006. var s = this.references[vertex1.triangleStart + i].vertexId;
  81007. var v1 = t.vertices[(s + 1) % 3];
  81008. var v2 = t.vertices[(s + 2) % 3];
  81009. if ((v1 === vertex2 || v2 === vertex2)) {
  81010. deletedArray[i] = true;
  81011. delTr.push(t);
  81012. continue;
  81013. }
  81014. var d1 = v1.position.subtract(point);
  81015. d1 = d1.normalize();
  81016. var d2 = v2.position.subtract(point);
  81017. d2 = d2.normalize();
  81018. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81019. return true;
  81020. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81021. deletedArray[i] = false;
  81022. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81023. return true;
  81024. }
  81025. return false;
  81026. };
  81027. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81028. var newDeleted = deletedTriangles;
  81029. for (var i = 0; i < vertex.triangleCount; ++i) {
  81030. var ref = this.references[vertex.triangleStart + i];
  81031. var t = this.triangles[ref.triangleId];
  81032. if (t.deleted)
  81033. continue;
  81034. if (deletedArray[i] && t.deletePending) {
  81035. t.deleted = true;
  81036. newDeleted++;
  81037. continue;
  81038. }
  81039. t.vertices[ref.vertexId] = origVertex;
  81040. t.isDirty = true;
  81041. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81042. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81043. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81044. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81045. this.references.push(ref);
  81046. }
  81047. return newDeleted;
  81048. };
  81049. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81050. for (var i = 0; i < this.vertices.length; ++i) {
  81051. var vCount = [];
  81052. var vId = [];
  81053. var v = this.vertices[i];
  81054. var j;
  81055. for (j = 0; j < v.triangleCount; ++j) {
  81056. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81057. for (var ii = 0; ii < 3; ii++) {
  81058. var ofs = 0;
  81059. var vv = triangle.vertices[ii];
  81060. while (ofs < vCount.length) {
  81061. if (vId[ofs] === vv.id)
  81062. break;
  81063. ++ofs;
  81064. }
  81065. if (ofs === vCount.length) {
  81066. vCount.push(1);
  81067. vId.push(vv.id);
  81068. }
  81069. else {
  81070. vCount[ofs]++;
  81071. }
  81072. }
  81073. }
  81074. for (j = 0; j < vCount.length; ++j) {
  81075. if (vCount[j] === 1) {
  81076. this.vertices[vId[j]].isBorder = true;
  81077. }
  81078. else {
  81079. this.vertices[vId[j]].isBorder = false;
  81080. }
  81081. }
  81082. }
  81083. };
  81084. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81085. if (identifyBorders === void 0) { identifyBorders = false; }
  81086. var i;
  81087. if (!identifyBorders) {
  81088. var newTrianglesVector = [];
  81089. for (i = 0; i < this.triangles.length; ++i) {
  81090. if (!this.triangles[i].deleted) {
  81091. newTrianglesVector.push(this.triangles[i]);
  81092. }
  81093. }
  81094. this.triangles = newTrianglesVector;
  81095. }
  81096. for (i = 0; i < this.vertices.length; ++i) {
  81097. this.vertices[i].triangleCount = 0;
  81098. this.vertices[i].triangleStart = 0;
  81099. }
  81100. var t;
  81101. var j;
  81102. var v;
  81103. for (i = 0; i < this.triangles.length; ++i) {
  81104. t = this.triangles[i];
  81105. for (j = 0; j < 3; ++j) {
  81106. v = t.vertices[j];
  81107. v.triangleCount++;
  81108. }
  81109. }
  81110. var tStart = 0;
  81111. for (i = 0; i < this.vertices.length; ++i) {
  81112. this.vertices[i].triangleStart = tStart;
  81113. tStart += this.vertices[i].triangleCount;
  81114. this.vertices[i].triangleCount = 0;
  81115. }
  81116. var newReferences = new Array(this.triangles.length * 3);
  81117. for (i = 0; i < this.triangles.length; ++i) {
  81118. t = this.triangles[i];
  81119. for (j = 0; j < 3; ++j) {
  81120. v = t.vertices[j];
  81121. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81122. v.triangleCount++;
  81123. }
  81124. }
  81125. this.references = newReferences;
  81126. if (identifyBorders) {
  81127. this.identifyBorder();
  81128. }
  81129. };
  81130. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81131. var x = point.x;
  81132. var y = point.y;
  81133. var z = point.z;
  81134. 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
  81135. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81136. };
  81137. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81138. var q = vertex1.q.add(vertex2.q);
  81139. var border = vertex1.isBorder && vertex2.isBorder;
  81140. var error = 0;
  81141. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81142. if (qDet !== 0 && !border) {
  81143. if (!pointResult) {
  81144. pointResult = BABYLON.Vector3.Zero();
  81145. }
  81146. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81147. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81148. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81149. error = this.vertexError(q, pointResult);
  81150. }
  81151. else {
  81152. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81153. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81154. var error1 = this.vertexError(q, vertex1.position);
  81155. var error2 = this.vertexError(q, vertex2.position);
  81156. var error3 = this.vertexError(q, p3);
  81157. error = Math.min(error1, error2, error3);
  81158. if (error === error1) {
  81159. if (pointResult) {
  81160. pointResult.copyFrom(vertex1.position);
  81161. }
  81162. }
  81163. else if (error === error2) {
  81164. if (pointResult) {
  81165. pointResult.copyFrom(vertex2.position);
  81166. }
  81167. }
  81168. else {
  81169. if (pointResult) {
  81170. pointResult.copyFrom(p3);
  81171. }
  81172. }
  81173. }
  81174. return error;
  81175. };
  81176. return QuadraticErrorSimplification;
  81177. }());
  81178. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81179. })(BABYLON || (BABYLON = {}));
  81180. //# sourceMappingURL=babylon.meshSimplification.js.map
  81181. var BABYLON;
  81182. (function (BABYLON) {
  81183. var MeshLODLevel = /** @class */ (function () {
  81184. function MeshLODLevel(distance, mesh) {
  81185. this.distance = distance;
  81186. this.mesh = mesh;
  81187. }
  81188. return MeshLODLevel;
  81189. }());
  81190. BABYLON.MeshLODLevel = MeshLODLevel;
  81191. })(BABYLON || (BABYLON = {}));
  81192. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81193. var BABYLON;
  81194. (function (BABYLON) {
  81195. /**
  81196. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81197. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81198. */
  81199. var SceneOptimization = /** @class */ (function () {
  81200. /**
  81201. * Creates the SceneOptimization object
  81202. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81203. * @param desc defines the description associated with the optimization
  81204. */
  81205. function SceneOptimization(
  81206. /**
  81207. * Defines the priority of this optimization (0 by default which means first in the list)
  81208. */
  81209. priority) {
  81210. if (priority === void 0) { priority = 0; }
  81211. this.priority = priority;
  81212. }
  81213. /**
  81214. * Gets a string describing the action executed by the current optimization
  81215. * @returns description string
  81216. */
  81217. SceneOptimization.prototype.getDescription = function () {
  81218. return "";
  81219. };
  81220. /**
  81221. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81222. * @param scene defines the current scene where to apply this optimization
  81223. * @param optimizer defines the current optimizer
  81224. * @returns true if everything that can be done was applied
  81225. */
  81226. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81227. return true;
  81228. };
  81229. ;
  81230. return SceneOptimization;
  81231. }());
  81232. BABYLON.SceneOptimization = SceneOptimization;
  81233. /**
  81234. * Defines an optimization used to reduce the size of render target textures
  81235. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81236. */
  81237. var TextureOptimization = /** @class */ (function (_super) {
  81238. __extends(TextureOptimization, _super);
  81239. /**
  81240. * Creates the TextureOptimization object
  81241. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81242. * @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
  81243. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81244. */
  81245. function TextureOptimization(
  81246. /**
  81247. * Defines the priority of this optimization (0 by default which means first in the list)
  81248. */
  81249. priority,
  81250. /**
  81251. * 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
  81252. */
  81253. maximumSize,
  81254. /**
  81255. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81256. */
  81257. step) {
  81258. if (priority === void 0) { priority = 0; }
  81259. if (maximumSize === void 0) { maximumSize = 1024; }
  81260. if (step === void 0) { step = 0.5; }
  81261. var _this = _super.call(this, priority) || this;
  81262. _this.priority = priority;
  81263. _this.maximumSize = maximumSize;
  81264. _this.step = step;
  81265. return _this;
  81266. }
  81267. /**
  81268. * Gets a string describing the action executed by the current optimization
  81269. * @returns description string
  81270. */
  81271. TextureOptimization.prototype.getDescription = function () {
  81272. return "Reducing render target texture size to " + this.maximumSize;
  81273. };
  81274. /**
  81275. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81276. * @param scene defines the current scene where to apply this optimization
  81277. * @param optimizer defines the current optimizer
  81278. * @returns true if everything that can be done was applied
  81279. */
  81280. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81281. var allDone = true;
  81282. for (var index = 0; index < scene.textures.length; index++) {
  81283. var texture = scene.textures[index];
  81284. if (!texture.canRescale || texture.getContext) {
  81285. continue;
  81286. }
  81287. var currentSize = texture.getSize();
  81288. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81289. if (maxDimension > this.maximumSize) {
  81290. texture.scale(this.step);
  81291. allDone = false;
  81292. }
  81293. }
  81294. return allDone;
  81295. };
  81296. return TextureOptimization;
  81297. }(SceneOptimization));
  81298. BABYLON.TextureOptimization = TextureOptimization;
  81299. /**
  81300. * Defines an optimization used to increase or decrease the rendering resolution
  81301. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81302. */
  81303. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81304. __extends(HardwareScalingOptimization, _super);
  81305. /**
  81306. * Creates the HardwareScalingOptimization object
  81307. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81308. * @param maximumScale defines the maximum scale to use (2 by default)
  81309. * @param step defines the step to use between two passes (0.5 by default)
  81310. */
  81311. function HardwareScalingOptimization(
  81312. /**
  81313. * Defines the priority of this optimization (0 by default which means first in the list)
  81314. */
  81315. priority,
  81316. /**
  81317. * Defines the maximum scale to use (2 by default)
  81318. */
  81319. maximumScale,
  81320. /**
  81321. * Defines the step to use between two passes (0.5 by default)
  81322. */
  81323. step) {
  81324. if (priority === void 0) { priority = 0; }
  81325. if (maximumScale === void 0) { maximumScale = 2; }
  81326. if (step === void 0) { step = 0.25; }
  81327. var _this = _super.call(this, priority) || this;
  81328. _this.priority = priority;
  81329. _this.maximumScale = maximumScale;
  81330. _this.step = step;
  81331. _this._currentScale = -1;
  81332. _this._directionOffset = 1;
  81333. return _this;
  81334. }
  81335. /**
  81336. * Gets a string describing the action executed by the current optimization
  81337. * @return description string
  81338. */
  81339. HardwareScalingOptimization.prototype.getDescription = function () {
  81340. return "Setting hardware scaling level to " + this._currentScale;
  81341. };
  81342. /**
  81343. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81344. * @param scene defines the current scene where to apply this optimization
  81345. * @param optimizer defines the current optimizer
  81346. * @returns true if everything that can be done was applied
  81347. */
  81348. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81349. if (this._currentScale === -1) {
  81350. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81351. if (this._currentScale > this.maximumScale) {
  81352. this._directionOffset = -1;
  81353. }
  81354. }
  81355. this._currentScale += this._directionOffset * this.step;
  81356. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81357. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81358. };
  81359. ;
  81360. return HardwareScalingOptimization;
  81361. }(SceneOptimization));
  81362. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81363. /**
  81364. * Defines an optimization used to remove shadows
  81365. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81366. */
  81367. var ShadowsOptimization = /** @class */ (function (_super) {
  81368. __extends(ShadowsOptimization, _super);
  81369. function ShadowsOptimization() {
  81370. return _super !== null && _super.apply(this, arguments) || this;
  81371. }
  81372. /**
  81373. * Gets a string describing the action executed by the current optimization
  81374. * @return description string
  81375. */
  81376. ShadowsOptimization.prototype.getDescription = function () {
  81377. return "Turning shadows on/off";
  81378. };
  81379. /**
  81380. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81381. * @param scene defines the current scene where to apply this optimization
  81382. * @param optimizer defines the current optimizer
  81383. * @returns true if everything that can be done was applied
  81384. */
  81385. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81386. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81387. return true;
  81388. };
  81389. ;
  81390. return ShadowsOptimization;
  81391. }(SceneOptimization));
  81392. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81393. /**
  81394. * Defines an optimization used to turn post-processes off
  81395. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81396. */
  81397. var PostProcessesOptimization = /** @class */ (function (_super) {
  81398. __extends(PostProcessesOptimization, _super);
  81399. function PostProcessesOptimization() {
  81400. return _super !== null && _super.apply(this, arguments) || this;
  81401. }
  81402. /**
  81403. * Gets a string describing the action executed by the current optimization
  81404. * @return description string
  81405. */
  81406. PostProcessesOptimization.prototype.getDescription = function () {
  81407. return "Turning post-processes on/off";
  81408. };
  81409. /**
  81410. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81411. * @param scene defines the current scene where to apply this optimization
  81412. * @param optimizer defines the current optimizer
  81413. * @returns true if everything that can be done was applied
  81414. */
  81415. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81416. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81417. return true;
  81418. };
  81419. ;
  81420. return PostProcessesOptimization;
  81421. }(SceneOptimization));
  81422. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81423. /**
  81424. * Defines an optimization used to turn lens flares off
  81425. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81426. */
  81427. var LensFlaresOptimization = /** @class */ (function (_super) {
  81428. __extends(LensFlaresOptimization, _super);
  81429. function LensFlaresOptimization() {
  81430. return _super !== null && _super.apply(this, arguments) || this;
  81431. }
  81432. /**
  81433. * Gets a string describing the action executed by the current optimization
  81434. * @return description string
  81435. */
  81436. LensFlaresOptimization.prototype.getDescription = function () {
  81437. return "Turning lens flares on/off";
  81438. };
  81439. /**
  81440. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81441. * @param scene defines the current scene where to apply this optimization
  81442. * @param optimizer defines the current optimizer
  81443. * @returns true if everything that can be done was applied
  81444. */
  81445. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81446. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81447. return true;
  81448. };
  81449. ;
  81450. return LensFlaresOptimization;
  81451. }(SceneOptimization));
  81452. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81453. /**
  81454. * Defines an optimization based on user defined callback.
  81455. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81456. */
  81457. var CustomOptimization = /** @class */ (function (_super) {
  81458. __extends(CustomOptimization, _super);
  81459. function CustomOptimization() {
  81460. return _super !== null && _super.apply(this, arguments) || this;
  81461. }
  81462. /**
  81463. * Gets a string describing the action executed by the current optimization
  81464. * @returns description string
  81465. */
  81466. CustomOptimization.prototype.getDescription = function () {
  81467. if (this.onGetDescription) {
  81468. return this.onGetDescription();
  81469. }
  81470. return "Running user defined callback";
  81471. };
  81472. /**
  81473. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81474. * @param scene defines the current scene where to apply this optimization
  81475. * @param optimizer defines the current optimizer
  81476. * @returns true if everything that can be done was applied
  81477. */
  81478. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81479. if (this.onApply) {
  81480. return this.onApply(scene, optimizer);
  81481. }
  81482. return true;
  81483. };
  81484. ;
  81485. return CustomOptimization;
  81486. }(SceneOptimization));
  81487. BABYLON.CustomOptimization = CustomOptimization;
  81488. /**
  81489. * Defines an optimization used to turn particles off
  81490. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81491. */
  81492. var ParticlesOptimization = /** @class */ (function (_super) {
  81493. __extends(ParticlesOptimization, _super);
  81494. function ParticlesOptimization() {
  81495. return _super !== null && _super.apply(this, arguments) || this;
  81496. }
  81497. /**
  81498. * Gets a string describing the action executed by the current optimization
  81499. * @return description string
  81500. */
  81501. ParticlesOptimization.prototype.getDescription = function () {
  81502. return "Turning particles on/off";
  81503. };
  81504. /**
  81505. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81506. * @param scene defines the current scene where to apply this optimization
  81507. * @param optimizer defines the current optimizer
  81508. * @returns true if everything that can be done was applied
  81509. */
  81510. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81511. scene.particlesEnabled = optimizer.isInImprovementMode;
  81512. return true;
  81513. };
  81514. ;
  81515. return ParticlesOptimization;
  81516. }(SceneOptimization));
  81517. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81518. /**
  81519. * Defines an optimization used to turn render targets off
  81520. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81521. */
  81522. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81523. __extends(RenderTargetsOptimization, _super);
  81524. function RenderTargetsOptimization() {
  81525. return _super !== null && _super.apply(this, arguments) || this;
  81526. }
  81527. /**
  81528. * Gets a string describing the action executed by the current optimization
  81529. * @return description string
  81530. */
  81531. RenderTargetsOptimization.prototype.getDescription = function () {
  81532. return "Turning render targets off";
  81533. };
  81534. /**
  81535. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81536. * @param scene defines the current scene where to apply this optimization
  81537. * @param optimizer defines the current optimizer
  81538. * @returns true if everything that can be done was applied
  81539. */
  81540. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81541. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81542. return true;
  81543. };
  81544. ;
  81545. return RenderTargetsOptimization;
  81546. }(SceneOptimization));
  81547. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81548. /**
  81549. * Defines an optimization used to merge meshes with compatible materials
  81550. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81551. */
  81552. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81553. __extends(MergeMeshesOptimization, _super);
  81554. function MergeMeshesOptimization() {
  81555. var _this = _super !== null && _super.apply(this, arguments) || this;
  81556. _this._canBeMerged = function (abstractMesh) {
  81557. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81558. return false;
  81559. }
  81560. var mesh = abstractMesh;
  81561. if (!mesh.isVisible || !mesh.isEnabled()) {
  81562. return false;
  81563. }
  81564. if (mesh.instances.length > 0) {
  81565. return false;
  81566. }
  81567. if (mesh.skeleton || mesh.hasLODLevels) {
  81568. return false;
  81569. }
  81570. if (mesh.parent) {
  81571. return false;
  81572. }
  81573. return true;
  81574. };
  81575. return _this;
  81576. }
  81577. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81578. /**
  81579. * Gets or sets a boolean which defines if optimization octree has to be updated
  81580. */
  81581. get: function () {
  81582. return MergeMeshesOptimization._UpdateSelectionTree;
  81583. },
  81584. /**
  81585. * Gets or sets a boolean which defines if optimization octree has to be updated
  81586. */
  81587. set: function (value) {
  81588. MergeMeshesOptimization._UpdateSelectionTree = value;
  81589. },
  81590. enumerable: true,
  81591. configurable: true
  81592. });
  81593. /**
  81594. * Gets a string describing the action executed by the current optimization
  81595. * @return description string
  81596. */
  81597. MergeMeshesOptimization.prototype.getDescription = function () {
  81598. return "Merging similar meshes together";
  81599. };
  81600. /**
  81601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81602. * @param scene defines the current scene where to apply this optimization
  81603. * @param optimizer defines the current optimizer
  81604. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81605. * @returns true if everything that can be done was applied
  81606. */
  81607. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81608. var globalPool = scene.meshes.slice(0);
  81609. var globalLength = globalPool.length;
  81610. for (var index = 0; index < globalLength; index++) {
  81611. var currentPool = new Array();
  81612. var current = globalPool[index];
  81613. // Checks
  81614. if (!this._canBeMerged(current)) {
  81615. continue;
  81616. }
  81617. currentPool.push(current);
  81618. // Find compatible meshes
  81619. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81620. var otherMesh = globalPool[subIndex];
  81621. if (!this._canBeMerged(otherMesh)) {
  81622. continue;
  81623. }
  81624. if (otherMesh.material !== current.material) {
  81625. continue;
  81626. }
  81627. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81628. continue;
  81629. }
  81630. currentPool.push(otherMesh);
  81631. globalLength--;
  81632. globalPool.splice(subIndex, 1);
  81633. subIndex--;
  81634. }
  81635. if (currentPool.length < 2) {
  81636. continue;
  81637. }
  81638. // Merge meshes
  81639. BABYLON.Mesh.MergeMeshes(currentPool);
  81640. }
  81641. if (updateSelectionTree != undefined) {
  81642. if (updateSelectionTree) {
  81643. scene.createOrUpdateSelectionOctree();
  81644. }
  81645. }
  81646. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81647. scene.createOrUpdateSelectionOctree();
  81648. }
  81649. return true;
  81650. };
  81651. ;
  81652. MergeMeshesOptimization._UpdateSelectionTree = false;
  81653. return MergeMeshesOptimization;
  81654. }(SceneOptimization));
  81655. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81656. /**
  81657. * Defines a list of options used by SceneOptimizer
  81658. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81659. */
  81660. var SceneOptimizerOptions = /** @class */ (function () {
  81661. /**
  81662. * Creates a new list of options used by SceneOptimizer
  81663. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81664. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81665. */
  81666. function SceneOptimizerOptions(
  81667. /**
  81668. * Defines the target frame rate to reach (60 by default)
  81669. */
  81670. targetFrameRate,
  81671. /**
  81672. * Defines the interval between two checkes (2000ms by default)
  81673. */
  81674. trackerDuration) {
  81675. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81676. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81677. this.targetFrameRate = targetFrameRate;
  81678. this.trackerDuration = trackerDuration;
  81679. /**
  81680. * Gets the list of optimizations to apply
  81681. */
  81682. this.optimizations = new Array();
  81683. }
  81684. /**
  81685. * Add a new optimization
  81686. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81687. * @returns the current SceneOptimizerOptions
  81688. */
  81689. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81690. this.optimizations.push(optimization);
  81691. return this;
  81692. };
  81693. /**
  81694. * Add a new custom optimization
  81695. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81696. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81697. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81698. * @returns the current SceneOptimizerOptions
  81699. */
  81700. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81701. if (priority === void 0) { priority = 0; }
  81702. var optimization = new CustomOptimization(priority);
  81703. optimization.onApply = onApply;
  81704. optimization.onGetDescription = onGetDescription;
  81705. this.optimizations.push(optimization);
  81706. return this;
  81707. };
  81708. /**
  81709. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81710. * @param targetFrameRate defines the target frame rate (60 by default)
  81711. * @returns a SceneOptimizerOptions object
  81712. */
  81713. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81714. var result = new SceneOptimizerOptions(targetFrameRate);
  81715. var priority = 0;
  81716. result.addOptimization(new MergeMeshesOptimization(priority));
  81717. result.addOptimization(new ShadowsOptimization(priority));
  81718. result.addOptimization(new LensFlaresOptimization(priority));
  81719. // Next priority
  81720. priority++;
  81721. result.addOptimization(new PostProcessesOptimization(priority));
  81722. result.addOptimization(new ParticlesOptimization(priority));
  81723. // Next priority
  81724. priority++;
  81725. result.addOptimization(new TextureOptimization(priority, 1024));
  81726. return result;
  81727. };
  81728. /**
  81729. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81730. * @param targetFrameRate defines the target frame rate (60 by default)
  81731. * @returns a SceneOptimizerOptions object
  81732. */
  81733. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81734. var result = new SceneOptimizerOptions(targetFrameRate);
  81735. var priority = 0;
  81736. result.addOptimization(new MergeMeshesOptimization(priority));
  81737. result.addOptimization(new ShadowsOptimization(priority));
  81738. result.addOptimization(new LensFlaresOptimization(priority));
  81739. // Next priority
  81740. priority++;
  81741. result.addOptimization(new PostProcessesOptimization(priority));
  81742. result.addOptimization(new ParticlesOptimization(priority));
  81743. // Next priority
  81744. priority++;
  81745. result.addOptimization(new TextureOptimization(priority, 512));
  81746. // Next priority
  81747. priority++;
  81748. result.addOptimization(new RenderTargetsOptimization(priority));
  81749. // Next priority
  81750. priority++;
  81751. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81752. return result;
  81753. };
  81754. /**
  81755. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81756. * @param targetFrameRate defines the target frame rate (60 by default)
  81757. * @returns a SceneOptimizerOptions object
  81758. */
  81759. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81760. var result = new SceneOptimizerOptions(targetFrameRate);
  81761. var priority = 0;
  81762. result.addOptimization(new MergeMeshesOptimization(priority));
  81763. result.addOptimization(new ShadowsOptimization(priority));
  81764. result.addOptimization(new LensFlaresOptimization(priority));
  81765. // Next priority
  81766. priority++;
  81767. result.addOptimization(new PostProcessesOptimization(priority));
  81768. result.addOptimization(new ParticlesOptimization(priority));
  81769. // Next priority
  81770. priority++;
  81771. result.addOptimization(new TextureOptimization(priority, 256));
  81772. // Next priority
  81773. priority++;
  81774. result.addOptimization(new RenderTargetsOptimization(priority));
  81775. // Next priority
  81776. priority++;
  81777. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81778. return result;
  81779. };
  81780. return SceneOptimizerOptions;
  81781. }());
  81782. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81783. /**
  81784. * Class used to run optimizations in order to reach a target frame rate
  81785. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81786. */
  81787. var SceneOptimizer = /** @class */ (function () {
  81788. /**
  81789. * Creates a new SceneOptimizer
  81790. * @param scene defines the scene to work on
  81791. * @param options defines the options to use with the SceneOptimizer
  81792. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81793. * @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)
  81794. */
  81795. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81796. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81797. if (improvementMode === void 0) { improvementMode = false; }
  81798. var _this = this;
  81799. this._isRunning = false;
  81800. this._currentPriorityLevel = 0;
  81801. this._targetFrameRate = 60;
  81802. this._trackerDuration = 2000;
  81803. this._currentFrameRate = 0;
  81804. this._improvementMode = false;
  81805. /**
  81806. * Defines an observable called when the optimizer reaches the target frame rate
  81807. */
  81808. this.onSuccessObservable = new BABYLON.Observable();
  81809. /**
  81810. * Defines an observable called when the optimizer enables an optimization
  81811. */
  81812. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81813. /**
  81814. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81815. */
  81816. this.onFailureObservable = new BABYLON.Observable();
  81817. if (!options) {
  81818. this._options = new SceneOptimizerOptions();
  81819. }
  81820. else {
  81821. this._options = options;
  81822. }
  81823. if (this._options.targetFrameRate) {
  81824. this._targetFrameRate = this._options.targetFrameRate;
  81825. }
  81826. if (this._options.trackerDuration) {
  81827. this._trackerDuration = this._options.trackerDuration;
  81828. }
  81829. if (autoGeneratePriorities) {
  81830. var priority = 0;
  81831. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81832. var optim = _a[_i];
  81833. optim.priority = priority++;
  81834. }
  81835. }
  81836. this._improvementMode = improvementMode;
  81837. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81838. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81839. _this._sceneDisposeObserver = null;
  81840. _this.dispose();
  81841. });
  81842. }
  81843. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81844. /**
  81845. * Gets a boolean indicating if the optimizer is in improvement mode
  81846. */
  81847. get: function () {
  81848. return this._improvementMode;
  81849. },
  81850. enumerable: true,
  81851. configurable: true
  81852. });
  81853. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81854. /**
  81855. * Gets the current priority level (0 at start)
  81856. */
  81857. get: function () {
  81858. return this._currentPriorityLevel;
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81864. /**
  81865. * Gets the current frame rate checked by the SceneOptimizer
  81866. */
  81867. get: function () {
  81868. return this._currentFrameRate;
  81869. },
  81870. enumerable: true,
  81871. configurable: true
  81872. });
  81873. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81874. /**
  81875. * Gets or sets the current target frame rate (60 by default)
  81876. */
  81877. get: function () {
  81878. return this._targetFrameRate;
  81879. },
  81880. /**
  81881. * Gets or sets the current target frame rate (60 by default)
  81882. */
  81883. set: function (value) {
  81884. this._targetFrameRate = value;
  81885. },
  81886. enumerable: true,
  81887. configurable: true
  81888. });
  81889. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81890. /**
  81891. * Gets or sets the current interval between two checks (every 2000ms by default)
  81892. */
  81893. get: function () {
  81894. return this._trackerDuration;
  81895. },
  81896. /**
  81897. * Gets or sets the current interval between two checks (every 2000ms by default)
  81898. */
  81899. set: function (value) {
  81900. this._trackerDuration = value;
  81901. },
  81902. enumerable: true,
  81903. configurable: true
  81904. });
  81905. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81906. /**
  81907. * Gets the list of active optimizations
  81908. */
  81909. get: function () {
  81910. return this._options.optimizations;
  81911. },
  81912. enumerable: true,
  81913. configurable: true
  81914. });
  81915. /**
  81916. * Stops the current optimizer
  81917. */
  81918. SceneOptimizer.prototype.stop = function () {
  81919. this._isRunning = false;
  81920. };
  81921. /**
  81922. * Reset the optimizer to initial step (current priority level = 0)
  81923. */
  81924. SceneOptimizer.prototype.reset = function () {
  81925. this._currentPriorityLevel = 0;
  81926. };
  81927. /**
  81928. * Start the optimizer. By default it will try to reach a specific framerate
  81929. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81930. */
  81931. SceneOptimizer.prototype.start = function () {
  81932. var _this = this;
  81933. if (this._isRunning) {
  81934. return;
  81935. }
  81936. this._isRunning = true;
  81937. // Let's wait for the scene to be ready before running our check
  81938. this._scene.executeWhenReady(function () {
  81939. setTimeout(function () {
  81940. _this._checkCurrentState();
  81941. }, _this._trackerDuration);
  81942. });
  81943. };
  81944. SceneOptimizer.prototype._checkCurrentState = function () {
  81945. var _this = this;
  81946. if (!this._isRunning) {
  81947. return;
  81948. }
  81949. var scene = this._scene;
  81950. var options = this._options;
  81951. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81952. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81953. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81954. this._isRunning = false;
  81955. this.onSuccessObservable.notifyObservers(this);
  81956. return;
  81957. }
  81958. // Apply current level of optimizations
  81959. var allDone = true;
  81960. var noOptimizationApplied = true;
  81961. for (var index = 0; index < options.optimizations.length; index++) {
  81962. var optimization = options.optimizations[index];
  81963. if (optimization.priority === this._currentPriorityLevel) {
  81964. noOptimizationApplied = false;
  81965. allDone = allDone && optimization.apply(scene, this);
  81966. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81967. }
  81968. }
  81969. // If no optimization was applied, this is a failure :(
  81970. if (noOptimizationApplied) {
  81971. this._isRunning = false;
  81972. this.onFailureObservable.notifyObservers(this);
  81973. return;
  81974. }
  81975. // If all optimizations were done, move to next level
  81976. if (allDone) {
  81977. this._currentPriorityLevel++;
  81978. }
  81979. // Let's the system running for a specific amount of time before checking FPS
  81980. scene.executeWhenReady(function () {
  81981. setTimeout(function () {
  81982. _this._checkCurrentState();
  81983. }, _this._trackerDuration);
  81984. });
  81985. };
  81986. /**
  81987. * Release all resources
  81988. */
  81989. SceneOptimizer.prototype.dispose = function () {
  81990. this.stop();
  81991. this.onSuccessObservable.clear();
  81992. this.onFailureObservable.clear();
  81993. this.onNewOptimizationAppliedObservable.clear();
  81994. if (this._sceneDisposeObserver) {
  81995. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81996. }
  81997. };
  81998. /**
  81999. * Helper function to create a SceneOptimizer with one single line of code
  82000. * @param scene defines the scene to work on
  82001. * @param options defines the options to use with the SceneOptimizer
  82002. * @param onSuccess defines a callback to call on success
  82003. * @param onFailure defines a callback to call on failure
  82004. * @returns the new SceneOptimizer object
  82005. */
  82006. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82007. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82008. if (onSuccess) {
  82009. optimizer.onSuccessObservable.add(function () {
  82010. onSuccess();
  82011. });
  82012. }
  82013. if (onFailure) {
  82014. optimizer.onFailureObservable.add(function () {
  82015. onFailure();
  82016. });
  82017. }
  82018. optimizer.start();
  82019. return optimizer;
  82020. };
  82021. return SceneOptimizer;
  82022. }());
  82023. BABYLON.SceneOptimizer = SceneOptimizer;
  82024. })(BABYLON || (BABYLON = {}));
  82025. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82026. var BABYLON;
  82027. (function (BABYLON) {
  82028. var OutlineRenderer = /** @class */ (function () {
  82029. function OutlineRenderer(scene) {
  82030. this.zOffset = 1;
  82031. this._scene = scene;
  82032. }
  82033. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82034. var _this = this;
  82035. if (useOverlay === void 0) { useOverlay = false; }
  82036. var scene = this._scene;
  82037. var engine = this._scene.getEngine();
  82038. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82039. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82040. return;
  82041. }
  82042. var mesh = subMesh.getRenderingMesh();
  82043. var material = subMesh.getMaterial();
  82044. if (!material || !scene.activeCamera) {
  82045. return;
  82046. }
  82047. engine.enableEffect(this._effect);
  82048. // Logarithmic depth
  82049. if (material.useLogarithmicDepth) {
  82050. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82051. }
  82052. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82053. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82054. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82055. // Bones
  82056. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82057. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82058. }
  82059. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82060. // Alpha test
  82061. if (material && material.needAlphaTesting()) {
  82062. var alphaTexture = material.getAlphaTestTexture();
  82063. if (alphaTexture) {
  82064. this._effect.setTexture("diffuseSampler", alphaTexture);
  82065. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82066. }
  82067. }
  82068. engine.setZOffset(-this.zOffset);
  82069. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82070. engine.setZOffset(0);
  82071. };
  82072. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82073. var defines = [];
  82074. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82075. var mesh = subMesh.getMesh();
  82076. var material = subMesh.getMaterial();
  82077. if (material) {
  82078. // Alpha test
  82079. if (material.needAlphaTesting()) {
  82080. defines.push("#define ALPHATEST");
  82081. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82082. attribs.push(BABYLON.VertexBuffer.UVKind);
  82083. defines.push("#define UV1");
  82084. }
  82085. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82086. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82087. defines.push("#define UV2");
  82088. }
  82089. }
  82090. //Logarithmic depth
  82091. if (material.useLogarithmicDepth) {
  82092. defines.push("#define LOGARITHMICDEPTH");
  82093. }
  82094. }
  82095. // Bones
  82096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82097. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82098. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82099. if (mesh.numBoneInfluencers > 4) {
  82100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82102. }
  82103. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82104. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82105. }
  82106. else {
  82107. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82108. }
  82109. // Instances
  82110. if (useInstances) {
  82111. defines.push("#define INSTANCES");
  82112. attribs.push("world0");
  82113. attribs.push("world1");
  82114. attribs.push("world2");
  82115. attribs.push("world3");
  82116. }
  82117. // Get correct effect
  82118. var join = defines.join("\n");
  82119. if (this._cachedDefines !== join) {
  82120. this._cachedDefines = join;
  82121. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82122. }
  82123. return this._effect.isReady();
  82124. };
  82125. return OutlineRenderer;
  82126. }());
  82127. BABYLON.OutlineRenderer = OutlineRenderer;
  82128. })(BABYLON || (BABYLON = {}));
  82129. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82130. var BABYLON;
  82131. (function (BABYLON) {
  82132. var FaceAdjacencies = /** @class */ (function () {
  82133. function FaceAdjacencies() {
  82134. this.edges = new Array();
  82135. this.edgesConnectedCount = 0;
  82136. }
  82137. return FaceAdjacencies;
  82138. }());
  82139. var EdgesRenderer = /** @class */ (function () {
  82140. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82141. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82142. if (epsilon === void 0) { epsilon = 0.95; }
  82143. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82144. this.edgesWidthScalerForOrthographic = 1000.0;
  82145. this.edgesWidthScalerForPerspective = 50.0;
  82146. this._linesPositions = new Array();
  82147. this._linesNormals = new Array();
  82148. this._linesIndices = new Array();
  82149. this._buffers = {};
  82150. this._checkVerticesInsteadOfIndices = false;
  82151. this._source = source;
  82152. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82153. this._epsilon = epsilon;
  82154. this._prepareRessources();
  82155. this._generateEdgesLines();
  82156. }
  82157. EdgesRenderer.prototype._prepareRessources = function () {
  82158. if (this._lineShader) {
  82159. return;
  82160. }
  82161. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82162. attributes: ["position", "normal"],
  82163. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82164. });
  82165. this._lineShader.disableDepthWrite = true;
  82166. this._lineShader.backFaceCulling = false;
  82167. };
  82168. EdgesRenderer.prototype._rebuild = function () {
  82169. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82170. if (buffer) {
  82171. buffer._rebuild();
  82172. }
  82173. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82174. if (buffer) {
  82175. buffer._rebuild();
  82176. }
  82177. var scene = this._source.getScene();
  82178. var engine = scene.getEngine();
  82179. this._ib = engine.createIndexBuffer(this._linesIndices);
  82180. };
  82181. EdgesRenderer.prototype.dispose = function () {
  82182. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82183. if (buffer) {
  82184. buffer.dispose();
  82185. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82186. }
  82187. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82188. if (buffer) {
  82189. buffer.dispose();
  82190. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82191. }
  82192. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82193. this._lineShader.dispose();
  82194. };
  82195. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82196. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82197. return 0;
  82198. }
  82199. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82200. return 1;
  82201. }
  82202. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82203. return 2;
  82204. }
  82205. return -1;
  82206. };
  82207. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82208. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82209. return 0;
  82210. }
  82211. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82212. return 1;
  82213. }
  82214. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82215. return 2;
  82216. }
  82217. return -1;
  82218. };
  82219. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82220. var needToCreateLine;
  82221. if (edge === undefined) {
  82222. needToCreateLine = true;
  82223. }
  82224. else {
  82225. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82226. needToCreateLine = dotProduct < this._epsilon;
  82227. }
  82228. if (needToCreateLine) {
  82229. var offset = this._linesPositions.length / 3;
  82230. var normal = p0.subtract(p1);
  82231. normal.normalize();
  82232. // Positions
  82233. this._linesPositions.push(p0.x);
  82234. this._linesPositions.push(p0.y);
  82235. this._linesPositions.push(p0.z);
  82236. this._linesPositions.push(p0.x);
  82237. this._linesPositions.push(p0.y);
  82238. this._linesPositions.push(p0.z);
  82239. this._linesPositions.push(p1.x);
  82240. this._linesPositions.push(p1.y);
  82241. this._linesPositions.push(p1.z);
  82242. this._linesPositions.push(p1.x);
  82243. this._linesPositions.push(p1.y);
  82244. this._linesPositions.push(p1.z);
  82245. // Normals
  82246. this._linesNormals.push(p1.x);
  82247. this._linesNormals.push(p1.y);
  82248. this._linesNormals.push(p1.z);
  82249. this._linesNormals.push(-1);
  82250. this._linesNormals.push(p1.x);
  82251. this._linesNormals.push(p1.y);
  82252. this._linesNormals.push(p1.z);
  82253. this._linesNormals.push(1);
  82254. this._linesNormals.push(p0.x);
  82255. this._linesNormals.push(p0.y);
  82256. this._linesNormals.push(p0.z);
  82257. this._linesNormals.push(-1);
  82258. this._linesNormals.push(p0.x);
  82259. this._linesNormals.push(p0.y);
  82260. this._linesNormals.push(p0.z);
  82261. this._linesNormals.push(1);
  82262. // Indices
  82263. this._linesIndices.push(offset);
  82264. this._linesIndices.push(offset + 1);
  82265. this._linesIndices.push(offset + 2);
  82266. this._linesIndices.push(offset);
  82267. this._linesIndices.push(offset + 2);
  82268. this._linesIndices.push(offset + 3);
  82269. }
  82270. };
  82271. EdgesRenderer.prototype._generateEdgesLines = function () {
  82272. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82273. var indices = this._source.getIndices();
  82274. if (!indices || !positions) {
  82275. return;
  82276. }
  82277. // First let's find adjacencies
  82278. var adjacencies = new Array();
  82279. var faceNormals = new Array();
  82280. var index;
  82281. var faceAdjacencies;
  82282. // Prepare faces
  82283. for (index = 0; index < indices.length; index += 3) {
  82284. faceAdjacencies = new FaceAdjacencies();
  82285. var p0Index = indices[index];
  82286. var p1Index = indices[index + 1];
  82287. var p2Index = indices[index + 2];
  82288. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82289. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82290. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82291. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82292. faceNormal.normalize();
  82293. faceNormals.push(faceNormal);
  82294. adjacencies.push(faceAdjacencies);
  82295. }
  82296. // Scan
  82297. for (index = 0; index < adjacencies.length; index++) {
  82298. faceAdjacencies = adjacencies[index];
  82299. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82300. var otherFaceAdjacencies = adjacencies[otherIndex];
  82301. if (faceAdjacencies.edgesConnectedCount === 3) {
  82302. break;
  82303. }
  82304. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82305. continue;
  82306. }
  82307. var otherP0 = indices[otherIndex * 3];
  82308. var otherP1 = indices[otherIndex * 3 + 1];
  82309. var otherP2 = indices[otherIndex * 3 + 2];
  82310. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82311. var otherEdgeIndex = 0;
  82312. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82313. continue;
  82314. }
  82315. switch (edgeIndex) {
  82316. case 0:
  82317. if (this._checkVerticesInsteadOfIndices) {
  82318. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82319. }
  82320. else {
  82321. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82322. }
  82323. break;
  82324. case 1:
  82325. if (this._checkVerticesInsteadOfIndices) {
  82326. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82327. }
  82328. else {
  82329. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82330. }
  82331. break;
  82332. case 2:
  82333. if (this._checkVerticesInsteadOfIndices) {
  82334. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82335. }
  82336. else {
  82337. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82338. }
  82339. break;
  82340. }
  82341. if (otherEdgeIndex === -1) {
  82342. continue;
  82343. }
  82344. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82345. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82346. faceAdjacencies.edgesConnectedCount++;
  82347. otherFaceAdjacencies.edgesConnectedCount++;
  82348. if (faceAdjacencies.edgesConnectedCount === 3) {
  82349. break;
  82350. }
  82351. }
  82352. }
  82353. }
  82354. // Create lines
  82355. for (index = 0; index < adjacencies.length; index++) {
  82356. // 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
  82357. var current = adjacencies[index];
  82358. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82359. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82360. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82361. }
  82362. // Merge into a single mesh
  82363. var engine = this._source.getScene().getEngine();
  82364. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82365. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82366. this._ib = engine.createIndexBuffer(this._linesIndices);
  82367. this._indicesCount = this._linesIndices.length;
  82368. };
  82369. EdgesRenderer.prototype.render = function () {
  82370. var scene = this._source.getScene();
  82371. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82372. return;
  82373. }
  82374. var engine = scene.getEngine();
  82375. this._lineShader._preBind();
  82376. // VBOs
  82377. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82378. scene.resetCachedMaterial();
  82379. this._lineShader.setColor4("color", this._source.edgesColor);
  82380. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82381. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82382. }
  82383. else {
  82384. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82385. }
  82386. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82387. this._lineShader.bind(this._source.getWorldMatrix());
  82388. // Draw order
  82389. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82390. this._lineShader.unbind();
  82391. engine.setDepthWrite(true);
  82392. };
  82393. return EdgesRenderer;
  82394. }());
  82395. BABYLON.EdgesRenderer = EdgesRenderer;
  82396. })(BABYLON || (BABYLON = {}));
  82397. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82398. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82399. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82400. s = arguments[i];
  82401. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82402. t[p] = s[p];
  82403. }
  82404. return t;
  82405. };
  82406. var BABYLON;
  82407. (function (BABYLON) {
  82408. /**
  82409. * The effect layer Helps adding post process effect blended with the main pass.
  82410. *
  82411. * This can be for instance use to generate glow or higlight effects on the scene.
  82412. *
  82413. * The effect layer class can not be used directly and is intented to inherited from to be
  82414. * customized per effects.
  82415. */
  82416. var EffectLayer = /** @class */ (function () {
  82417. /**
  82418. * Instantiates a new effect Layer and references it in the scene.
  82419. * @param name The name of the layer
  82420. * @param scene The scene to use the layer in
  82421. */
  82422. function EffectLayer(
  82423. /** The Friendly of the effect in the scene */
  82424. name, scene) {
  82425. this.name = name;
  82426. this._vertexBuffers = {};
  82427. this._maxSize = 0;
  82428. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82429. this._shouldRender = true;
  82430. this._postProcesses = [];
  82431. this._textures = [];
  82432. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82433. /**
  82434. * The clear color of the texture used to generate the glow map.
  82435. */
  82436. this.neutralColor = new BABYLON.Color4();
  82437. /**
  82438. * Specifies wether the highlight layer is enabled or not.
  82439. */
  82440. this.isEnabled = true;
  82441. /**
  82442. * An event triggered when the effect layer has been disposed.
  82443. */
  82444. this.onDisposeObservable = new BABYLON.Observable();
  82445. /**
  82446. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82447. */
  82448. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82449. /**
  82450. * An event triggered when the generated texture is being merged in the scene.
  82451. */
  82452. this.onBeforeComposeObservable = new BABYLON.Observable();
  82453. /**
  82454. * An event triggered when the generated texture has been merged in the scene.
  82455. */
  82456. this.onAfterComposeObservable = new BABYLON.Observable();
  82457. /**
  82458. * An event triggered when the efffect layer changes its size.
  82459. */
  82460. this.onSizeChangedObservable = new BABYLON.Observable();
  82461. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82462. this._engine = scene.getEngine();
  82463. this._maxSize = this._engine.getCaps().maxTextureSize;
  82464. this._scene.effectLayers.push(this);
  82465. // Generate Buffers
  82466. this._generateIndexBuffer();
  82467. this._genrateVertexBuffer();
  82468. }
  82469. Object.defineProperty(EffectLayer.prototype, "camera", {
  82470. /**
  82471. * Gets the camera attached to the layer.
  82472. */
  82473. get: function () {
  82474. return this._effectLayerOptions.camera;
  82475. },
  82476. enumerable: true,
  82477. configurable: true
  82478. });
  82479. /**
  82480. * Initializes the effect layer with the required options.
  82481. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82482. */
  82483. EffectLayer.prototype._init = function (options) {
  82484. // Adapt options
  82485. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82486. this._setMainTextureSize();
  82487. this._createMainTexture();
  82488. this._createTextureAndPostProcesses();
  82489. this._mergeEffect = this._createMergeEffect();
  82490. };
  82491. /**
  82492. * Generates the index buffer of the full screen quad blending to the main canvas.
  82493. */
  82494. EffectLayer.prototype._generateIndexBuffer = function () {
  82495. // Indices
  82496. var indices = [];
  82497. indices.push(0);
  82498. indices.push(1);
  82499. indices.push(2);
  82500. indices.push(0);
  82501. indices.push(2);
  82502. indices.push(3);
  82503. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82504. };
  82505. /**
  82506. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82507. */
  82508. EffectLayer.prototype._genrateVertexBuffer = function () {
  82509. // VBO
  82510. var vertices = [];
  82511. vertices.push(1, 1);
  82512. vertices.push(-1, 1);
  82513. vertices.push(-1, -1);
  82514. vertices.push(1, -1);
  82515. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82516. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82517. };
  82518. /**
  82519. * Sets the main texture desired size which is the closest power of two
  82520. * of the engine canvas size.
  82521. */
  82522. EffectLayer.prototype._setMainTextureSize = function () {
  82523. if (this._effectLayerOptions.mainTextureFixedSize) {
  82524. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82525. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82526. }
  82527. else {
  82528. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82529. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82530. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82531. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82532. }
  82533. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82534. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82535. };
  82536. /**
  82537. * Creates the main texture for the effect layer.
  82538. */
  82539. EffectLayer.prototype._createMainTexture = function () {
  82540. var _this = this;
  82541. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82542. width: this._mainTextureDesiredSize.width,
  82543. height: this._mainTextureDesiredSize.height
  82544. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82545. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82546. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82547. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82548. this._mainTexture.anisotropicFilteringLevel = 1;
  82549. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82550. this._mainTexture.renderParticles = false;
  82551. this._mainTexture.renderList = null;
  82552. this._mainTexture.ignoreCameraViewport = true;
  82553. // Custom render function
  82554. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82555. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82556. var index;
  82557. var engine = _this._scene.getEngine();
  82558. if (depthOnlySubMeshes.length) {
  82559. engine.setColorWrite(false);
  82560. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82561. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82562. }
  82563. engine.setColorWrite(true);
  82564. }
  82565. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82566. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82567. }
  82568. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82569. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82570. }
  82571. for (index = 0; index < transparentSubMeshes.length; index++) {
  82572. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82573. }
  82574. };
  82575. this._mainTexture.onClearObservable.add(function (engine) {
  82576. engine.clear(_this.neutralColor, true, true, true);
  82577. });
  82578. };
  82579. /**
  82580. * Checks for the readiness of the element composing the layer.
  82581. * @param subMesh the mesh to check for
  82582. * @param useInstances specify wether or not to use instances to render the mesh
  82583. * @param emissiveTexture the associated emissive texture used to generate the glow
  82584. * @return true if ready otherwise, false
  82585. */
  82586. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82587. var material = subMesh.getMaterial();
  82588. if (!material) {
  82589. return false;
  82590. }
  82591. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82592. return false;
  82593. }
  82594. var defines = [];
  82595. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82596. var mesh = subMesh.getMesh();
  82597. var uv1 = false;
  82598. var uv2 = false;
  82599. // Alpha test
  82600. if (material && material.needAlphaTesting()) {
  82601. var alphaTexture = material.getAlphaTestTexture();
  82602. if (alphaTexture) {
  82603. defines.push("#define ALPHATEST");
  82604. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82605. alphaTexture.coordinatesIndex === 1) {
  82606. defines.push("#define DIFFUSEUV2");
  82607. uv2 = true;
  82608. }
  82609. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82610. defines.push("#define DIFFUSEUV1");
  82611. uv1 = true;
  82612. }
  82613. }
  82614. }
  82615. // Emissive
  82616. if (emissiveTexture) {
  82617. defines.push("#define EMISSIVE");
  82618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82619. emissiveTexture.coordinatesIndex === 1) {
  82620. defines.push("#define EMISSIVEUV2");
  82621. uv2 = true;
  82622. }
  82623. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82624. defines.push("#define EMISSIVEUV1");
  82625. uv1 = true;
  82626. }
  82627. }
  82628. if (uv1) {
  82629. attribs.push(BABYLON.VertexBuffer.UVKind);
  82630. defines.push("#define UV1");
  82631. }
  82632. if (uv2) {
  82633. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82634. defines.push("#define UV2");
  82635. }
  82636. // Bones
  82637. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82638. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82639. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82640. if (mesh.numBoneInfluencers > 4) {
  82641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82643. }
  82644. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82645. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82646. }
  82647. else {
  82648. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82649. }
  82650. // Instances
  82651. if (useInstances) {
  82652. defines.push("#define INSTANCES");
  82653. attribs.push("world0");
  82654. attribs.push("world1");
  82655. attribs.push("world2");
  82656. attribs.push("world3");
  82657. }
  82658. // Get correct effect
  82659. var join = defines.join("\n");
  82660. if (this._cachedDefines !== join) {
  82661. this._cachedDefines = join;
  82662. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82663. }
  82664. return this._effectLayerMapGenerationEffect.isReady();
  82665. };
  82666. /**
  82667. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82668. */
  82669. EffectLayer.prototype.render = function () {
  82670. var currentEffect = this._mergeEffect;
  82671. // Check
  82672. if (!currentEffect.isReady())
  82673. return;
  82674. for (var i = 0; i < this._postProcesses.length; i++) {
  82675. if (!this._postProcesses[i].isReady()) {
  82676. return;
  82677. }
  82678. }
  82679. var engine = this._scene.getEngine();
  82680. this.onBeforeComposeObservable.notifyObservers(this);
  82681. // Render
  82682. engine.enableEffect(currentEffect);
  82683. engine.setState(false);
  82684. // VBOs
  82685. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82686. // Cache
  82687. var previousAlphaMode = engine.getAlphaMode();
  82688. // Go Blend.
  82689. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82690. // Blends the map on the main canvas.
  82691. this._internalRender(currentEffect);
  82692. // Restore Alpha
  82693. engine.setAlphaMode(previousAlphaMode);
  82694. this.onAfterComposeObservable.notifyObservers(this);
  82695. // Handle size changes.
  82696. var size = this._mainTexture.getSize();
  82697. this._setMainTextureSize();
  82698. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82699. // Recreate RTT and post processes on size change.
  82700. this.onSizeChangedObservable.notifyObservers(this);
  82701. this._disposeTextureAndPostProcesses();
  82702. this._createMainTexture();
  82703. this._createTextureAndPostProcesses();
  82704. }
  82705. };
  82706. /**
  82707. * Determine if a given mesh will be used in the current effect.
  82708. * @param mesh mesh to test
  82709. * @returns true if the mesh will be used
  82710. */
  82711. EffectLayer.prototype.hasMesh = function (mesh) {
  82712. return true;
  82713. };
  82714. /**
  82715. * Returns true if the layer contains information to display, otherwise false.
  82716. * @returns true if the glow layer should be rendered
  82717. */
  82718. EffectLayer.prototype.shouldRender = function () {
  82719. return this.isEnabled && this._shouldRender;
  82720. };
  82721. /**
  82722. * Returns true if the mesh should render, otherwise false.
  82723. * @param mesh The mesh to render
  82724. * @returns true if it should render otherwise false
  82725. */
  82726. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82727. return true;
  82728. };
  82729. /**
  82730. * Returns true if the mesh should render, otherwise false.
  82731. * @param mesh The mesh to render
  82732. * @returns true if it should render otherwise false
  82733. */
  82734. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82735. return true;
  82736. };
  82737. /**
  82738. * Renders the submesh passed in parameter to the generation map.
  82739. */
  82740. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82741. var _this = this;
  82742. if (!this.shouldRender()) {
  82743. return;
  82744. }
  82745. var material = subMesh.getMaterial();
  82746. var mesh = subMesh.getRenderingMesh();
  82747. var scene = this._scene;
  82748. var engine = scene.getEngine();
  82749. if (!material) {
  82750. return;
  82751. }
  82752. // Do not block in blend mode.
  82753. if (material.needAlphaBlendingForMesh(mesh)) {
  82754. return;
  82755. }
  82756. // Culling
  82757. engine.setState(material.backFaceCulling);
  82758. // Managing instances
  82759. var batch = mesh._getInstancesRenderList(subMesh._id);
  82760. if (batch.mustReturn) {
  82761. return;
  82762. }
  82763. // Early Exit per mesh
  82764. if (!this._shouldRenderMesh(mesh)) {
  82765. return;
  82766. }
  82767. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82768. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82769. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82770. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82771. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82772. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82773. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82774. // Alpha test
  82775. if (material && material.needAlphaTesting()) {
  82776. var alphaTexture = material.getAlphaTestTexture();
  82777. if (alphaTexture) {
  82778. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82779. var textureMatrix = alphaTexture.getTextureMatrix();
  82780. if (textureMatrix) {
  82781. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82782. }
  82783. }
  82784. }
  82785. // Glow emissive only
  82786. if (this._emissiveTextureAndColor.texture) {
  82787. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82788. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82789. }
  82790. // Bones
  82791. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82792. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82793. }
  82794. // Draw
  82795. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82796. }
  82797. else {
  82798. // Need to reset refresh rate of the shadowMap
  82799. this._mainTexture.resetRefreshCounter();
  82800. }
  82801. };
  82802. /**
  82803. * Rebuild the required buffers.
  82804. * @ignore Internal use only.
  82805. */
  82806. EffectLayer.prototype._rebuild = function () {
  82807. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82808. if (vb) {
  82809. vb._rebuild();
  82810. }
  82811. this._generateIndexBuffer();
  82812. };
  82813. /**
  82814. * Dispose only the render target textures and post process.
  82815. */
  82816. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82817. this._mainTexture.dispose();
  82818. for (var i = 0; i < this._postProcesses.length; i++) {
  82819. if (this._postProcesses[i]) {
  82820. this._postProcesses[i].dispose();
  82821. }
  82822. }
  82823. this._postProcesses = [];
  82824. for (var i = 0; i < this._textures.length; i++) {
  82825. if (this._textures[i]) {
  82826. this._textures[i].dispose();
  82827. }
  82828. }
  82829. this._textures = [];
  82830. };
  82831. /**
  82832. * Dispose the highlight layer and free resources.
  82833. */
  82834. EffectLayer.prototype.dispose = function () {
  82835. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82836. if (vertexBuffer) {
  82837. vertexBuffer.dispose();
  82838. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82839. }
  82840. if (this._indexBuffer) {
  82841. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82842. this._indexBuffer = null;
  82843. }
  82844. // Clean textures and post processes
  82845. this._disposeTextureAndPostProcesses();
  82846. // Remove from scene
  82847. var index = this._scene.effectLayers.indexOf(this, 0);
  82848. if (index > -1) {
  82849. this._scene.effectLayers.splice(index, 1);
  82850. }
  82851. // Callback
  82852. this.onDisposeObservable.notifyObservers(this);
  82853. this.onDisposeObservable.clear();
  82854. this.onBeforeRenderMainTextureObservable.clear();
  82855. this.onBeforeComposeObservable.clear();
  82856. this.onAfterComposeObservable.clear();
  82857. this.onSizeChangedObservable.clear();
  82858. };
  82859. return EffectLayer;
  82860. }());
  82861. BABYLON.EffectLayer = EffectLayer;
  82862. })(BABYLON || (BABYLON = {}));
  82863. //# sourceMappingURL=babylon.effectLayer.js.map
  82864. var BABYLON;
  82865. (function (BABYLON) {
  82866. /**
  82867. * Special Glow Blur post process only blurring the alpha channel
  82868. * It enforces keeping the most luminous color in the color channel.
  82869. */
  82870. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82871. __extends(GlowBlurPostProcess, _super);
  82872. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82874. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82875. _this.direction = direction;
  82876. _this.kernel = kernel;
  82877. _this.onApplyObservable.add(function (effect) {
  82878. effect.setFloat2("screenSize", _this.width, _this.height);
  82879. effect.setVector2("direction", _this.direction);
  82880. effect.setFloat("blurWidth", _this.kernel);
  82881. });
  82882. return _this;
  82883. }
  82884. return GlowBlurPostProcess;
  82885. }(BABYLON.PostProcess));
  82886. /**
  82887. * The highlight layer Helps adding a glow effect around a mesh.
  82888. *
  82889. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82890. * glowy meshes to your scene.
  82891. *
  82892. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82893. */
  82894. var HighlightLayer = /** @class */ (function (_super) {
  82895. __extends(HighlightLayer, _super);
  82896. /**
  82897. * Instantiates a new highlight Layer and references it to the scene..
  82898. * @param name The name of the layer
  82899. * @param scene The scene to use the layer in
  82900. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82901. */
  82902. function HighlightLayer(name, scene, options) {
  82903. var _this = _super.call(this, name, scene) || this;
  82904. _this.name = name;
  82905. /**
  82906. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82907. */
  82908. _this.innerGlow = true;
  82909. /**
  82910. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82911. */
  82912. _this.outerGlow = true;
  82913. /**
  82914. * An event triggered when the highlight layer is being blurred.
  82915. */
  82916. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82917. /**
  82918. * An event triggered when the highlight layer has been blurred.
  82919. */
  82920. _this.onAfterBlurObservable = new BABYLON.Observable();
  82921. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82922. _this._meshes = {};
  82923. _this._excludedMeshes = {};
  82924. _this.neutralColor = HighlightLayer.NeutralColor;
  82925. // Warn on stencil
  82926. if (!_this._engine.isStencilEnable) {
  82927. 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 }");
  82928. }
  82929. // Adapt options
  82930. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82931. // Initialize the layer
  82932. _this._init({
  82933. alphaBlendingMode: _this._options.alphaBlendingMode,
  82934. camera: _this._options.camera,
  82935. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82936. mainTextureRatio: _this._options.mainTextureRatio
  82937. });
  82938. return _this;
  82939. }
  82940. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82941. /**
  82942. * Gets the horizontal size of the blur.
  82943. */
  82944. get: function () {
  82945. return this._horizontalBlurPostprocess.kernel;
  82946. },
  82947. /**
  82948. * Specifies the horizontal size of the blur.
  82949. */
  82950. set: function (value) {
  82951. this._horizontalBlurPostprocess.kernel = value;
  82952. },
  82953. enumerable: true,
  82954. configurable: true
  82955. });
  82956. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82957. /**
  82958. * Gets the vertical size of the blur.
  82959. */
  82960. get: function () {
  82961. return this._verticalBlurPostprocess.kernel;
  82962. },
  82963. /**
  82964. * Specifies the vertical size of the blur.
  82965. */
  82966. set: function (value) {
  82967. this._verticalBlurPostprocess.kernel = value;
  82968. },
  82969. enumerable: true,
  82970. configurable: true
  82971. });
  82972. /**
  82973. * Get the effect name of the layer.
  82974. * @return The effect name
  82975. */
  82976. HighlightLayer.prototype.getEffectName = function () {
  82977. return HighlightLayer.EffectName;
  82978. };
  82979. /**
  82980. * Create the merge effect. This is the shader use to blit the information back
  82981. * to the main canvas at the end of the scene rendering.
  82982. */
  82983. HighlightLayer.prototype._createMergeEffect = function () {
  82984. // Effect
  82985. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82986. };
  82987. /**
  82988. * Creates the render target textures and post processes used in the highlight layer.
  82989. */
  82990. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82991. var _this = this;
  82992. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82993. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82994. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82995. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82996. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82997. width: blurTextureWidth,
  82998. height: blurTextureHeight
  82999. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83000. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83001. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83002. this._blurTexture.anisotropicFilteringLevel = 16;
  83003. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83004. this._blurTexture.renderParticles = false;
  83005. this._blurTexture.ignoreCameraViewport = true;
  83006. this._textures = [this._blurTexture];
  83007. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83008. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83009. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83010. effect.setTexture("textureSampler", _this._mainTexture);
  83011. });
  83012. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83013. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83014. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83015. });
  83016. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83017. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83018. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83019. });
  83020. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83021. }
  83022. else {
  83023. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83024. width: blurTextureWidth,
  83025. height: blurTextureHeight
  83026. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83027. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83028. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83029. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83030. effect.setTexture("textureSampler", _this._mainTexture);
  83031. });
  83032. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83033. width: blurTextureWidth,
  83034. height: blurTextureHeight
  83035. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83036. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83037. }
  83038. this._mainTexture.onAfterUnbindObservable.add(function () {
  83039. _this.onBeforeBlurObservable.notifyObservers(_this);
  83040. var internalTexture = _this._blurTexture.getInternalTexture();
  83041. if (internalTexture) {
  83042. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83043. }
  83044. _this.onAfterBlurObservable.notifyObservers(_this);
  83045. });
  83046. // Prevent autoClear.
  83047. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83048. };
  83049. /**
  83050. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83051. */
  83052. HighlightLayer.prototype.needStencil = function () {
  83053. return true;
  83054. };
  83055. /**
  83056. * Checks for the readiness of the element composing the layer.
  83057. * @param subMesh the mesh to check for
  83058. * @param useInstances specify wether or not to use instances to render the mesh
  83059. * @param emissiveTexture the associated emissive texture used to generate the glow
  83060. * @return true if ready otherwise, false
  83061. */
  83062. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83063. var material = subMesh.getMaterial();
  83064. var mesh = subMesh.getRenderingMesh();
  83065. if (!material || !mesh || !this._meshes) {
  83066. return false;
  83067. }
  83068. var emissiveTexture = null;
  83069. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83070. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83071. emissiveTexture = material.emissiveTexture;
  83072. }
  83073. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83074. };
  83075. /**
  83076. * Implementation specific of rendering the generating effect on the main canvas.
  83077. * @param effect The effect used to render through
  83078. */
  83079. HighlightLayer.prototype._internalRender = function (effect) {
  83080. // Texture
  83081. effect.setTexture("textureSampler", this._blurTexture);
  83082. // Cache
  83083. var engine = this._engine;
  83084. var previousStencilBuffer = engine.getStencilBuffer();
  83085. var previousStencilFunction = engine.getStencilFunction();
  83086. var previousStencilMask = engine.getStencilMask();
  83087. var previousStencilOperationPass = engine.getStencilOperationPass();
  83088. var previousStencilOperationFail = engine.getStencilOperationFail();
  83089. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83090. // Stencil operations
  83091. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83092. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83093. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83094. // Draw order
  83095. engine.setStencilMask(0x00);
  83096. engine.setStencilBuffer(true);
  83097. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83098. // 2 passes inner outer
  83099. if (this.outerGlow) {
  83100. effect.setFloat("offset", 0);
  83101. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83102. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83103. }
  83104. if (this.innerGlow) {
  83105. effect.setFloat("offset", 1);
  83106. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83107. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83108. }
  83109. // Restore Cache
  83110. engine.setStencilFunction(previousStencilFunction);
  83111. engine.setStencilMask(previousStencilMask);
  83112. engine.setStencilBuffer(previousStencilBuffer);
  83113. engine.setStencilOperationPass(previousStencilOperationPass);
  83114. engine.setStencilOperationFail(previousStencilOperationFail);
  83115. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83116. };
  83117. /**
  83118. * Returns true if the layer contains information to display, otherwise false.
  83119. */
  83120. HighlightLayer.prototype.shouldRender = function () {
  83121. if (_super.prototype.shouldRender.call(this)) {
  83122. return this._meshes ? true : false;
  83123. }
  83124. return false;
  83125. };
  83126. /**
  83127. * Returns true if the mesh should render, otherwise false.
  83128. * @param mesh The mesh to render
  83129. * @returns true if it should render otherwise false
  83130. */
  83131. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83132. // Excluded Mesh
  83133. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83134. return false;
  83135. }
  83136. ;
  83137. return true;
  83138. };
  83139. /**
  83140. * Sets the required values for both the emissive texture and and the main color.
  83141. */
  83142. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83143. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83144. if (highlightLayerMesh) {
  83145. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83146. }
  83147. else {
  83148. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83149. }
  83150. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83151. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83152. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83153. }
  83154. else {
  83155. this._emissiveTextureAndColor.texture = null;
  83156. }
  83157. };
  83158. /**
  83159. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83160. * @param mesh The mesh to exclude from the highlight layer
  83161. */
  83162. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83163. if (!this._excludedMeshes) {
  83164. return;
  83165. }
  83166. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83167. if (!meshExcluded) {
  83168. this._excludedMeshes[mesh.uniqueId] = {
  83169. mesh: mesh,
  83170. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83171. mesh.getEngine().setStencilBuffer(false);
  83172. }),
  83173. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83174. mesh.getEngine().setStencilBuffer(true);
  83175. }),
  83176. };
  83177. }
  83178. };
  83179. /**
  83180. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83181. * @param mesh The mesh to highlight
  83182. */
  83183. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83184. if (!this._excludedMeshes) {
  83185. return;
  83186. }
  83187. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83188. if (meshExcluded) {
  83189. if (meshExcluded.beforeRender) {
  83190. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83191. }
  83192. if (meshExcluded.afterRender) {
  83193. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83194. }
  83195. }
  83196. this._excludedMeshes[mesh.uniqueId] = null;
  83197. };
  83198. /**
  83199. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83200. * @param mesh mesh to test
  83201. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83202. */
  83203. HighlightLayer.prototype.hasMesh = function (mesh) {
  83204. if (!this._meshes) {
  83205. return false;
  83206. }
  83207. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83208. };
  83209. /**
  83210. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83211. * @param mesh The mesh to highlight
  83212. * @param color The color of the highlight
  83213. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83214. */
  83215. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83216. var _this = this;
  83217. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83218. if (!this._meshes) {
  83219. return;
  83220. }
  83221. var meshHighlight = this._meshes[mesh.uniqueId];
  83222. if (meshHighlight) {
  83223. meshHighlight.color = color;
  83224. }
  83225. else {
  83226. this._meshes[mesh.uniqueId] = {
  83227. mesh: mesh,
  83228. color: color,
  83229. // Lambda required for capture due to Observable this context
  83230. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83231. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83232. _this._defaultStencilReference(mesh);
  83233. }
  83234. else {
  83235. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83236. }
  83237. }),
  83238. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83239. glowEmissiveOnly: glowEmissiveOnly
  83240. };
  83241. }
  83242. this._shouldRender = true;
  83243. };
  83244. /**
  83245. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83246. * @param mesh The mesh to highlight
  83247. */
  83248. HighlightLayer.prototype.removeMesh = function (mesh) {
  83249. if (!this._meshes) {
  83250. return;
  83251. }
  83252. var meshHighlight = this._meshes[mesh.uniqueId];
  83253. if (meshHighlight) {
  83254. if (meshHighlight.observerHighlight) {
  83255. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83256. }
  83257. if (meshHighlight.observerDefault) {
  83258. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83259. }
  83260. delete this._meshes[mesh.uniqueId];
  83261. }
  83262. this._shouldRender = false;
  83263. for (var meshHighlightToCheck in this._meshes) {
  83264. if (this._meshes[meshHighlightToCheck]) {
  83265. this._shouldRender = true;
  83266. break;
  83267. }
  83268. }
  83269. };
  83270. /**
  83271. * Force the stencil to the normal expected value for none glowing parts
  83272. */
  83273. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83274. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83275. };
  83276. /**
  83277. * Free any resources and references associated to a mesh.
  83278. * Internal use
  83279. * @param mesh The mesh to free.
  83280. */
  83281. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83282. this.removeMesh(mesh);
  83283. this.removeExcludedMesh(mesh);
  83284. };
  83285. /**
  83286. * Dispose the highlight layer and free resources.
  83287. */
  83288. HighlightLayer.prototype.dispose = function () {
  83289. if (this._meshes) {
  83290. // Clean mesh references
  83291. for (var id in this._meshes) {
  83292. var meshHighlight = this._meshes[id];
  83293. if (meshHighlight && meshHighlight.mesh) {
  83294. if (meshHighlight.observerHighlight) {
  83295. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83296. }
  83297. if (meshHighlight.observerDefault) {
  83298. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83299. }
  83300. }
  83301. }
  83302. this._meshes = null;
  83303. }
  83304. if (this._excludedMeshes) {
  83305. for (var id in this._excludedMeshes) {
  83306. var meshHighlight = this._excludedMeshes[id];
  83307. if (meshHighlight) {
  83308. if (meshHighlight.beforeRender) {
  83309. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83310. }
  83311. if (meshHighlight.afterRender) {
  83312. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83313. }
  83314. }
  83315. }
  83316. this._excludedMeshes = null;
  83317. }
  83318. _super.prototype.dispose.call(this);
  83319. };
  83320. /**
  83321. * Effect Name of the highlight layer.
  83322. */
  83323. HighlightLayer.EffectName = "HighlightLayer";
  83324. /**
  83325. * The neutral color used during the preparation of the glow effect.
  83326. * This is black by default as the blend operation is a blend operation.
  83327. */
  83328. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83329. /**
  83330. * Stencil value used for glowing meshes.
  83331. */
  83332. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83333. /**
  83334. * Stencil value used for the other meshes in the scene.
  83335. */
  83336. HighlightLayer.NormalMeshStencilReference = 0x01;
  83337. return HighlightLayer;
  83338. }(BABYLON.EffectLayer));
  83339. BABYLON.HighlightLayer = HighlightLayer;
  83340. })(BABYLON || (BABYLON = {}));
  83341. //# sourceMappingURL=babylon.highlightLayer.js.map
  83342. var BABYLON;
  83343. (function (BABYLON) {
  83344. /**
  83345. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83346. *
  83347. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83348. * glowy meshes to your scene.
  83349. *
  83350. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83351. */
  83352. var GlowLayer = /** @class */ (function (_super) {
  83353. __extends(GlowLayer, _super);
  83354. /**
  83355. * Instantiates a new glow Layer and references it to the scene.
  83356. * @param name The name of the layer
  83357. * @param scene The scene to use the layer in
  83358. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83359. */
  83360. function GlowLayer(name, scene, options) {
  83361. var _this = _super.call(this, name, scene) || this;
  83362. _this.name = name;
  83363. _this._intensity = 1.0;
  83364. _this._includedOnlyMeshes = [];
  83365. _this._excludedMeshes = [];
  83366. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83367. // Adapt options
  83368. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83369. // Initialize the layer
  83370. _this._init({
  83371. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83372. camera: _this._options.camera,
  83373. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83374. mainTextureRatio: _this._options.mainTextureRatio
  83375. });
  83376. return _this;
  83377. }
  83378. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83379. /**
  83380. * Gets the kernel size of the blur.
  83381. */
  83382. get: function () {
  83383. return this._horizontalBlurPostprocess1.kernel;
  83384. },
  83385. /**
  83386. * Sets the kernel size of the blur.
  83387. */
  83388. set: function (value) {
  83389. this._horizontalBlurPostprocess1.kernel = value;
  83390. this._verticalBlurPostprocess1.kernel = value;
  83391. this._horizontalBlurPostprocess2.kernel = value;
  83392. this._verticalBlurPostprocess2.kernel = value;
  83393. },
  83394. enumerable: true,
  83395. configurable: true
  83396. });
  83397. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83398. /**
  83399. * Gets the glow intensity.
  83400. */
  83401. get: function () {
  83402. return this._intensity;
  83403. },
  83404. /**
  83405. * Sets the glow intensity.
  83406. */
  83407. set: function (value) {
  83408. this._intensity = value;
  83409. },
  83410. enumerable: true,
  83411. configurable: true
  83412. });
  83413. /**
  83414. * Get the effect name of the layer.
  83415. * @return The effect name
  83416. */
  83417. GlowLayer.prototype.getEffectName = function () {
  83418. return GlowLayer.EffectName;
  83419. };
  83420. /**
  83421. * Create the merge effect. This is the shader use to blit the information back
  83422. * to the main canvas at the end of the scene rendering.
  83423. */
  83424. GlowLayer.prototype._createMergeEffect = function () {
  83425. // Effect
  83426. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83427. };
  83428. /**
  83429. * Creates the render target textures and post processes used in the glow layer.
  83430. */
  83431. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83432. var _this = this;
  83433. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83434. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83435. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83436. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83437. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83438. width: blurTextureWidth,
  83439. height: blurTextureHeight
  83440. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83441. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83442. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83443. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83444. this._blurTexture1.renderParticles = false;
  83445. this._blurTexture1.ignoreCameraViewport = true;
  83446. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83447. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83448. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83449. width: blurTextureWidth2,
  83450. height: blurTextureHeight2
  83451. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83452. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83453. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83454. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83455. this._blurTexture2.renderParticles = false;
  83456. this._blurTexture2.ignoreCameraViewport = true;
  83457. this._textures = [this._blurTexture1, this._blurTexture2];
  83458. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83459. width: blurTextureWidth,
  83460. height: blurTextureHeight
  83461. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83462. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83463. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83464. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83465. effect.setTexture("textureSampler", _this._mainTexture);
  83466. });
  83467. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83468. width: blurTextureWidth,
  83469. height: blurTextureHeight
  83470. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83471. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83472. width: blurTextureWidth2,
  83473. height: blurTextureHeight2
  83474. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83475. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83476. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83477. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83478. effect.setTexture("textureSampler", _this._blurTexture1);
  83479. });
  83480. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83481. width: blurTextureWidth2,
  83482. height: blurTextureHeight2
  83483. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83484. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83485. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83486. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83487. this._mainTexture.samples = this._options.mainTextureSamples;
  83488. this._mainTexture.onAfterUnbindObservable.add(function () {
  83489. var internalTexture = _this._blurTexture1.getInternalTexture();
  83490. if (internalTexture) {
  83491. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83492. internalTexture = _this._blurTexture2.getInternalTexture();
  83493. if (internalTexture) {
  83494. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83495. }
  83496. }
  83497. });
  83498. // Prevent autoClear.
  83499. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83500. };
  83501. /**
  83502. * Checks for the readiness of the element composing the layer.
  83503. * @param subMesh the mesh to check for
  83504. * @param useInstances specify wether or not to use instances to render the mesh
  83505. * @param emissiveTexture the associated emissive texture used to generate the glow
  83506. * @return true if ready otherwise, false
  83507. */
  83508. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83509. var material = subMesh.getMaterial();
  83510. var mesh = subMesh.getRenderingMesh();
  83511. if (!material || !mesh) {
  83512. return false;
  83513. }
  83514. var emissiveTexture = material.emissiveTexture;
  83515. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83516. };
  83517. /**
  83518. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83519. */
  83520. GlowLayer.prototype.needStencil = function () {
  83521. return false;
  83522. };
  83523. /**
  83524. * Implementation specific of rendering the generating effect on the main canvas.
  83525. * @param effect The effect used to render through
  83526. */
  83527. GlowLayer.prototype._internalRender = function (effect) {
  83528. // Texture
  83529. effect.setTexture("textureSampler", this._blurTexture1);
  83530. effect.setTexture("textureSampler2", this._blurTexture2);
  83531. effect.setFloat("offset", this._intensity);
  83532. // Cache
  83533. var engine = this._engine;
  83534. var previousStencilBuffer = engine.getStencilBuffer();
  83535. // Draw order
  83536. engine.setStencilBuffer(false);
  83537. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83538. // Draw order
  83539. engine.setStencilBuffer(previousStencilBuffer);
  83540. };
  83541. /**
  83542. * Sets the required values for both the emissive texture and and the main color.
  83543. */
  83544. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83545. var textureLevel = 1.0;
  83546. if (this.customEmissiveTextureSelector) {
  83547. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83548. }
  83549. else {
  83550. if (material) {
  83551. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83552. if (this._emissiveTextureAndColor.texture) {
  83553. textureLevel = this._emissiveTextureAndColor.texture.level;
  83554. }
  83555. }
  83556. else {
  83557. this._emissiveTextureAndColor.texture = null;
  83558. }
  83559. }
  83560. if (this.customEmissiveColorSelector) {
  83561. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83562. }
  83563. else {
  83564. if (material.emissiveColor) {
  83565. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83566. }
  83567. else {
  83568. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83569. }
  83570. }
  83571. };
  83572. /**
  83573. * Returns true if the mesh should render, otherwise false.
  83574. * @param mesh The mesh to render
  83575. * @returns true if it should render otherwise false
  83576. */
  83577. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83578. return this.hasMesh(mesh);
  83579. };
  83580. /**
  83581. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83582. * @param mesh The mesh to exclude from the glow layer
  83583. */
  83584. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83585. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83586. this._excludedMeshes.push(mesh.uniqueId);
  83587. }
  83588. };
  83589. /**
  83590. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83591. * @param mesh The mesh to remove
  83592. */
  83593. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83594. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83595. if (index !== -1) {
  83596. this._excludedMeshes.splice(index, 1);
  83597. }
  83598. };
  83599. /**
  83600. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83601. * @param mesh The mesh to include in the glow layer
  83602. */
  83603. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83604. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83605. this._includedOnlyMeshes.push(mesh.uniqueId);
  83606. }
  83607. };
  83608. /**
  83609. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83610. * @param mesh The mesh to remove
  83611. */
  83612. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83613. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83614. if (index !== -1) {
  83615. this._includedOnlyMeshes.splice(index, 1);
  83616. }
  83617. };
  83618. /**
  83619. * Determine if a given mesh will be used in the glow layer
  83620. * @param mesh The mesh to test
  83621. * @returns true if the mesh will be highlighted by the current glow layer
  83622. */
  83623. GlowLayer.prototype.hasMesh = function (mesh) {
  83624. // Included Mesh
  83625. if (this._includedOnlyMeshes.length) {
  83626. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83627. }
  83628. ;
  83629. // Excluded Mesh
  83630. if (this._excludedMeshes.length) {
  83631. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83632. }
  83633. ;
  83634. return true;
  83635. };
  83636. /**
  83637. * Free any resources and references associated to a mesh.
  83638. * Internal use
  83639. * @param mesh The mesh to free.
  83640. */
  83641. GlowLayer.prototype._disposeMesh = function (mesh) {
  83642. this.removeIncludedOnlyMesh(mesh);
  83643. this.removeExcludedMesh(mesh);
  83644. };
  83645. /**
  83646. * Effect Name of the layer.
  83647. */
  83648. GlowLayer.EffectName = "GlowLayer";
  83649. /**
  83650. * The default blur kernel size used for the glow.
  83651. */
  83652. GlowLayer.DefaultBlurKernelSize = 32;
  83653. /**
  83654. * The default texture size ratio used for the glow.
  83655. */
  83656. GlowLayer.DefaultTextureRatio = 0.5;
  83657. return GlowLayer;
  83658. }(BABYLON.EffectLayer));
  83659. BABYLON.GlowLayer = GlowLayer;
  83660. })(BABYLON || (BABYLON = {}));
  83661. //# sourceMappingURL=babylon.glowLayer.js.map
  83662. var BABYLON;
  83663. (function (BABYLON) {
  83664. /**
  83665. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83666. */
  83667. var AssetTaskState;
  83668. (function (AssetTaskState) {
  83669. /**
  83670. * Initialization
  83671. */
  83672. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83673. /**
  83674. * Running
  83675. */
  83676. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83677. /**
  83678. * Done
  83679. */
  83680. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83681. /**
  83682. * Error
  83683. */
  83684. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83685. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83686. /**
  83687. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83688. */
  83689. var AbstractAssetTask = /** @class */ (function () {
  83690. /**
  83691. * Creates a new {BABYLON.AssetsManager}
  83692. * @param name defines the name of the task
  83693. */
  83694. function AbstractAssetTask(
  83695. /**
  83696. * Task name
  83697. */ name) {
  83698. this.name = name;
  83699. this._isCompleted = false;
  83700. this._taskState = AssetTaskState.INIT;
  83701. }
  83702. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83703. /**
  83704. * Get if the task is completed
  83705. */
  83706. get: function () {
  83707. return this._isCompleted;
  83708. },
  83709. enumerable: true,
  83710. configurable: true
  83711. });
  83712. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83713. /**
  83714. * Gets the current state of the task
  83715. */
  83716. get: function () {
  83717. return this._taskState;
  83718. },
  83719. enumerable: true,
  83720. configurable: true
  83721. });
  83722. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83723. /**
  83724. * Gets the current error object (if task is in error)
  83725. */
  83726. get: function () {
  83727. return this._errorObject;
  83728. },
  83729. enumerable: true,
  83730. configurable: true
  83731. });
  83732. /**
  83733. * Internal only
  83734. * @ignore
  83735. */
  83736. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83737. if (this._errorObject) {
  83738. return;
  83739. }
  83740. this._errorObject = {
  83741. message: message,
  83742. exception: exception
  83743. };
  83744. };
  83745. /**
  83746. * Execute the current task
  83747. * @param scene defines the scene where you want your assets to be loaded
  83748. * @param onSuccess is a callback called when the task is successfully executed
  83749. * @param onError is a callback called if an error occurs
  83750. */
  83751. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83752. var _this = this;
  83753. this._taskState = AssetTaskState.RUNNING;
  83754. this.runTask(scene, function () {
  83755. _this.onDoneCallback(onSuccess, onError);
  83756. }, function (msg, exception) {
  83757. _this.onErrorCallback(onError, msg, exception);
  83758. });
  83759. };
  83760. /**
  83761. * Execute the current task
  83762. * @param scene defines the scene where you want your assets to be loaded
  83763. * @param onSuccess is a callback called when the task is successfully executed
  83764. * @param onError is a callback called if an error occurs
  83765. */
  83766. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83767. throw new Error("runTask is not implemented");
  83768. };
  83769. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83770. this._taskState = AssetTaskState.ERROR;
  83771. this._errorObject = {
  83772. message: message,
  83773. exception: exception
  83774. };
  83775. if (this.onError) {
  83776. this.onError(this, message, exception);
  83777. }
  83778. onError();
  83779. };
  83780. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83781. try {
  83782. this._taskState = AssetTaskState.DONE;
  83783. this._isCompleted = true;
  83784. if (this.onSuccess) {
  83785. this.onSuccess(this);
  83786. }
  83787. onSuccess();
  83788. }
  83789. catch (e) {
  83790. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83791. }
  83792. };
  83793. return AbstractAssetTask;
  83794. }());
  83795. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83796. /**
  83797. * Class used to share progress information about assets loading
  83798. */
  83799. var AssetsProgressEvent = /** @class */ (function () {
  83800. /**
  83801. * Creates a {BABYLON.AssetsProgressEvent}
  83802. * @param remainingCount defines the number of remaining tasks to process
  83803. * @param totalCount defines the total number of tasks
  83804. * @param task defines the task that was just processed
  83805. */
  83806. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83807. this.remainingCount = remainingCount;
  83808. this.totalCount = totalCount;
  83809. this.task = task;
  83810. }
  83811. return AssetsProgressEvent;
  83812. }());
  83813. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83814. /**
  83815. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83816. */
  83817. var MeshAssetTask = /** @class */ (function (_super) {
  83818. __extends(MeshAssetTask, _super);
  83819. /**
  83820. * Creates a new {BABYLON.MeshAssetTask}
  83821. * @param name defines the name of the task
  83822. * @param meshesNames defines the list of mesh's names you want to load
  83823. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83824. * @param sceneFilename defines the filename of the scene to load from
  83825. */
  83826. function MeshAssetTask(
  83827. /**
  83828. * Defines the name of the task
  83829. */
  83830. name,
  83831. /**
  83832. * Defines the list of mesh's names you want to load
  83833. */
  83834. meshesNames,
  83835. /**
  83836. * Defines the root url to use as a base to load your meshes and associated resources
  83837. */
  83838. rootUrl,
  83839. /**
  83840. * Defines the filename of the scene to load from
  83841. */
  83842. sceneFilename) {
  83843. var _this = _super.call(this, name) || this;
  83844. _this.name = name;
  83845. _this.meshesNames = meshesNames;
  83846. _this.rootUrl = rootUrl;
  83847. _this.sceneFilename = sceneFilename;
  83848. return _this;
  83849. }
  83850. /**
  83851. * Execute the current task
  83852. * @param scene defines the scene where you want your assets to be loaded
  83853. * @param onSuccess is a callback called when the task is successfully executed
  83854. * @param onError is a callback called if an error occurs
  83855. */
  83856. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83857. var _this = this;
  83858. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83859. _this.loadedMeshes = meshes;
  83860. _this.loadedParticleSystems = particleSystems;
  83861. _this.loadedSkeletons = skeletons;
  83862. onSuccess();
  83863. }, null, function (scene, message, exception) {
  83864. onError(message, exception);
  83865. });
  83866. };
  83867. return MeshAssetTask;
  83868. }(AbstractAssetTask));
  83869. BABYLON.MeshAssetTask = MeshAssetTask;
  83870. /**
  83871. * Define a task used by {BABYLON.AssetsManager} to load text content
  83872. */
  83873. var TextFileAssetTask = /** @class */ (function (_super) {
  83874. __extends(TextFileAssetTask, _super);
  83875. /**
  83876. * Creates a new TextFileAssetTask object
  83877. * @param name defines the name of the task
  83878. * @param url defines the location of the file to load
  83879. */
  83880. function TextFileAssetTask(
  83881. /**
  83882. * Defines the name of the task
  83883. */
  83884. name,
  83885. /**
  83886. * Defines the location of the file to load
  83887. */
  83888. url) {
  83889. var _this = _super.call(this, name) || this;
  83890. _this.name = name;
  83891. _this.url = url;
  83892. return _this;
  83893. }
  83894. /**
  83895. * Execute the current task
  83896. * @param scene defines the scene where you want your assets to be loaded
  83897. * @param onSuccess is a callback called when the task is successfully executed
  83898. * @param onError is a callback called if an error occurs
  83899. */
  83900. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83901. var _this = this;
  83902. scene._loadFile(this.url, function (data) {
  83903. _this.text = data;
  83904. onSuccess();
  83905. }, undefined, false, false, function (request, exception) {
  83906. if (request) {
  83907. onError(request.status + " " + request.statusText, exception);
  83908. }
  83909. });
  83910. };
  83911. return TextFileAssetTask;
  83912. }(AbstractAssetTask));
  83913. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83914. /**
  83915. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83916. */
  83917. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83918. __extends(BinaryFileAssetTask, _super);
  83919. /**
  83920. * Creates a new BinaryFileAssetTask object
  83921. * @param name defines the name of the new task
  83922. * @param url defines the location of the file to load
  83923. */
  83924. function BinaryFileAssetTask(
  83925. /**
  83926. * Defines the name of the task
  83927. */
  83928. name,
  83929. /**
  83930. * Defines the location of the file to load
  83931. */
  83932. url) {
  83933. var _this = _super.call(this, name) || this;
  83934. _this.name = name;
  83935. _this.url = url;
  83936. return _this;
  83937. }
  83938. /**
  83939. * Execute the current task
  83940. * @param scene defines the scene where you want your assets to be loaded
  83941. * @param onSuccess is a callback called when the task is successfully executed
  83942. * @param onError is a callback called if an error occurs
  83943. */
  83944. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83945. var _this = this;
  83946. scene._loadFile(this.url, function (data) {
  83947. _this.data = data;
  83948. onSuccess();
  83949. }, undefined, true, true, function (request, exception) {
  83950. if (request) {
  83951. onError(request.status + " " + request.statusText, exception);
  83952. }
  83953. });
  83954. };
  83955. return BinaryFileAssetTask;
  83956. }(AbstractAssetTask));
  83957. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83958. /**
  83959. * Define a task used by {BABYLON.AssetsManager} to load images
  83960. */
  83961. var ImageAssetTask = /** @class */ (function (_super) {
  83962. __extends(ImageAssetTask, _super);
  83963. /**
  83964. * Creates a new ImageAssetTask
  83965. * @param name defines the name of the task
  83966. * @param url defines the location of the image to load
  83967. */
  83968. function ImageAssetTask(
  83969. /**
  83970. * Defines the name of the task
  83971. */
  83972. name,
  83973. /**
  83974. * Defines the location of the image to load
  83975. */
  83976. url) {
  83977. var _this = _super.call(this, name) || this;
  83978. _this.name = name;
  83979. _this.url = url;
  83980. return _this;
  83981. }
  83982. /**
  83983. * Execute the current task
  83984. * @param scene defines the scene where you want your assets to be loaded
  83985. * @param onSuccess is a callback called when the task is successfully executed
  83986. * @param onError is a callback called if an error occurs
  83987. */
  83988. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83989. var _this = this;
  83990. var img = new Image();
  83991. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83992. img.onload = function () {
  83993. _this.image = img;
  83994. onSuccess();
  83995. };
  83996. img.onerror = function (err) {
  83997. onError("Error loading image", err);
  83998. };
  83999. img.src = this.url;
  84000. };
  84001. return ImageAssetTask;
  84002. }(AbstractAssetTask));
  84003. BABYLON.ImageAssetTask = ImageAssetTask;
  84004. /**
  84005. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84006. */
  84007. var TextureAssetTask = /** @class */ (function (_super) {
  84008. __extends(TextureAssetTask, _super);
  84009. /**
  84010. * Creates a new TextureAssetTask object
  84011. * @param name defines the name of the task
  84012. * @param url defines the location of the file to load
  84013. * @param noMipmap defines if mipmap should not be generated (default is false)
  84014. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84015. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84016. */
  84017. function TextureAssetTask(
  84018. /**
  84019. * Defines the name of the task
  84020. */
  84021. name,
  84022. /**
  84023. * Defines the location of the file to load
  84024. */
  84025. url,
  84026. /**
  84027. * Defines if mipmap should not be generated (default is false)
  84028. */
  84029. noMipmap,
  84030. /**
  84031. * Defines if texture must be inverted on Y axis (default is false)
  84032. */
  84033. invertY,
  84034. /**
  84035. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84036. */
  84037. samplingMode) {
  84038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84039. var _this = _super.call(this, name) || this;
  84040. _this.name = name;
  84041. _this.url = url;
  84042. _this.noMipmap = noMipmap;
  84043. _this.invertY = invertY;
  84044. _this.samplingMode = samplingMode;
  84045. return _this;
  84046. }
  84047. /**
  84048. * Execute the current task
  84049. * @param scene defines the scene where you want your assets to be loaded
  84050. * @param onSuccess is a callback called when the task is successfully executed
  84051. * @param onError is a callback called if an error occurs
  84052. */
  84053. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84054. var onload = function () {
  84055. onSuccess();
  84056. };
  84057. var onerror = function (message, exception) {
  84058. onError(message, exception);
  84059. };
  84060. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84061. };
  84062. return TextureAssetTask;
  84063. }(AbstractAssetTask));
  84064. BABYLON.TextureAssetTask = TextureAssetTask;
  84065. /**
  84066. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84067. */
  84068. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84069. __extends(CubeTextureAssetTask, _super);
  84070. /**
  84071. * Creates a new CubeTextureAssetTask
  84072. * @param name defines the name of the task
  84073. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84074. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84075. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84076. * @param files defines the explicit list of files (undefined by default)
  84077. */
  84078. function CubeTextureAssetTask(
  84079. /**
  84080. * Defines the name of the task
  84081. */
  84082. name,
  84083. /**
  84084. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84085. */
  84086. url,
  84087. /**
  84088. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84089. */
  84090. extensions,
  84091. /**
  84092. * Defines if mipmaps should not be generated (default is false)
  84093. */
  84094. noMipmap,
  84095. /**
  84096. * Defines the explicit list of files (undefined by default)
  84097. */
  84098. files) {
  84099. var _this = _super.call(this, name) || this;
  84100. _this.name = name;
  84101. _this.url = url;
  84102. _this.extensions = extensions;
  84103. _this.noMipmap = noMipmap;
  84104. _this.files = files;
  84105. return _this;
  84106. }
  84107. /**
  84108. * Execute the current task
  84109. * @param scene defines the scene where you want your assets to be loaded
  84110. * @param onSuccess is a callback called when the task is successfully executed
  84111. * @param onError is a callback called if an error occurs
  84112. */
  84113. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84114. var onload = function () {
  84115. onSuccess();
  84116. };
  84117. var onerror = function (message, exception) {
  84118. onError(message, exception);
  84119. };
  84120. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84121. };
  84122. return CubeTextureAssetTask;
  84123. }(AbstractAssetTask));
  84124. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84125. /**
  84126. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84127. */
  84128. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84129. __extends(HDRCubeTextureAssetTask, _super);
  84130. /**
  84131. * Creates a new HDRCubeTextureAssetTask object
  84132. * @param name defines the name of the task
  84133. * @param url defines the location of the file to load
  84134. * @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.
  84135. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84136. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84137. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  84138. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84139. */
  84140. function HDRCubeTextureAssetTask(
  84141. /**
  84142. * Defines the name of the task
  84143. */
  84144. name,
  84145. /**
  84146. * Defines the location of the file to load
  84147. */
  84148. url,
  84149. /**
  84150. * 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.
  84151. */
  84152. size,
  84153. /**
  84154. * Defines if mipmaps should not be generated (default is false)
  84155. */
  84156. noMipmap,
  84157. /**
  84158. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84159. */
  84160. generateHarmonics,
  84161. /**
  84162. * 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)
  84163. */
  84164. useInGammaSpace,
  84165. /**
  84166. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84167. */
  84168. usePMREMGenerator) {
  84169. if (noMipmap === void 0) { noMipmap = false; }
  84170. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84171. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84172. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84173. var _this = _super.call(this, name) || this;
  84174. _this.name = name;
  84175. _this.url = url;
  84176. _this.size = size;
  84177. _this.noMipmap = noMipmap;
  84178. _this.generateHarmonics = generateHarmonics;
  84179. _this.useInGammaSpace = useInGammaSpace;
  84180. _this.usePMREMGenerator = usePMREMGenerator;
  84181. return _this;
  84182. }
  84183. /**
  84184. * Execute the current task
  84185. * @param scene defines the scene where you want your assets to be loaded
  84186. * @param onSuccess is a callback called when the task is successfully executed
  84187. * @param onError is a callback called if an error occurs
  84188. */
  84189. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84190. var onload = function () {
  84191. onSuccess();
  84192. };
  84193. var onerror = function (message, exception) {
  84194. onError(message, exception);
  84195. };
  84196. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84197. };
  84198. return HDRCubeTextureAssetTask;
  84199. }(AbstractAssetTask));
  84200. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84201. /**
  84202. * This class can be used to easily import assets into a scene
  84203. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84204. */
  84205. var AssetsManager = /** @class */ (function () {
  84206. /**
  84207. * Creates a new AssetsManager
  84208. * @param scene defines the scene to work on
  84209. */
  84210. function AssetsManager(scene) {
  84211. this._isLoading = false;
  84212. this._tasks = new Array();
  84213. this._waitingTasksCount = 0;
  84214. this._totalTasksCount = 0;
  84215. /**
  84216. * Observable called when all tasks are processed
  84217. */
  84218. this.onTaskSuccessObservable = new BABYLON.Observable();
  84219. /**
  84220. * Observable called when a task had an error
  84221. */
  84222. this.onTaskErrorObservable = new BABYLON.Observable();
  84223. /**
  84224. * Observable called when a task is successful
  84225. */
  84226. this.onTasksDoneObservable = new BABYLON.Observable();
  84227. /**
  84228. * Observable called when a task is done (whatever the result is)
  84229. */
  84230. this.onProgressObservable = new BABYLON.Observable();
  84231. /**
  84232. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84233. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84234. */
  84235. this.useDefaultLoadingScreen = true;
  84236. this._scene = scene;
  84237. }
  84238. /**
  84239. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84240. * @param taskName defines the name of the new task
  84241. * @param meshesNames defines the name of meshes to load
  84242. * @param rootUrl defines the root url to use to locate files
  84243. * @param sceneFilename defines the filename of the scene file
  84244. * @returns a new {BABYLON.MeshAssetTask} object
  84245. */
  84246. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84247. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84248. this._tasks.push(task);
  84249. return task;
  84250. };
  84251. /**
  84252. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84253. * @param taskName defines the name of the new task
  84254. * @param url defines the url of the file to load
  84255. * @returns a new {BABYLON.TextFileAssetTask} object
  84256. */
  84257. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84258. var task = new TextFileAssetTask(taskName, url);
  84259. this._tasks.push(task);
  84260. return task;
  84261. };
  84262. /**
  84263. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84264. * @param taskName defines the name of the new task
  84265. * @param url defines the url of the file to load
  84266. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84267. */
  84268. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84269. var task = new BinaryFileAssetTask(taskName, url);
  84270. this._tasks.push(task);
  84271. return task;
  84272. };
  84273. /**
  84274. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84275. * @param taskName defines the name of the new task
  84276. * @param url defines the url of the file to load
  84277. * @returns a new {BABYLON.ImageAssetTask} object
  84278. */
  84279. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84280. var task = new ImageAssetTask(taskName, url);
  84281. this._tasks.push(task);
  84282. return task;
  84283. };
  84284. /**
  84285. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84286. * @param taskName defines the name of the new task
  84287. * @param url defines the url of the file to load
  84288. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84289. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84290. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84291. * @returns a new {BABYLON.TextureAssetTask} object
  84292. */
  84293. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84295. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84296. this._tasks.push(task);
  84297. return task;
  84298. };
  84299. /**
  84300. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84301. * @param taskName defines the name of the new task
  84302. * @param url defines the url of the file to load
  84303. * @param extensions defines the extension to use to load the cube map (can be null)
  84304. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84305. * @param files defines the list of files to load (can be null)
  84306. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84307. */
  84308. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84309. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84310. this._tasks.push(task);
  84311. return task;
  84312. };
  84313. /**
  84314. *
  84315. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84316. * @param taskName defines the name of the new task
  84317. * @param url defines the url of the file to load
  84318. * @param size defines the size you want for the cubemap (can be null)
  84319. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84320. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84321. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84322. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84323. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84324. */
  84325. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84326. if (noMipmap === void 0) { noMipmap = false; }
  84327. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84328. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84329. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84330. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84331. this._tasks.push(task);
  84332. return task;
  84333. };
  84334. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84335. var _this = this;
  84336. this._waitingTasksCount--;
  84337. try {
  84338. if (task.taskState === AssetTaskState.DONE) {
  84339. // Let's remove successfull tasks
  84340. BABYLON.Tools.SetImmediate(function () {
  84341. var index = _this._tasks.indexOf(task);
  84342. if (index > -1) {
  84343. _this._tasks.splice(index, 1);
  84344. }
  84345. });
  84346. }
  84347. if (this.onProgress) {
  84348. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84349. }
  84350. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84351. }
  84352. catch (e) {
  84353. BABYLON.Tools.Error("Error running progress callbacks.");
  84354. console.log(e);
  84355. }
  84356. if (this._waitingTasksCount === 0) {
  84357. try {
  84358. if (this.onFinish) {
  84359. this.onFinish(this._tasks);
  84360. }
  84361. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84362. }
  84363. catch (e) {
  84364. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84365. console.log(e);
  84366. }
  84367. this._isLoading = false;
  84368. this._scene.getEngine().hideLoadingUI();
  84369. }
  84370. };
  84371. AssetsManager.prototype._runTask = function (task) {
  84372. var _this = this;
  84373. var done = function () {
  84374. try {
  84375. if (_this.onTaskSuccess) {
  84376. _this.onTaskSuccess(task);
  84377. }
  84378. _this.onTaskSuccessObservable.notifyObservers(task);
  84379. _this._decreaseWaitingTasksCount(task);
  84380. }
  84381. catch (e) {
  84382. error("Error executing task success callbacks", e);
  84383. }
  84384. };
  84385. var error = function (message, exception) {
  84386. task._setErrorObject(message, exception);
  84387. if (_this.onTaskError) {
  84388. _this.onTaskError(task);
  84389. }
  84390. _this.onTaskErrorObservable.notifyObservers(task);
  84391. _this._decreaseWaitingTasksCount(task);
  84392. };
  84393. task.run(this._scene, done, error);
  84394. };
  84395. /**
  84396. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84397. * @return the current instance of the {BABYLON.AssetsManager}
  84398. */
  84399. AssetsManager.prototype.reset = function () {
  84400. this._isLoading = false;
  84401. this._tasks = new Array();
  84402. return this;
  84403. };
  84404. /**
  84405. * Start the loading process
  84406. * @return the current instance of the {BABYLON.AssetsManager}
  84407. */
  84408. AssetsManager.prototype.load = function () {
  84409. if (this._isLoading) {
  84410. return this;
  84411. }
  84412. this._isLoading = true;
  84413. this._waitingTasksCount = this._tasks.length;
  84414. this._totalTasksCount = this._tasks.length;
  84415. if (this._waitingTasksCount === 0) {
  84416. if (this.onFinish) {
  84417. this.onFinish(this._tasks);
  84418. }
  84419. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84420. return this;
  84421. }
  84422. if (this.useDefaultLoadingScreen) {
  84423. this._scene.getEngine().displayLoadingUI();
  84424. }
  84425. for (var index = 0; index < this._tasks.length; index++) {
  84426. var task = this._tasks[index];
  84427. this._runTask(task);
  84428. }
  84429. return this;
  84430. };
  84431. return AssetsManager;
  84432. }());
  84433. BABYLON.AssetsManager = AssetsManager;
  84434. })(BABYLON || (BABYLON = {}));
  84435. //# sourceMappingURL=babylon.assetsManager.js.map
  84436. var BABYLON;
  84437. (function (BABYLON) {
  84438. var serializedGeometries = [];
  84439. var serializeGeometry = function (geometry, serializationGeometries) {
  84440. if (serializedGeometries[geometry.id]) {
  84441. return;
  84442. }
  84443. if (geometry.doNotSerialize) {
  84444. return;
  84445. }
  84446. if (geometry instanceof BABYLON.BoxGeometry) {
  84447. serializationGeometries.boxes.push(geometry.serialize());
  84448. }
  84449. else if (geometry instanceof BABYLON.SphereGeometry) {
  84450. serializationGeometries.spheres.push(geometry.serialize());
  84451. }
  84452. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84453. serializationGeometries.cylinders.push(geometry.serialize());
  84454. }
  84455. else if (geometry instanceof BABYLON.TorusGeometry) {
  84456. serializationGeometries.toruses.push(geometry.serialize());
  84457. }
  84458. else if (geometry instanceof BABYLON.GroundGeometry) {
  84459. serializationGeometries.grounds.push(geometry.serialize());
  84460. }
  84461. else if (geometry instanceof BABYLON.Plane) {
  84462. serializationGeometries.planes.push(geometry.serialize());
  84463. }
  84464. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84465. serializationGeometries.torusKnots.push(geometry.serialize());
  84466. }
  84467. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84468. throw new Error("Unknown primitive type");
  84469. }
  84470. else {
  84471. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84472. }
  84473. serializedGeometries[geometry.id] = true;
  84474. };
  84475. var serializeMesh = function (mesh, serializationScene) {
  84476. var serializationObject = {};
  84477. // Geometry
  84478. var geometry = mesh._geometry;
  84479. if (geometry) {
  84480. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84481. // 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
  84482. serializeGeometry(geometry, serializationScene.geometries);
  84483. }
  84484. }
  84485. // Custom
  84486. if (mesh.serialize) {
  84487. mesh.serialize(serializationObject);
  84488. }
  84489. return serializationObject;
  84490. };
  84491. var finalizeSingleMesh = function (mesh, serializationObject) {
  84492. //only works if the mesh is already loaded
  84493. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84494. //serialize material
  84495. if (mesh.material) {
  84496. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84497. serializationObject.materials = serializationObject.materials || [];
  84498. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84499. serializationObject.materials.push(mesh.material.serialize());
  84500. }
  84501. }
  84502. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84503. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84504. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84505. serializationObject.multiMaterials.push(mesh.material.serialize());
  84506. }
  84507. }
  84508. }
  84509. //serialize geometry
  84510. var geometry = mesh._geometry;
  84511. if (geometry) {
  84512. if (!serializationObject.geometries) {
  84513. serializationObject.geometries = {};
  84514. serializationObject.geometries.boxes = [];
  84515. serializationObject.geometries.spheres = [];
  84516. serializationObject.geometries.cylinders = [];
  84517. serializationObject.geometries.toruses = [];
  84518. serializationObject.geometries.grounds = [];
  84519. serializationObject.geometries.planes = [];
  84520. serializationObject.geometries.torusKnots = [];
  84521. serializationObject.geometries.vertexData = [];
  84522. }
  84523. serializeGeometry(geometry, serializationObject.geometries);
  84524. }
  84525. // Skeletons
  84526. if (mesh.skeleton) {
  84527. serializationObject.skeletons = serializationObject.skeletons || [];
  84528. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84529. }
  84530. //serialize the actual mesh
  84531. serializationObject.meshes = serializationObject.meshes || [];
  84532. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84533. }
  84534. };
  84535. var SceneSerializer = /** @class */ (function () {
  84536. function SceneSerializer() {
  84537. }
  84538. SceneSerializer.ClearCache = function () {
  84539. serializedGeometries = [];
  84540. };
  84541. SceneSerializer.Serialize = function (scene) {
  84542. var serializationObject = {};
  84543. SceneSerializer.ClearCache();
  84544. // Scene
  84545. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84546. serializationObject.autoClear = scene.autoClear;
  84547. serializationObject.clearColor = scene.clearColor.asArray();
  84548. serializationObject.ambientColor = scene.ambientColor.asArray();
  84549. serializationObject.gravity = scene.gravity.asArray();
  84550. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84551. serializationObject.workerCollisions = scene.workerCollisions;
  84552. // Fog
  84553. if (scene.fogMode && scene.fogMode !== 0) {
  84554. serializationObject.fogMode = scene.fogMode;
  84555. serializationObject.fogColor = scene.fogColor.asArray();
  84556. serializationObject.fogStart = scene.fogStart;
  84557. serializationObject.fogEnd = scene.fogEnd;
  84558. serializationObject.fogDensity = scene.fogDensity;
  84559. }
  84560. //Physics
  84561. if (scene.isPhysicsEnabled()) {
  84562. var physicEngine = scene.getPhysicsEngine();
  84563. if (physicEngine) {
  84564. serializationObject.physicsEnabled = true;
  84565. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84566. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84567. }
  84568. }
  84569. // Metadata
  84570. if (scene.metadata) {
  84571. serializationObject.metadata = scene.metadata;
  84572. }
  84573. // Morph targets
  84574. serializationObject.morphTargetManagers = [];
  84575. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84576. var abstractMesh = _a[_i];
  84577. var manager = abstractMesh.morphTargetManager;
  84578. if (manager) {
  84579. serializationObject.morphTargetManagers.push(manager.serialize());
  84580. }
  84581. }
  84582. // Lights
  84583. serializationObject.lights = [];
  84584. var index;
  84585. var light;
  84586. for (index = 0; index < scene.lights.length; index++) {
  84587. light = scene.lights[index];
  84588. if (!light.doNotSerialize) {
  84589. serializationObject.lights.push(light.serialize());
  84590. }
  84591. }
  84592. // Cameras
  84593. serializationObject.cameras = [];
  84594. for (index = 0; index < scene.cameras.length; index++) {
  84595. var camera = scene.cameras[index];
  84596. if (!camera.doNotSerialize) {
  84597. serializationObject.cameras.push(camera.serialize());
  84598. }
  84599. }
  84600. if (scene.activeCamera) {
  84601. serializationObject.activeCameraID = scene.activeCamera.id;
  84602. }
  84603. // Animations
  84604. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84605. // Materials
  84606. serializationObject.materials = [];
  84607. serializationObject.multiMaterials = [];
  84608. var material;
  84609. for (index = 0; index < scene.materials.length; index++) {
  84610. material = scene.materials[index];
  84611. if (!material.doNotSerialize) {
  84612. serializationObject.materials.push(material.serialize());
  84613. }
  84614. }
  84615. // MultiMaterials
  84616. serializationObject.multiMaterials = [];
  84617. for (index = 0; index < scene.multiMaterials.length; index++) {
  84618. var multiMaterial = scene.multiMaterials[index];
  84619. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84620. }
  84621. // Environment texture
  84622. if (scene.environmentTexture) {
  84623. serializationObject.environmentTexture = scene.environmentTexture.name;
  84624. }
  84625. // Skeletons
  84626. serializationObject.skeletons = [];
  84627. for (index = 0; index < scene.skeletons.length; index++) {
  84628. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84629. }
  84630. // Transform nodes
  84631. serializationObject.transformNodes = [];
  84632. for (index = 0; index < scene.transformNodes.length; index++) {
  84633. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84634. }
  84635. // Geometries
  84636. serializationObject.geometries = {};
  84637. serializationObject.geometries.boxes = [];
  84638. serializationObject.geometries.spheres = [];
  84639. serializationObject.geometries.cylinders = [];
  84640. serializationObject.geometries.toruses = [];
  84641. serializationObject.geometries.grounds = [];
  84642. serializationObject.geometries.planes = [];
  84643. serializationObject.geometries.torusKnots = [];
  84644. serializationObject.geometries.vertexData = [];
  84645. serializedGeometries = [];
  84646. var geometries = scene.getGeometries();
  84647. for (index = 0; index < geometries.length; index++) {
  84648. var geometry = geometries[index];
  84649. if (geometry.isReady()) {
  84650. serializeGeometry(geometry, serializationObject.geometries);
  84651. }
  84652. }
  84653. // Meshes
  84654. serializationObject.meshes = [];
  84655. for (index = 0; index < scene.meshes.length; index++) {
  84656. var abstractMesh = scene.meshes[index];
  84657. if (abstractMesh instanceof BABYLON.Mesh) {
  84658. var mesh = abstractMesh;
  84659. if (!mesh.doNotSerialize) {
  84660. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84661. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84662. }
  84663. }
  84664. }
  84665. }
  84666. // Particles Systems
  84667. serializationObject.particleSystems = [];
  84668. for (index = 0; index < scene.particleSystems.length; index++) {
  84669. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84670. }
  84671. // Lens flares
  84672. serializationObject.lensFlareSystems = [];
  84673. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84674. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84675. }
  84676. // Shadows
  84677. serializationObject.shadowGenerators = [];
  84678. for (index = 0; index < scene.lights.length; index++) {
  84679. light = scene.lights[index];
  84680. var shadowGenerator = light.getShadowGenerator();
  84681. if (shadowGenerator) {
  84682. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84683. }
  84684. }
  84685. // Action Manager
  84686. if (scene.actionManager) {
  84687. serializationObject.actions = scene.actionManager.serialize("scene");
  84688. }
  84689. // Audio
  84690. serializationObject.sounds = [];
  84691. for (index = 0; index < scene.soundTracks.length; index++) {
  84692. var soundtrack = scene.soundTracks[index];
  84693. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84694. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84695. }
  84696. }
  84697. return serializationObject;
  84698. };
  84699. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84700. if (withParents === void 0) { withParents = false; }
  84701. if (withChildren === void 0) { withChildren = false; }
  84702. var serializationObject = {};
  84703. SceneSerializer.ClearCache();
  84704. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84705. if (withParents || withChildren) {
  84706. //deliberate for loop! not for each, appended should be processed as well.
  84707. for (var i = 0; i < toSerialize.length; ++i) {
  84708. if (withChildren) {
  84709. toSerialize[i].getDescendants().forEach(function (node) {
  84710. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84711. toSerialize.push(node);
  84712. }
  84713. });
  84714. }
  84715. //make sure the array doesn't contain the object already
  84716. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84717. toSerialize.push(toSerialize[i].parent);
  84718. }
  84719. }
  84720. }
  84721. toSerialize.forEach(function (mesh) {
  84722. finalizeSingleMesh(mesh, serializationObject);
  84723. });
  84724. return serializationObject;
  84725. };
  84726. return SceneSerializer;
  84727. }());
  84728. BABYLON.SceneSerializer = SceneSerializer;
  84729. })(BABYLON || (BABYLON = {}));
  84730. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84731. var BABYLON;
  84732. (function (BABYLON) {
  84733. var ReflectionProbe = /** @class */ (function () {
  84734. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84735. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84736. var _this = this;
  84737. this.name = name;
  84738. this._viewMatrix = BABYLON.Matrix.Identity();
  84739. this._target = BABYLON.Vector3.Zero();
  84740. this._add = BABYLON.Vector3.Zero();
  84741. this.invertYAxis = false;
  84742. this.position = BABYLON.Vector3.Zero();
  84743. this._scene = scene;
  84744. this._scene.reflectionProbes.push(this);
  84745. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84746. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84747. switch (faceIndex) {
  84748. case 0:
  84749. _this._add.copyFromFloats(1, 0, 0);
  84750. break;
  84751. case 1:
  84752. _this._add.copyFromFloats(-1, 0, 0);
  84753. break;
  84754. case 2:
  84755. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84756. break;
  84757. case 3:
  84758. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84759. break;
  84760. case 4:
  84761. _this._add.copyFromFloats(0, 0, 1);
  84762. break;
  84763. case 5:
  84764. _this._add.copyFromFloats(0, 0, -1);
  84765. break;
  84766. }
  84767. if (_this._attachedMesh) {
  84768. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84769. }
  84770. _this.position.addToRef(_this._add, _this._target);
  84771. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84772. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84773. scene._forcedViewPosition = _this.position;
  84774. });
  84775. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84776. scene._forcedViewPosition = null;
  84777. scene.updateTransformMatrix(true);
  84778. });
  84779. if (scene.activeCamera) {
  84780. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84781. }
  84782. }
  84783. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84784. get: function () {
  84785. return this._renderTargetTexture.samples;
  84786. },
  84787. set: function (value) {
  84788. this._renderTargetTexture.samples = value;
  84789. },
  84790. enumerable: true,
  84791. configurable: true
  84792. });
  84793. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84794. get: function () {
  84795. return this._renderTargetTexture.refreshRate;
  84796. },
  84797. set: function (value) {
  84798. this._renderTargetTexture.refreshRate = value;
  84799. },
  84800. enumerable: true,
  84801. configurable: true
  84802. });
  84803. ReflectionProbe.prototype.getScene = function () {
  84804. return this._scene;
  84805. };
  84806. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84807. get: function () {
  84808. return this._renderTargetTexture;
  84809. },
  84810. enumerable: true,
  84811. configurable: true
  84812. });
  84813. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84814. get: function () {
  84815. return this._renderTargetTexture.renderList;
  84816. },
  84817. enumerable: true,
  84818. configurable: true
  84819. });
  84820. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84821. this._attachedMesh = mesh;
  84822. };
  84823. /**
  84824. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84825. *
  84826. * @param renderingGroupId The rendering group id corresponding to its index
  84827. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84828. */
  84829. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84830. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84831. };
  84832. ReflectionProbe.prototype.dispose = function () {
  84833. var index = this._scene.reflectionProbes.indexOf(this);
  84834. if (index !== -1) {
  84835. // Remove from the scene if found
  84836. this._scene.reflectionProbes.splice(index, 1);
  84837. }
  84838. if (this._renderTargetTexture) {
  84839. this._renderTargetTexture.dispose();
  84840. this._renderTargetTexture = null;
  84841. }
  84842. };
  84843. return ReflectionProbe;
  84844. }());
  84845. BABYLON.ReflectionProbe = ReflectionProbe;
  84846. })(BABYLON || (BABYLON = {}));
  84847. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84848. var BABYLON;
  84849. (function (BABYLON) {
  84850. var Layer = /** @class */ (function () {
  84851. function Layer(name, imgUrl, scene, isBackground, color) {
  84852. this.name = name;
  84853. this.scale = new BABYLON.Vector2(1, 1);
  84854. this.offset = new BABYLON.Vector2(0, 0);
  84855. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84856. this.layerMask = 0x0FFFFFFF;
  84857. this._vertexBuffers = {};
  84858. // Events
  84859. /**
  84860. * An event triggered when the layer is disposed.
  84861. * @type {BABYLON.Observable}
  84862. */
  84863. this.onDisposeObservable = new BABYLON.Observable();
  84864. /**
  84865. * An event triggered before rendering the scene
  84866. * @type {BABYLON.Observable}
  84867. */
  84868. this.onBeforeRenderObservable = new BABYLON.Observable();
  84869. /**
  84870. * An event triggered after rendering the scene
  84871. * @type {BABYLON.Observable}
  84872. */
  84873. this.onAfterRenderObservable = new BABYLON.Observable();
  84874. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84875. this.isBackground = isBackground === undefined ? true : isBackground;
  84876. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84877. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84878. this._scene.layers.push(this);
  84879. var engine = this._scene.getEngine();
  84880. // VBO
  84881. var vertices = [];
  84882. vertices.push(1, 1);
  84883. vertices.push(-1, 1);
  84884. vertices.push(-1, -1);
  84885. vertices.push(1, -1);
  84886. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84887. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84888. this._createIndexBuffer();
  84889. // Effects
  84890. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84891. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84892. }
  84893. Object.defineProperty(Layer.prototype, "onDispose", {
  84894. set: function (callback) {
  84895. if (this._onDisposeObserver) {
  84896. this.onDisposeObservable.remove(this._onDisposeObserver);
  84897. }
  84898. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84899. },
  84900. enumerable: true,
  84901. configurable: true
  84902. });
  84903. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84904. set: function (callback) {
  84905. if (this._onBeforeRenderObserver) {
  84906. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84907. }
  84908. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84909. },
  84910. enumerable: true,
  84911. configurable: true
  84912. });
  84913. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84914. set: function (callback) {
  84915. if (this._onAfterRenderObserver) {
  84916. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84917. }
  84918. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84919. },
  84920. enumerable: true,
  84921. configurable: true
  84922. });
  84923. Layer.prototype._createIndexBuffer = function () {
  84924. var engine = this._scene.getEngine();
  84925. // Indices
  84926. var indices = [];
  84927. indices.push(0);
  84928. indices.push(1);
  84929. indices.push(2);
  84930. indices.push(0);
  84931. indices.push(2);
  84932. indices.push(3);
  84933. this._indexBuffer = engine.createIndexBuffer(indices);
  84934. };
  84935. Layer.prototype._rebuild = function () {
  84936. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84937. if (vb) {
  84938. vb._rebuild();
  84939. }
  84940. this._createIndexBuffer();
  84941. };
  84942. Layer.prototype.render = function () {
  84943. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84944. // Check
  84945. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84946. return;
  84947. var engine = this._scene.getEngine();
  84948. this.onBeforeRenderObservable.notifyObservers(this);
  84949. // Render
  84950. engine.enableEffect(currentEffect);
  84951. engine.setState(false);
  84952. // Texture
  84953. currentEffect.setTexture("textureSampler", this.texture);
  84954. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84955. // Color
  84956. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84957. // Scale / offset
  84958. currentEffect.setVector2("offset", this.offset);
  84959. currentEffect.setVector2("scale", this.scale);
  84960. // VBOs
  84961. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84962. // Draw order
  84963. if (!this.alphaTest) {
  84964. engine.setAlphaMode(this.alphaBlendingMode);
  84965. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84967. }
  84968. else {
  84969. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84970. }
  84971. this.onAfterRenderObservable.notifyObservers(this);
  84972. };
  84973. Layer.prototype.dispose = function () {
  84974. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84975. if (vertexBuffer) {
  84976. vertexBuffer.dispose();
  84977. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84978. }
  84979. if (this._indexBuffer) {
  84980. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84981. this._indexBuffer = null;
  84982. }
  84983. if (this.texture) {
  84984. this.texture.dispose();
  84985. this.texture = null;
  84986. }
  84987. // Remove from scene
  84988. var index = this._scene.layers.indexOf(this);
  84989. this._scene.layers.splice(index, 1);
  84990. // Callback
  84991. this.onDisposeObservable.notifyObservers(this);
  84992. this.onDisposeObservable.clear();
  84993. this.onAfterRenderObservable.clear();
  84994. this.onBeforeRenderObservable.clear();
  84995. };
  84996. return Layer;
  84997. }());
  84998. BABYLON.Layer = Layer;
  84999. })(BABYLON || (BABYLON = {}));
  85000. //# sourceMappingURL=babylon.layer.js.map
  85001. var BABYLON;
  85002. (function (BABYLON) {
  85003. var TextureTools = /** @class */ (function () {
  85004. function TextureTools() {
  85005. }
  85006. /**
  85007. * Uses the GPU to create a copy texture rescaled at a given size
  85008. * @param texture Texture to copy from
  85009. * @param width Desired width
  85010. * @param height Desired height
  85011. * @return Generated texture
  85012. */
  85013. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85014. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85015. var scene = texture.getScene();
  85016. var engine = scene.getEngine();
  85017. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85018. rtt.wrapU = texture.wrapU;
  85019. rtt.wrapV = texture.wrapV;
  85020. rtt.uOffset = texture.uOffset;
  85021. rtt.vOffset = texture.vOffset;
  85022. rtt.uScale = texture.uScale;
  85023. rtt.vScale = texture.vScale;
  85024. rtt.uAng = texture.uAng;
  85025. rtt.vAng = texture.vAng;
  85026. rtt.wAng = texture.wAng;
  85027. rtt.coordinatesIndex = texture.coordinatesIndex;
  85028. rtt.level = texture.level;
  85029. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85030. rtt._texture.isReady = false;
  85031. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85032. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85033. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85034. passPostProcess.getEffect().executeWhenCompiled(function () {
  85035. passPostProcess.onApply = function (effect) {
  85036. effect.setTexture("textureSampler", texture);
  85037. };
  85038. var internalTexture = rtt.getInternalTexture();
  85039. if (internalTexture) {
  85040. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85041. engine.unBindFramebuffer(internalTexture);
  85042. rtt.disposeFramebufferObjects();
  85043. passPostProcess.dispose();
  85044. internalTexture.isReady = true;
  85045. }
  85046. });
  85047. return rtt;
  85048. };
  85049. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85050. if (!scene._environmentBRDFTexture) {
  85051. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85052. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85053. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85054. scene._environmentBRDFTexture = texture;
  85055. }
  85056. return scene._environmentBRDFTexture;
  85057. };
  85058. 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=";
  85059. return TextureTools;
  85060. }());
  85061. BABYLON.TextureTools = TextureTools;
  85062. })(BABYLON || (BABYLON = {}));
  85063. //# sourceMappingURL=babylon.textureTools.js.map
  85064. var BABYLON;
  85065. (function (BABYLON) {
  85066. var FramingBehavior = /** @class */ (function () {
  85067. function FramingBehavior() {
  85068. this._mode = FramingBehavior.FitFrustumSidesMode;
  85069. this._radiusScale = 1.0;
  85070. this._positionScale = 0.5;
  85071. this._defaultElevation = 0.3;
  85072. this._elevationReturnTime = 1500;
  85073. this._elevationReturnWaitTime = 1000;
  85074. this._zoomStopsAnimation = false;
  85075. this._framingTime = 1500;
  85076. this._isPointerDown = false;
  85077. this._lastInteractionTime = -Infinity;
  85078. // Framing control
  85079. this._animatables = new Array();
  85080. this._betaIsAnimating = false;
  85081. }
  85082. Object.defineProperty(FramingBehavior.prototype, "name", {
  85083. get: function () {
  85084. return "Framing";
  85085. },
  85086. enumerable: true,
  85087. configurable: true
  85088. });
  85089. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85090. /**
  85091. * Gets current mode used by the behavior.
  85092. */
  85093. get: function () {
  85094. return this._mode;
  85095. },
  85096. /**
  85097. * Sets the current mode used by the behavior
  85098. */
  85099. set: function (mode) {
  85100. this._mode = mode;
  85101. },
  85102. enumerable: true,
  85103. configurable: true
  85104. });
  85105. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85106. /**
  85107. * Gets the scale applied to the radius
  85108. */
  85109. get: function () {
  85110. return this._radiusScale;
  85111. },
  85112. /**
  85113. * Sets the scale applied to the radius (1 by default)
  85114. */
  85115. set: function (radius) {
  85116. this._radiusScale = radius;
  85117. },
  85118. enumerable: true,
  85119. configurable: true
  85120. });
  85121. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85122. /**
  85123. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85124. */
  85125. get: function () {
  85126. return this._positionScale;
  85127. },
  85128. /**
  85129. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85130. */
  85131. set: function (scale) {
  85132. this._positionScale = scale;
  85133. },
  85134. enumerable: true,
  85135. configurable: true
  85136. });
  85137. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85138. /**
  85139. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85140. * behaviour is triggered, in radians.
  85141. */
  85142. get: function () {
  85143. return this._defaultElevation;
  85144. },
  85145. /**
  85146. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85147. * behaviour is triggered, in radians.
  85148. */
  85149. set: function (elevation) {
  85150. this._defaultElevation = elevation;
  85151. },
  85152. enumerable: true,
  85153. configurable: true
  85154. });
  85155. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85156. /**
  85157. * Gets the time (in milliseconds) taken to return to the default beta position.
  85158. * Negative value indicates camera should not return to default.
  85159. */
  85160. get: function () {
  85161. return this._elevationReturnTime;
  85162. },
  85163. /**
  85164. * Sets the time (in milliseconds) taken to return to the default beta position.
  85165. * Negative value indicates camera should not return to default.
  85166. */
  85167. set: function (speed) {
  85168. this._elevationReturnTime = speed;
  85169. },
  85170. enumerable: true,
  85171. configurable: true
  85172. });
  85173. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85174. /**
  85175. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85176. */
  85177. get: function () {
  85178. return this._elevationReturnWaitTime;
  85179. },
  85180. /**
  85181. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85182. */
  85183. set: function (time) {
  85184. this._elevationReturnWaitTime = time;
  85185. },
  85186. enumerable: true,
  85187. configurable: true
  85188. });
  85189. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85190. /**
  85191. * Gets the flag that indicates if user zooming should stop animation.
  85192. */
  85193. get: function () {
  85194. return this._zoomStopsAnimation;
  85195. },
  85196. /**
  85197. * Sets the flag that indicates if user zooming should stop animation.
  85198. */
  85199. set: function (flag) {
  85200. this._zoomStopsAnimation = flag;
  85201. },
  85202. enumerable: true,
  85203. configurable: true
  85204. });
  85205. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85206. /**
  85207. * Gets the transition time when framing the mesh, in milliseconds
  85208. */
  85209. get: function () {
  85210. return this._framingTime;
  85211. },
  85212. /**
  85213. * Sets the transition time when framing the mesh, in milliseconds
  85214. */
  85215. set: function (time) {
  85216. this._framingTime = time;
  85217. },
  85218. enumerable: true,
  85219. configurable: true
  85220. });
  85221. FramingBehavior.prototype.init = function () {
  85222. // Do notihng
  85223. };
  85224. FramingBehavior.prototype.attach = function (camera) {
  85225. var _this = this;
  85226. this._attachedCamera = camera;
  85227. var scene = this._attachedCamera.getScene();
  85228. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85229. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85230. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85231. _this._isPointerDown = true;
  85232. return;
  85233. }
  85234. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85235. _this._isPointerDown = false;
  85236. }
  85237. });
  85238. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85239. if (mesh) {
  85240. _this.zoomOnMesh(mesh);
  85241. }
  85242. });
  85243. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85244. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85245. _this._applyUserInteraction();
  85246. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85247. // back to the default position after a given timeout
  85248. _this._maintainCameraAboveGround();
  85249. });
  85250. };
  85251. FramingBehavior.prototype.detach = function () {
  85252. if (!this._attachedCamera) {
  85253. return;
  85254. }
  85255. var scene = this._attachedCamera.getScene();
  85256. if (this._onPrePointerObservableObserver) {
  85257. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85258. }
  85259. if (this._onAfterCheckInputsObserver) {
  85260. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85261. }
  85262. if (this._onMeshTargetChangedObserver) {
  85263. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85264. }
  85265. this._attachedCamera = null;
  85266. };
  85267. /**
  85268. * Targets the given mesh and updates zoom level accordingly.
  85269. * @param mesh The mesh to target.
  85270. * @param radius Optional. If a cached radius position already exists, overrides default.
  85271. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85272. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85273. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85274. */
  85275. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85276. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85277. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85278. mesh.computeWorldMatrix(true);
  85279. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85280. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85281. };
  85282. /**
  85283. * Targets the given mesh with its children and updates zoom level accordingly.
  85284. * @param mesh The mesh to target.
  85285. * @param radius Optional. If a cached radius position already exists, overrides default.
  85286. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85287. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85288. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85289. */
  85290. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85291. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85292. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85293. mesh.computeWorldMatrix(true);
  85294. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85295. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85296. };
  85297. /**
  85298. * Targets the given meshes with their children and updates zoom level accordingly.
  85299. * @param meshes The mesh to target.
  85300. * @param radius Optional. If a cached radius position already exists, overrides default.
  85301. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85302. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85303. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85304. */
  85305. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85306. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85307. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85308. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85309. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85310. for (var i = 0; i < meshes.length; i++) {
  85311. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85312. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85313. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85314. }
  85315. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85316. };
  85317. /**
  85318. * Targets the given mesh and updates zoom level accordingly.
  85319. * @param mesh The mesh to target.
  85320. * @param radius Optional. If a cached radius position already exists, overrides default.
  85321. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85322. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85323. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85324. */
  85325. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85326. var _this = this;
  85327. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85328. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85329. var zoomTarget;
  85330. if (!this._attachedCamera) {
  85331. return;
  85332. }
  85333. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85334. var bottom = minimumWorld.y;
  85335. var top = maximumWorld.y;
  85336. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85337. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85338. if (focusOnOriginXZ) {
  85339. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85340. }
  85341. else {
  85342. var centerWorld = minimumWorld.add(radiusWorld);
  85343. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85344. }
  85345. if (!this._vectorTransition) {
  85346. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85347. }
  85348. this._betaIsAnimating = true;
  85349. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85350. if (animatable) {
  85351. this._animatables.push(animatable);
  85352. }
  85353. // sets the radius and lower radius bounds
  85354. // Small delta ensures camera is not always at lower zoom limit.
  85355. var radius = 0;
  85356. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85357. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85358. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85359. radius = position;
  85360. }
  85361. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85362. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85363. if (this._attachedCamera.lowerRadiusLimit === null) {
  85364. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85365. }
  85366. }
  85367. // Set sensibilities
  85368. var extend = maximumWorld.subtract(minimumWorld).length();
  85369. this._attachedCamera.panningSensibility = 5000 / extend;
  85370. this._attachedCamera.wheelPrecision = 100 / radius;
  85371. // transition to new radius
  85372. if (!this._radiusTransition) {
  85373. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85374. }
  85375. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85376. if (onAnimationEnd) {
  85377. onAnimationEnd();
  85378. }
  85379. if (_this._attachedCamera) {
  85380. _this._attachedCamera.storeState();
  85381. }
  85382. });
  85383. if (animatable) {
  85384. this._animatables.push(animatable);
  85385. }
  85386. };
  85387. /**
  85388. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85389. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85390. * frustum width.
  85391. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85392. * to fully enclose the mesh in the viewing frustum.
  85393. */
  85394. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85395. var size = maximumWorld.subtract(minimumWorld);
  85396. var boxVectorGlobalDiagonal = size.length();
  85397. var frustumSlope = this._getFrustumSlope();
  85398. // Formula for setting distance
  85399. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85400. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85401. // Horizon distance
  85402. var radius = radiusWithoutFraming * this._radiusScale;
  85403. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85404. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85405. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85406. var camera = this._attachedCamera;
  85407. if (!camera) {
  85408. return 0;
  85409. }
  85410. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85411. // Don't exceed the requested limit
  85412. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85413. }
  85414. // Don't exceed the upper radius limit
  85415. if (camera.upperRadiusLimit) {
  85416. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85417. }
  85418. return distance;
  85419. };
  85420. /**
  85421. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85422. * is automatically returned to its default position (expected to be above ground plane).
  85423. */
  85424. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85425. var _this = this;
  85426. if (this._elevationReturnTime < 0) {
  85427. return;
  85428. }
  85429. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85430. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85431. var limitBeta = Math.PI * 0.5;
  85432. // Bring the camera back up if below the ground plane
  85433. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85434. this._betaIsAnimating = true;
  85435. //Transition to new position
  85436. this.stopAllAnimations();
  85437. if (!this._betaTransition) {
  85438. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85439. }
  85440. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85441. _this._clearAnimationLocks();
  85442. _this.stopAllAnimations();
  85443. });
  85444. if (animatabe) {
  85445. this._animatables.push(animatabe);
  85446. }
  85447. }
  85448. };
  85449. /**
  85450. * Returns the frustum slope based on the canvas ratio and camera FOV
  85451. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85452. */
  85453. FramingBehavior.prototype._getFrustumSlope = function () {
  85454. // Calculate the viewport ratio
  85455. // Aspect Ratio is Height/Width.
  85456. var camera = this._attachedCamera;
  85457. if (!camera) {
  85458. return BABYLON.Vector2.Zero();
  85459. }
  85460. var engine = camera.getScene().getEngine();
  85461. var aspectRatio = engine.getAspectRatio(camera);
  85462. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85463. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85464. var frustumSlopeY = Math.tan(camera.fov / 2);
  85465. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85466. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85467. // along the forward vector.
  85468. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85469. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85470. };
  85471. /**
  85472. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85473. */
  85474. FramingBehavior.prototype._clearAnimationLocks = function () {
  85475. this._betaIsAnimating = false;
  85476. };
  85477. /**
  85478. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85479. */
  85480. FramingBehavior.prototype._applyUserInteraction = function () {
  85481. if (this.isUserIsMoving) {
  85482. this._lastInteractionTime = BABYLON.Tools.Now;
  85483. this.stopAllAnimations();
  85484. this._clearAnimationLocks();
  85485. }
  85486. };
  85487. /**
  85488. * Stops and removes all animations that have been applied to the camera
  85489. */
  85490. FramingBehavior.prototype.stopAllAnimations = function () {
  85491. if (this._attachedCamera) {
  85492. this._attachedCamera.animations = [];
  85493. }
  85494. while (this._animatables.length) {
  85495. if (this._animatables[0]) {
  85496. this._animatables[0].onAnimationEnd = null;
  85497. this._animatables[0].stop();
  85498. }
  85499. this._animatables.shift();
  85500. }
  85501. };
  85502. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85503. /**
  85504. * Gets a value indicating if the user is moving the camera
  85505. */
  85506. get: function () {
  85507. if (!this._attachedCamera) {
  85508. return false;
  85509. }
  85510. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85511. this._attachedCamera.inertialBetaOffset !== 0 ||
  85512. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85513. this._attachedCamera.inertialPanningX !== 0 ||
  85514. this._attachedCamera.inertialPanningY !== 0 ||
  85515. this._isPointerDown;
  85516. },
  85517. enumerable: true,
  85518. configurable: true
  85519. });
  85520. /**
  85521. * The easing function used by animations
  85522. */
  85523. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85524. /**
  85525. * The easing mode used by animations
  85526. */
  85527. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85528. // Statics
  85529. /**
  85530. * The camera can move all the way towards the mesh.
  85531. */
  85532. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85533. /**
  85534. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85535. */
  85536. FramingBehavior.FitFrustumSidesMode = 1;
  85537. return FramingBehavior;
  85538. }());
  85539. BABYLON.FramingBehavior = FramingBehavior;
  85540. })(BABYLON || (BABYLON = {}));
  85541. //# sourceMappingURL=babylon.framingBehavior.js.map
  85542. var BABYLON;
  85543. (function (BABYLON) {
  85544. /**
  85545. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85546. */
  85547. var BouncingBehavior = /** @class */ (function () {
  85548. function BouncingBehavior() {
  85549. /**
  85550. * The duration of the animation, in milliseconds
  85551. */
  85552. this.transitionDuration = 450;
  85553. /**
  85554. * Length of the distance animated by the transition when lower radius is reached
  85555. */
  85556. this.lowerRadiusTransitionRange = 2;
  85557. /**
  85558. * Length of the distance animated by the transition when upper radius is reached
  85559. */
  85560. this.upperRadiusTransitionRange = -2;
  85561. this._autoTransitionRange = false;
  85562. // Animations
  85563. this._radiusIsAnimating = false;
  85564. this._radiusBounceTransition = null;
  85565. this._animatables = new Array();
  85566. }
  85567. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85568. get: function () {
  85569. return "Bouncing";
  85570. },
  85571. enumerable: true,
  85572. configurable: true
  85573. });
  85574. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85575. /**
  85576. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85577. */
  85578. get: function () {
  85579. return this._autoTransitionRange;
  85580. },
  85581. /**
  85582. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85583. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85584. */
  85585. set: function (value) {
  85586. var _this = this;
  85587. if (this._autoTransitionRange === value) {
  85588. return;
  85589. }
  85590. this._autoTransitionRange = value;
  85591. var camera = this._attachedCamera;
  85592. if (!camera) {
  85593. return;
  85594. }
  85595. if (value) {
  85596. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85597. if (!mesh) {
  85598. return;
  85599. }
  85600. mesh.computeWorldMatrix(true);
  85601. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85602. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85603. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85604. });
  85605. }
  85606. else if (this._onMeshTargetChangedObserver) {
  85607. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85608. }
  85609. },
  85610. enumerable: true,
  85611. configurable: true
  85612. });
  85613. BouncingBehavior.prototype.init = function () {
  85614. // Do notihng
  85615. };
  85616. BouncingBehavior.prototype.attach = function (camera) {
  85617. var _this = this;
  85618. this._attachedCamera = camera;
  85619. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85620. if (!_this._attachedCamera) {
  85621. return;
  85622. }
  85623. // Add the bounce animation to the lower radius limit
  85624. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85625. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85626. }
  85627. // Add the bounce animation to the upper radius limit
  85628. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85629. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85630. }
  85631. });
  85632. };
  85633. BouncingBehavior.prototype.detach = function () {
  85634. if (!this._attachedCamera) {
  85635. return;
  85636. }
  85637. if (this._onAfterCheckInputsObserver) {
  85638. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85639. }
  85640. if (this._onMeshTargetChangedObserver) {
  85641. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85642. }
  85643. this._attachedCamera = null;
  85644. };
  85645. /**
  85646. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85647. * @param radiusLimit The limit to check against.
  85648. * @return Bool to indicate if at limit.
  85649. */
  85650. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85651. if (!this._attachedCamera) {
  85652. return false;
  85653. }
  85654. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85655. return true;
  85656. }
  85657. return false;
  85658. };
  85659. /**
  85660. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85661. * @param radiusDelta The delta by which to animate to. Can be negative.
  85662. */
  85663. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85664. var _this = this;
  85665. if (!this._attachedCamera) {
  85666. return;
  85667. }
  85668. if (!this._radiusBounceTransition) {
  85669. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85670. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85671. }
  85672. // Prevent zoom until bounce has completed
  85673. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85674. this._attachedCamera.wheelPrecision = Infinity;
  85675. this._attachedCamera.inertialRadiusOffset = 0;
  85676. // Animate to the radius limit
  85677. this.stopAllAnimations();
  85678. this._radiusIsAnimating = true;
  85679. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85680. if (animatable) {
  85681. this._animatables.push(animatable);
  85682. }
  85683. };
  85684. /**
  85685. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85686. */
  85687. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85688. this._radiusIsAnimating = false;
  85689. if (this._attachedCamera) {
  85690. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85691. }
  85692. };
  85693. /**
  85694. * Stops and removes all animations that have been applied to the camera
  85695. */
  85696. BouncingBehavior.prototype.stopAllAnimations = function () {
  85697. if (this._attachedCamera) {
  85698. this._attachedCamera.animations = [];
  85699. }
  85700. while (this._animatables.length) {
  85701. this._animatables[0].onAnimationEnd = null;
  85702. this._animatables[0].stop();
  85703. this._animatables.shift();
  85704. }
  85705. };
  85706. /**
  85707. * The easing function used by animations
  85708. */
  85709. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85710. /**
  85711. * The easing mode used by animations
  85712. */
  85713. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85714. return BouncingBehavior;
  85715. }());
  85716. BABYLON.BouncingBehavior = BouncingBehavior;
  85717. })(BABYLON || (BABYLON = {}));
  85718. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85719. var BABYLON;
  85720. (function (BABYLON) {
  85721. var AutoRotationBehavior = /** @class */ (function () {
  85722. function AutoRotationBehavior() {
  85723. this._zoomStopsAnimation = false;
  85724. this._idleRotationSpeed = 0.05;
  85725. this._idleRotationWaitTime = 2000;
  85726. this._idleRotationSpinupTime = 2000;
  85727. this._isPointerDown = false;
  85728. this._lastFrameTime = null;
  85729. this._lastInteractionTime = -Infinity;
  85730. this._cameraRotationSpeed = 0;
  85731. this._lastFrameRadius = 0;
  85732. }
  85733. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85734. get: function () {
  85735. return "AutoRotation";
  85736. },
  85737. enumerable: true,
  85738. configurable: true
  85739. });
  85740. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85741. /**
  85742. * Gets the flag that indicates if user zooming should stop animation.
  85743. */
  85744. get: function () {
  85745. return this._zoomStopsAnimation;
  85746. },
  85747. /**
  85748. * Sets the flag that indicates if user zooming should stop animation.
  85749. */
  85750. set: function (flag) {
  85751. this._zoomStopsAnimation = flag;
  85752. },
  85753. enumerable: true,
  85754. configurable: true
  85755. });
  85756. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85757. /**
  85758. * Gets the default speed at which the camera rotates around the model.
  85759. */
  85760. get: function () {
  85761. return this._idleRotationSpeed;
  85762. },
  85763. /**
  85764. * Sets the default speed at which the camera rotates around the model.
  85765. */
  85766. set: function (speed) {
  85767. this._idleRotationSpeed = speed;
  85768. },
  85769. enumerable: true,
  85770. configurable: true
  85771. });
  85772. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85773. /**
  85774. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85775. */
  85776. get: function () {
  85777. return this._idleRotationWaitTime;
  85778. },
  85779. /**
  85780. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85781. */
  85782. set: function (time) {
  85783. this._idleRotationWaitTime = time;
  85784. },
  85785. enumerable: true,
  85786. configurable: true
  85787. });
  85788. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85789. /**
  85790. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85791. */
  85792. get: function () {
  85793. return this._idleRotationSpinupTime;
  85794. },
  85795. /**
  85796. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85797. */
  85798. set: function (time) {
  85799. this._idleRotationSpinupTime = time;
  85800. },
  85801. enumerable: true,
  85802. configurable: true
  85803. });
  85804. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85805. /**
  85806. * Gets a value indicating if the camera is currently rotating because of this behavior
  85807. */
  85808. get: function () {
  85809. return Math.abs(this._cameraRotationSpeed) > 0;
  85810. },
  85811. enumerable: true,
  85812. configurable: true
  85813. });
  85814. AutoRotationBehavior.prototype.init = function () {
  85815. // Do notihng
  85816. };
  85817. AutoRotationBehavior.prototype.attach = function (camera) {
  85818. var _this = this;
  85819. this._attachedCamera = camera;
  85820. var scene = this._attachedCamera.getScene();
  85821. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85822. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85823. _this._isPointerDown = true;
  85824. return;
  85825. }
  85826. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85827. _this._isPointerDown = false;
  85828. }
  85829. });
  85830. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85831. var now = BABYLON.Tools.Now;
  85832. var dt = 0;
  85833. if (_this._lastFrameTime != null) {
  85834. dt = now - _this._lastFrameTime;
  85835. }
  85836. _this._lastFrameTime = now;
  85837. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85838. _this._applyUserInteraction();
  85839. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85840. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85841. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85842. // Step camera rotation by rotation speed
  85843. if (_this._attachedCamera) {
  85844. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85845. }
  85846. });
  85847. };
  85848. AutoRotationBehavior.prototype.detach = function () {
  85849. if (!this._attachedCamera) {
  85850. return;
  85851. }
  85852. var scene = this._attachedCamera.getScene();
  85853. if (this._onPrePointerObservableObserver) {
  85854. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85855. }
  85856. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85857. this._attachedCamera = null;
  85858. };
  85859. /**
  85860. * Returns true if user is scrolling.
  85861. * @return true if user is scrolling.
  85862. */
  85863. AutoRotationBehavior.prototype._userIsZooming = function () {
  85864. if (!this._attachedCamera) {
  85865. return false;
  85866. }
  85867. return this._attachedCamera.inertialRadiusOffset !== 0;
  85868. };
  85869. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85870. if (!this._attachedCamera) {
  85871. return false;
  85872. }
  85873. var zoomHasHitLimit = false;
  85874. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85875. zoomHasHitLimit = true;
  85876. }
  85877. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85878. this._lastFrameRadius = this._attachedCamera.radius;
  85879. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85880. };
  85881. /**
  85882. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85883. */
  85884. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85885. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85886. this._lastInteractionTime = BABYLON.Tools.Now;
  85887. }
  85888. };
  85889. // Tools
  85890. AutoRotationBehavior.prototype._userIsMoving = function () {
  85891. if (!this._attachedCamera) {
  85892. return false;
  85893. }
  85894. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85895. this._attachedCamera.inertialBetaOffset !== 0 ||
  85896. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85897. this._attachedCamera.inertialPanningX !== 0 ||
  85898. this._attachedCamera.inertialPanningY !== 0 ||
  85899. this._isPointerDown;
  85900. };
  85901. return AutoRotationBehavior;
  85902. }());
  85903. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85904. })(BABYLON || (BABYLON = {}));
  85905. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85906. var BABYLON;
  85907. (function (BABYLON) {
  85908. var NullEngineOptions = /** @class */ (function () {
  85909. function NullEngineOptions() {
  85910. this.renderWidth = 512;
  85911. this.renderHeight = 256;
  85912. this.textureSize = 512;
  85913. this.deterministicLockstep = false;
  85914. this.lockstepMaxSteps = 4;
  85915. }
  85916. return NullEngineOptions;
  85917. }());
  85918. BABYLON.NullEngineOptions = NullEngineOptions;
  85919. /**
  85920. * The null engine class provides support for headless version of babylon.js.
  85921. * This can be used in server side scenario or for testing purposes
  85922. */
  85923. var NullEngine = /** @class */ (function (_super) {
  85924. __extends(NullEngine, _super);
  85925. function NullEngine(options) {
  85926. if (options === void 0) { options = new NullEngineOptions(); }
  85927. var _this = _super.call(this, null) || this;
  85928. if (options.deterministicLockstep === undefined) {
  85929. options.deterministicLockstep = false;
  85930. }
  85931. if (options.lockstepMaxSteps === undefined) {
  85932. options.lockstepMaxSteps = 4;
  85933. }
  85934. _this._options = options;
  85935. // Init caps
  85936. // We consider we are on a webgl1 capable device
  85937. _this._caps = new BABYLON.EngineCapabilities();
  85938. _this._caps.maxTexturesImageUnits = 16;
  85939. _this._caps.maxVertexTextureImageUnits = 16;
  85940. _this._caps.maxTextureSize = 512;
  85941. _this._caps.maxCubemapTextureSize = 512;
  85942. _this._caps.maxRenderTextureSize = 512;
  85943. _this._caps.maxVertexAttribs = 16;
  85944. _this._caps.maxVaryingVectors = 16;
  85945. _this._caps.maxFragmentUniformVectors = 16;
  85946. _this._caps.maxVertexUniformVectors = 16;
  85947. // Extensions
  85948. _this._caps.standardDerivatives = false;
  85949. _this._caps.astc = null;
  85950. _this._caps.s3tc = null;
  85951. _this._caps.pvrtc = null;
  85952. _this._caps.etc1 = null;
  85953. _this._caps.etc2 = null;
  85954. _this._caps.textureAnisotropicFilterExtension = null;
  85955. _this._caps.maxAnisotropy = 0;
  85956. _this._caps.uintIndices = false;
  85957. _this._caps.fragmentDepthSupported = false;
  85958. _this._caps.highPrecisionShaderSupported = true;
  85959. _this._caps.colorBufferFloat = false;
  85960. _this._caps.textureFloat = false;
  85961. _this._caps.textureFloatLinearFiltering = false;
  85962. _this._caps.textureFloatRender = false;
  85963. _this._caps.textureHalfFloat = false;
  85964. _this._caps.textureHalfFloatLinearFiltering = false;
  85965. _this._caps.textureHalfFloatRender = false;
  85966. _this._caps.textureLOD = false;
  85967. _this._caps.drawBuffersExtension = false;
  85968. _this._caps.depthTextureExtension = false;
  85969. _this._caps.vertexArrayObject = false;
  85970. _this._caps.instancedArrays = false;
  85971. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  85972. // Wrappers
  85973. if (typeof URL === "undefined") {
  85974. URL = {
  85975. createObjectURL: function () { },
  85976. revokeObjectURL: function () { }
  85977. };
  85978. }
  85979. if (typeof Blob === "undefined") {
  85980. Blob = function () { };
  85981. }
  85982. return _this;
  85983. }
  85984. NullEngine.prototype.isDeterministicLockStep = function () {
  85985. return this._options.deterministicLockstep;
  85986. };
  85987. NullEngine.prototype.getLockstepMaxSteps = function () {
  85988. return this._options.lockstepMaxSteps;
  85989. };
  85990. NullEngine.prototype.createVertexBuffer = function (vertices) {
  85991. return {
  85992. capacity: 0,
  85993. references: 1,
  85994. is32Bits: false
  85995. };
  85996. };
  85997. NullEngine.prototype.createIndexBuffer = function (indices) {
  85998. return {
  85999. capacity: 0,
  86000. references: 1,
  86001. is32Bits: false
  86002. };
  86003. };
  86004. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  86005. if (stencil === void 0) { stencil = false; }
  86006. };
  86007. NullEngine.prototype.getRenderWidth = function (useScreen) {
  86008. if (useScreen === void 0) { useScreen = false; }
  86009. if (!useScreen && this._currentRenderTarget) {
  86010. return this._currentRenderTarget.width;
  86011. }
  86012. return this._options.renderWidth;
  86013. };
  86014. NullEngine.prototype.getRenderHeight = function (useScreen) {
  86015. if (useScreen === void 0) { useScreen = false; }
  86016. if (!useScreen && this._currentRenderTarget) {
  86017. return this._currentRenderTarget.height;
  86018. }
  86019. return this._options.renderHeight;
  86020. };
  86021. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  86022. this._cachedViewport = viewport;
  86023. };
  86024. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  86025. return {
  86026. transformFeedback: null,
  86027. __SPECTOR_rebuildProgram: null
  86028. };
  86029. };
  86030. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  86031. return [];
  86032. };
  86033. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  86034. return [];
  86035. };
  86036. NullEngine.prototype.bindSamplers = function (effect) {
  86037. this._currentEffect = null;
  86038. };
  86039. NullEngine.prototype.enableEffect = function (effect) {
  86040. this._currentEffect = effect;
  86041. if (effect.onBind) {
  86042. effect.onBind(effect);
  86043. }
  86044. effect.onBindObservable.notifyObservers(effect);
  86045. };
  86046. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  86047. if (zOffset === void 0) { zOffset = 0; }
  86048. if (reverseSide === void 0) { reverseSide = false; }
  86049. };
  86050. NullEngine.prototype.setIntArray = function (uniform, array) {
  86051. };
  86052. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  86053. };
  86054. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  86055. };
  86056. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  86057. };
  86058. NullEngine.prototype.setFloatArray = function (uniform, array) {
  86059. };
  86060. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  86061. };
  86062. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  86063. };
  86064. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  86065. };
  86066. NullEngine.prototype.setArray = function (uniform, array) {
  86067. };
  86068. NullEngine.prototype.setArray2 = function (uniform, array) {
  86069. };
  86070. NullEngine.prototype.setArray3 = function (uniform, array) {
  86071. };
  86072. NullEngine.prototype.setArray4 = function (uniform, array) {
  86073. };
  86074. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  86075. };
  86076. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  86077. };
  86078. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  86079. };
  86080. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  86081. };
  86082. NullEngine.prototype.setFloat = function (uniform, value) {
  86083. };
  86084. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  86085. };
  86086. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  86087. };
  86088. NullEngine.prototype.setBool = function (uniform, bool) {
  86089. };
  86090. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  86091. };
  86092. NullEngine.prototype.setColor3 = function (uniform, color3) {
  86093. };
  86094. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  86095. };
  86096. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  86097. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  86098. if (this._alphaMode === mode) {
  86099. return;
  86100. }
  86101. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  86102. if (!noDepthWriteChange) {
  86103. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  86104. }
  86105. this._alphaMode = mode;
  86106. };
  86107. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  86108. };
  86109. NullEngine.prototype.wipeCaches = function (bruteForce) {
  86110. if (this.preventCacheWipeBetweenFrames) {
  86111. return;
  86112. }
  86113. this.resetTextureCache();
  86114. this._currentEffect = null;
  86115. if (bruteForce) {
  86116. this._currentProgram = null;
  86117. this._stencilState.reset();
  86118. this._depthCullingState.reset();
  86119. this._alphaState.reset();
  86120. }
  86121. this._cachedVertexBuffers = null;
  86122. this._cachedIndexBuffer = null;
  86123. this._cachedEffectForVertexBuffers = null;
  86124. };
  86125. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  86126. };
  86127. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  86128. };
  86129. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  86130. };
  86131. NullEngine.prototype._createTexture = function () {
  86132. return {};
  86133. };
  86134. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  86135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86136. if (onLoad === void 0) { onLoad = null; }
  86137. if (onError === void 0) { onError = null; }
  86138. if (buffer === void 0) { buffer = null; }
  86139. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  86140. var url = String(urlArg);
  86141. texture.url = url;
  86142. texture.generateMipMaps = !noMipmap;
  86143. texture.samplingMode = samplingMode;
  86144. texture.invertY = invertY;
  86145. texture.baseWidth = this._options.textureSize;
  86146. texture.baseHeight = this._options.textureSize;
  86147. texture.width = this._options.textureSize;
  86148. texture.height = this._options.textureSize;
  86149. if (format) {
  86150. texture.format = format;
  86151. }
  86152. texture.isReady = true;
  86153. if (onLoad) {
  86154. onLoad();
  86155. }
  86156. return texture;
  86157. };
  86158. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  86159. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  86160. if (options !== undefined && typeof options === "object") {
  86161. fullOptions.generateMipMaps = options.generateMipMaps;
  86162. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  86163. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  86164. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  86165. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  86166. }
  86167. else {
  86168. fullOptions.generateMipMaps = options;
  86169. fullOptions.generateDepthBuffer = true;
  86170. fullOptions.generateStencilBuffer = false;
  86171. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86172. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86173. }
  86174. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  86175. var width = size.width || size;
  86176. var height = size.height || size;
  86177. texture._depthStencilBuffer = {};
  86178. texture._framebuffer = {};
  86179. texture.baseWidth = width;
  86180. texture.baseHeight = height;
  86181. texture.width = width;
  86182. texture.height = height;
  86183. texture.isReady = true;
  86184. texture.samples = 1;
  86185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  86186. texture.samplingMode = fullOptions.samplingMode;
  86187. texture.type = fullOptions.type;
  86188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  86189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  86190. return texture;
  86191. };
  86192. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  86193. texture.samplingMode = samplingMode;
  86194. };
  86195. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  86196. if (this._currentRenderTarget) {
  86197. this.unBindFramebuffer(this._currentRenderTarget);
  86198. }
  86199. this._currentRenderTarget = texture;
  86200. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  86201. if (this._cachedViewport && !forceFullscreenViewport) {
  86202. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  86203. }
  86204. };
  86205. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  86206. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  86207. this._currentRenderTarget = null;
  86208. if (onBeforeUnbind) {
  86209. if (texture._MSAAFramebuffer) {
  86210. this._currentFramebuffer = texture._framebuffer;
  86211. }
  86212. onBeforeUnbind();
  86213. }
  86214. this._currentFramebuffer = null;
  86215. };
  86216. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  86217. var vbo = {
  86218. capacity: 1,
  86219. references: 1,
  86220. is32Bits: false
  86221. };
  86222. return vbo;
  86223. };
  86224. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  86225. if (offset === void 0) { offset = 0; }
  86226. };
  86227. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  86228. };
  86229. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  86230. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  86231. this._boundTexturesCache[this._activeChannel] = texture;
  86232. }
  86233. };
  86234. NullEngine.prototype._bindTexture = function (channel, texture) {
  86235. if (channel < 0) {
  86236. return;
  86237. }
  86238. this._bindTextureDirectly(0, texture);
  86239. };
  86240. NullEngine.prototype._releaseBuffer = function (buffer) {
  86241. buffer.references--;
  86242. if (buffer.references === 0) {
  86243. return true;
  86244. }
  86245. return false;
  86246. };
  86247. return NullEngine;
  86248. }(BABYLON.Engine));
  86249. BABYLON.NullEngine = NullEngine;
  86250. })(BABYLON || (BABYLON = {}));
  86251. //# sourceMappingURL=babylon.nullEngine.js.map
  86252. var BABYLON;
  86253. (function (BABYLON) {
  86254. /**
  86255. * This class can be used to get instrumentation data from a Babylon engine
  86256. */
  86257. var EngineInstrumentation = /** @class */ (function () {
  86258. function EngineInstrumentation(engine) {
  86259. this.engine = engine;
  86260. this._captureGPUFrameTime = false;
  86261. this._gpuFrameTime = new BABYLON.PerfCounter();
  86262. this._captureShaderCompilationTime = false;
  86263. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86264. // Observers
  86265. this._onBeginFrameObserver = null;
  86266. this._onEndFrameObserver = null;
  86267. this._onBeforeShaderCompilationObserver = null;
  86268. this._onAfterShaderCompilationObserver = null;
  86269. }
  86270. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86271. // Properties
  86272. /**
  86273. * Gets the perf counter used for GPU frame time
  86274. */
  86275. get: function () {
  86276. return this._gpuFrameTime;
  86277. },
  86278. enumerable: true,
  86279. configurable: true
  86280. });
  86281. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86282. /**
  86283. * Gets the GPU frame time capture status
  86284. */
  86285. get: function () {
  86286. return this._captureGPUFrameTime;
  86287. },
  86288. /**
  86289. * Enable or disable the GPU frame time capture
  86290. */
  86291. set: function (value) {
  86292. var _this = this;
  86293. if (value === this._captureGPUFrameTime) {
  86294. return;
  86295. }
  86296. this._captureGPUFrameTime = value;
  86297. if (value) {
  86298. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86299. if (!_this._gpuFrameTimeToken) {
  86300. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86301. }
  86302. });
  86303. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86304. if (!_this._gpuFrameTimeToken) {
  86305. return;
  86306. }
  86307. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86308. if (time > -1) {
  86309. _this._gpuFrameTimeToken = null;
  86310. _this._gpuFrameTime.fetchNewFrame();
  86311. _this._gpuFrameTime.addCount(time, true);
  86312. }
  86313. });
  86314. }
  86315. else {
  86316. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86317. this._onBeginFrameObserver = null;
  86318. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86319. this._onEndFrameObserver = null;
  86320. }
  86321. },
  86322. enumerable: true,
  86323. configurable: true
  86324. });
  86325. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86326. /**
  86327. * Gets the perf counter used for shader compilation time
  86328. */
  86329. get: function () {
  86330. return this._shaderCompilationTime;
  86331. },
  86332. enumerable: true,
  86333. configurable: true
  86334. });
  86335. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86336. /**
  86337. * Gets the shader compilation time capture status
  86338. */
  86339. get: function () {
  86340. return this._captureShaderCompilationTime;
  86341. },
  86342. /**
  86343. * Enable or disable the shader compilation time capture
  86344. */
  86345. set: function (value) {
  86346. var _this = this;
  86347. if (value === this._captureShaderCompilationTime) {
  86348. return;
  86349. }
  86350. this._captureShaderCompilationTime = value;
  86351. if (value) {
  86352. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86353. _this._shaderCompilationTime.fetchNewFrame();
  86354. _this._shaderCompilationTime.beginMonitoring();
  86355. });
  86356. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86357. _this._shaderCompilationTime.endMonitoring();
  86358. });
  86359. }
  86360. else {
  86361. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86362. this._onBeforeShaderCompilationObserver = null;
  86363. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86364. this._onAfterShaderCompilationObserver = null;
  86365. }
  86366. },
  86367. enumerable: true,
  86368. configurable: true
  86369. });
  86370. EngineInstrumentation.prototype.dispose = function () {
  86371. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86372. this._onBeginFrameObserver = null;
  86373. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86374. this._onEndFrameObserver = null;
  86375. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86376. this._onBeforeShaderCompilationObserver = null;
  86377. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86378. this._onAfterShaderCompilationObserver = null;
  86379. this.engine = null;
  86380. };
  86381. return EngineInstrumentation;
  86382. }());
  86383. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86384. })(BABYLON || (BABYLON = {}));
  86385. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86386. var BABYLON;
  86387. (function (BABYLON) {
  86388. /**
  86389. * This class can be used to get instrumentation data from a Babylon engine
  86390. */
  86391. var SceneInstrumentation = /** @class */ (function () {
  86392. function SceneInstrumentation(scene) {
  86393. var _this = this;
  86394. this.scene = scene;
  86395. this._captureActiveMeshesEvaluationTime = false;
  86396. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86397. this._captureRenderTargetsRenderTime = false;
  86398. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86399. this._captureFrameTime = false;
  86400. this._frameTime = new BABYLON.PerfCounter();
  86401. this._captureRenderTime = false;
  86402. this._renderTime = new BABYLON.PerfCounter();
  86403. this._captureInterFrameTime = false;
  86404. this._interFrameTime = new BABYLON.PerfCounter();
  86405. this._captureParticlesRenderTime = false;
  86406. this._particlesRenderTime = new BABYLON.PerfCounter();
  86407. this._captureSpritesRenderTime = false;
  86408. this._spritesRenderTime = new BABYLON.PerfCounter();
  86409. this._capturePhysicsTime = false;
  86410. this._physicsTime = new BABYLON.PerfCounter();
  86411. this._captureAnimationsTime = false;
  86412. this._animationsTime = new BABYLON.PerfCounter();
  86413. // Observers
  86414. this._onBeforeActiveMeshesEvaluationObserver = null;
  86415. this._onAfterActiveMeshesEvaluationObserver = null;
  86416. this._onBeforeRenderTargetsRenderObserver = null;
  86417. this._onAfterRenderTargetsRenderObserver = null;
  86418. this._onAfterRenderObserver = null;
  86419. this._onBeforeDrawPhaseObserver = null;
  86420. this._onAfterDrawPhaseObserver = null;
  86421. this._onBeforeAnimationsObserver = null;
  86422. this._onBeforeParticlesRenderingObserver = null;
  86423. this._onAfterParticlesRenderingObserver = null;
  86424. this._onBeforeSpritesRenderingObserver = null;
  86425. this._onAfterSpritesRenderingObserver = null;
  86426. this._onBeforePhysicsObserver = null;
  86427. this._onAfterPhysicsObserver = null;
  86428. this._onAfterAnimationsObserver = null;
  86429. // Before render
  86430. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86431. if (_this._captureActiveMeshesEvaluationTime) {
  86432. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86433. }
  86434. if (_this._captureRenderTargetsRenderTime) {
  86435. _this._renderTargetsRenderTime.fetchNewFrame();
  86436. }
  86437. if (_this._captureFrameTime) {
  86438. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  86439. _this._frameTime.beginMonitoring();
  86440. }
  86441. if (_this._captureInterFrameTime) {
  86442. _this._interFrameTime.endMonitoring();
  86443. }
  86444. if (_this._captureParticlesRenderTime) {
  86445. _this._particlesRenderTime.fetchNewFrame();
  86446. }
  86447. if (_this._captureSpritesRenderTime) {
  86448. _this._spritesRenderTime.fetchNewFrame();
  86449. }
  86450. if (_this._captureAnimationsTime) {
  86451. _this._animationsTime.beginMonitoring();
  86452. }
  86453. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  86454. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  86455. });
  86456. // After render
  86457. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  86458. if (_this._captureFrameTime) {
  86459. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  86460. _this._frameTime.endMonitoring();
  86461. }
  86462. if (_this._captureRenderTime) {
  86463. _this._renderTime.endMonitoring(false);
  86464. }
  86465. if (_this._captureInterFrameTime) {
  86466. _this._interFrameTime.beginMonitoring();
  86467. }
  86468. });
  86469. }
  86470. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86471. // Properties
  86472. /**
  86473. * Gets the perf counter used for active meshes evaluation time
  86474. */
  86475. get: function () {
  86476. return this._activeMeshesEvaluationTime;
  86477. },
  86478. enumerable: true,
  86479. configurable: true
  86480. });
  86481. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86482. /**
  86483. * Gets the active meshes evaluation time capture status
  86484. */
  86485. get: function () {
  86486. return this._captureActiveMeshesEvaluationTime;
  86487. },
  86488. /**
  86489. * Enable or disable the active meshes evaluation time capture
  86490. */
  86491. set: function (value) {
  86492. var _this = this;
  86493. if (value === this._captureActiveMeshesEvaluationTime) {
  86494. return;
  86495. }
  86496. this._captureActiveMeshesEvaluationTime = value;
  86497. if (value) {
  86498. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86499. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86500. _this._activeMeshesEvaluationTime.beginMonitoring();
  86501. });
  86502. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86503. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86504. _this._activeMeshesEvaluationTime.endMonitoring();
  86505. });
  86506. }
  86507. else {
  86508. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86509. this._onBeforeActiveMeshesEvaluationObserver = null;
  86510. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86511. this._onAfterActiveMeshesEvaluationObserver = null;
  86512. }
  86513. },
  86514. enumerable: true,
  86515. configurable: true
  86516. });
  86517. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86518. /**
  86519. * Gets the perf counter used for render targets render time
  86520. */
  86521. get: function () {
  86522. return this._renderTargetsRenderTime;
  86523. },
  86524. enumerable: true,
  86525. configurable: true
  86526. });
  86527. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86528. /**
  86529. * Gets the render targets render time capture status
  86530. */
  86531. get: function () {
  86532. return this._captureRenderTargetsRenderTime;
  86533. },
  86534. /**
  86535. * Enable or disable the render targets render time capture
  86536. */
  86537. set: function (value) {
  86538. var _this = this;
  86539. if (value === this._captureRenderTargetsRenderTime) {
  86540. return;
  86541. }
  86542. this._captureRenderTargetsRenderTime = value;
  86543. if (value) {
  86544. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86545. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86546. _this._renderTargetsRenderTime.beginMonitoring();
  86547. });
  86548. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86549. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86550. _this._renderTargetsRenderTime.endMonitoring(false);
  86551. });
  86552. }
  86553. else {
  86554. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86555. this._onBeforeRenderTargetsRenderObserver = null;
  86556. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86557. this._onAfterRenderTargetsRenderObserver = null;
  86558. }
  86559. },
  86560. enumerable: true,
  86561. configurable: true
  86562. });
  86563. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86564. /**
  86565. * Gets the perf counter used for particles render time
  86566. */
  86567. get: function () {
  86568. return this._particlesRenderTime;
  86569. },
  86570. enumerable: true,
  86571. configurable: true
  86572. });
  86573. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86574. /**
  86575. * Gets the particles render time capture status
  86576. */
  86577. get: function () {
  86578. return this._captureParticlesRenderTime;
  86579. },
  86580. /**
  86581. * Enable or disable the particles render time capture
  86582. */
  86583. set: function (value) {
  86584. var _this = this;
  86585. if (value === this._captureParticlesRenderTime) {
  86586. return;
  86587. }
  86588. this._captureParticlesRenderTime = value;
  86589. if (value) {
  86590. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86591. BABYLON.Tools.StartPerformanceCounter("Particles");
  86592. _this._particlesRenderTime.beginMonitoring();
  86593. });
  86594. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86595. BABYLON.Tools.EndPerformanceCounter("Particles");
  86596. _this._particlesRenderTime.endMonitoring(false);
  86597. });
  86598. }
  86599. else {
  86600. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86601. this._onBeforeParticlesRenderingObserver = null;
  86602. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86603. this._onAfterParticlesRenderingObserver = null;
  86604. }
  86605. },
  86606. enumerable: true,
  86607. configurable: true
  86608. });
  86609. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86610. /**
  86611. * Gets the perf counter used for sprites render time
  86612. */
  86613. get: function () {
  86614. return this._spritesRenderTime;
  86615. },
  86616. enumerable: true,
  86617. configurable: true
  86618. });
  86619. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86620. /**
  86621. * Gets the sprites render time capture status
  86622. */
  86623. get: function () {
  86624. return this._captureSpritesRenderTime;
  86625. },
  86626. /**
  86627. * Enable or disable the sprites render time capture
  86628. */
  86629. set: function (value) {
  86630. var _this = this;
  86631. if (value === this._captureSpritesRenderTime) {
  86632. return;
  86633. }
  86634. this._captureSpritesRenderTime = value;
  86635. if (value) {
  86636. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86637. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86638. _this._spritesRenderTime.beginMonitoring();
  86639. });
  86640. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86641. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86642. _this._spritesRenderTime.endMonitoring(false);
  86643. });
  86644. }
  86645. else {
  86646. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86647. this._onBeforeSpritesRenderingObserver = null;
  86648. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86649. this._onAfterSpritesRenderingObserver = null;
  86650. }
  86651. },
  86652. enumerable: true,
  86653. configurable: true
  86654. });
  86655. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86656. /**
  86657. * Gets the perf counter used for physics time
  86658. */
  86659. get: function () {
  86660. return this._physicsTime;
  86661. },
  86662. enumerable: true,
  86663. configurable: true
  86664. });
  86665. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86666. /**
  86667. * Gets the physics time capture status
  86668. */
  86669. get: function () {
  86670. return this._capturePhysicsTime;
  86671. },
  86672. /**
  86673. * Enable or disable the physics time capture
  86674. */
  86675. set: function (value) {
  86676. var _this = this;
  86677. if (value === this._capturePhysicsTime) {
  86678. return;
  86679. }
  86680. this._capturePhysicsTime = value;
  86681. if (value) {
  86682. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86683. BABYLON.Tools.StartPerformanceCounter("Physics");
  86684. _this._physicsTime.beginMonitoring();
  86685. });
  86686. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86687. BABYLON.Tools.EndPerformanceCounter("Physics");
  86688. _this._physicsTime.endMonitoring();
  86689. });
  86690. }
  86691. else {
  86692. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86693. this._onBeforePhysicsObserver = null;
  86694. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86695. this._onAfterPhysicsObserver = null;
  86696. }
  86697. },
  86698. enumerable: true,
  86699. configurable: true
  86700. });
  86701. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86702. /**
  86703. * Gets the perf counter used for animations time
  86704. */
  86705. get: function () {
  86706. return this._animationsTime;
  86707. },
  86708. enumerable: true,
  86709. configurable: true
  86710. });
  86711. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86712. /**
  86713. * Gets the animations time capture status
  86714. */
  86715. get: function () {
  86716. return this._captureAnimationsTime;
  86717. },
  86718. /**
  86719. * Enable or disable the animations time capture
  86720. */
  86721. set: function (value) {
  86722. var _this = this;
  86723. if (value === this._captureAnimationsTime) {
  86724. return;
  86725. }
  86726. this._captureAnimationsTime = value;
  86727. if (value) {
  86728. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86729. _this._animationsTime.endMonitoring();
  86730. });
  86731. }
  86732. else {
  86733. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86734. this._onAfterAnimationsObserver = null;
  86735. }
  86736. },
  86737. enumerable: true,
  86738. configurable: true
  86739. });
  86740. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86741. /**
  86742. * Gets the perf counter used for frame time capture
  86743. */
  86744. get: function () {
  86745. return this._frameTime;
  86746. },
  86747. enumerable: true,
  86748. configurable: true
  86749. });
  86750. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86751. /**
  86752. * Gets the frame time capture status
  86753. */
  86754. get: function () {
  86755. return this._captureFrameTime;
  86756. },
  86757. /**
  86758. * Enable or disable the frame time capture
  86759. */
  86760. set: function (value) {
  86761. this._captureFrameTime = value;
  86762. },
  86763. enumerable: true,
  86764. configurable: true
  86765. });
  86766. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86767. /**
  86768. * Gets the perf counter used for inter-frames time capture
  86769. */
  86770. get: function () {
  86771. return this._interFrameTime;
  86772. },
  86773. enumerable: true,
  86774. configurable: true
  86775. });
  86776. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86777. /**
  86778. * Gets the inter-frames time capture status
  86779. */
  86780. get: function () {
  86781. return this._captureInterFrameTime;
  86782. },
  86783. /**
  86784. * Enable or disable the inter-frames time capture
  86785. */
  86786. set: function (value) {
  86787. this._captureInterFrameTime = value;
  86788. },
  86789. enumerable: true,
  86790. configurable: true
  86791. });
  86792. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86793. /**
  86794. * Gets the perf counter used for render time capture
  86795. */
  86796. get: function () {
  86797. return this._renderTime;
  86798. },
  86799. enumerable: true,
  86800. configurable: true
  86801. });
  86802. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86803. /**
  86804. * Gets the render time capture status
  86805. */
  86806. get: function () {
  86807. return this._captureRenderTime;
  86808. },
  86809. /**
  86810. * Enable or disable the render time capture
  86811. */
  86812. set: function (value) {
  86813. var _this = this;
  86814. if (value === this._captureRenderTime) {
  86815. return;
  86816. }
  86817. this._captureRenderTime = value;
  86818. if (value) {
  86819. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86820. _this._renderTime.beginMonitoring();
  86821. BABYLON.Tools.StartPerformanceCounter("Main render");
  86822. });
  86823. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86824. _this._renderTime.endMonitoring(false);
  86825. BABYLON.Tools.EndPerformanceCounter("Main render");
  86826. });
  86827. }
  86828. else {
  86829. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86830. this._onBeforeDrawPhaseObserver = null;
  86831. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86832. this._onAfterDrawPhaseObserver = null;
  86833. }
  86834. },
  86835. enumerable: true,
  86836. configurable: true
  86837. });
  86838. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86839. /**
  86840. * Gets the perf counter used for draw calls
  86841. */
  86842. get: function () {
  86843. return this.scene.getEngine()._drawCalls;
  86844. },
  86845. enumerable: true,
  86846. configurable: true
  86847. });
  86848. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86849. /**
  86850. * Gets the perf counter used for texture collisions
  86851. */
  86852. get: function () {
  86853. return this.scene.getEngine()._textureCollisions;
  86854. },
  86855. enumerable: true,
  86856. configurable: true
  86857. });
  86858. SceneInstrumentation.prototype.dispose = function () {
  86859. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86860. this._onAfterRenderObserver = null;
  86861. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86862. this._onBeforeActiveMeshesEvaluationObserver = null;
  86863. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86864. this._onAfterActiveMeshesEvaluationObserver = null;
  86865. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86866. this._onBeforeRenderTargetsRenderObserver = null;
  86867. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86868. this._onAfterRenderTargetsRenderObserver = null;
  86869. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86870. this._onBeforeAnimationsObserver = null;
  86871. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86872. this._onBeforeParticlesRenderingObserver = null;
  86873. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86874. this._onAfterParticlesRenderingObserver = null;
  86875. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86876. this._onBeforeSpritesRenderingObserver = null;
  86877. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86878. this._onAfterSpritesRenderingObserver = null;
  86879. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86880. this._onBeforeDrawPhaseObserver = null;
  86881. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86882. this._onAfterDrawPhaseObserver = null;
  86883. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86884. this._onBeforePhysicsObserver = null;
  86885. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86886. this._onAfterPhysicsObserver = null;
  86887. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86888. this._onAfterAnimationsObserver = null;
  86889. this.scene = null;
  86890. };
  86891. return SceneInstrumentation;
  86892. }());
  86893. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86894. })(BABYLON || (BABYLON = {}));
  86895. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86896. var BABYLON;
  86897. (function (BABYLON) {
  86898. var _TimeToken = /** @class */ (function () {
  86899. function _TimeToken() {
  86900. this._timeElapsedQueryEnded = false;
  86901. }
  86902. return _TimeToken;
  86903. }());
  86904. BABYLON._TimeToken = _TimeToken;
  86905. })(BABYLON || (BABYLON = {}));
  86906. //# sourceMappingURL=babylon.timeToken.js.map
  86907. var BABYLON;
  86908. (function (BABYLON) {
  86909. /**
  86910. * Background material defines definition.
  86911. * @ignore Mainly internal Use
  86912. */
  86913. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86914. __extends(BackgroundMaterialDefines, _super);
  86915. /**
  86916. * Constructor of the defines.
  86917. */
  86918. function BackgroundMaterialDefines() {
  86919. var _this = _super.call(this) || this;
  86920. /**
  86921. * True if the diffuse texture is in use.
  86922. */
  86923. _this.DIFFUSE = false;
  86924. /**
  86925. * The direct UV channel to use.
  86926. */
  86927. _this.DIFFUSEDIRECTUV = 0;
  86928. /**
  86929. * True if the diffuse texture is in gamma space.
  86930. */
  86931. _this.GAMMADIFFUSE = false;
  86932. /**
  86933. * True if the diffuse texture has opacity in the alpha channel.
  86934. */
  86935. _this.DIFFUSEHASALPHA = false;
  86936. /**
  86937. * True if you want the material to fade to transparent at grazing angle.
  86938. */
  86939. _this.OPACITYFRESNEL = false;
  86940. /**
  86941. * True if an extra blur needs to be added in the reflection.
  86942. */
  86943. _this.REFLECTIONBLUR = false;
  86944. /**
  86945. * True if you want the material to fade to reflection at grazing angle.
  86946. */
  86947. _this.REFLECTIONFRESNEL = false;
  86948. /**
  86949. * True if you want the material to falloff as far as you move away from the scene center.
  86950. */
  86951. _this.REFLECTIONFALLOFF = false;
  86952. /**
  86953. * False if the current Webgl implementation does not support the texture lod extension.
  86954. */
  86955. _this.TEXTURELODSUPPORT = false;
  86956. /**
  86957. * True to ensure the data are premultiplied.
  86958. */
  86959. _this.PREMULTIPLYALPHA = false;
  86960. /**
  86961. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86962. */
  86963. _this.USERGBCOLOR = false;
  86964. /**
  86965. * True to add noise in order to reduce the banding effect.
  86966. */
  86967. _this.NOISE = false;
  86968. // Image Processing Configuration.
  86969. _this.IMAGEPROCESSING = false;
  86970. _this.VIGNETTE = false;
  86971. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86972. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86973. _this.TONEMAPPING = false;
  86974. _this.CONTRAST = false;
  86975. _this.COLORCURVES = false;
  86976. _this.COLORGRADING = false;
  86977. _this.COLORGRADING3D = false;
  86978. _this.SAMPLER3DGREENDEPTH = false;
  86979. _this.SAMPLER3DBGRMAP = false;
  86980. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86981. _this.EXPOSURE = false;
  86982. // Reflection.
  86983. _this.REFLECTION = false;
  86984. _this.REFLECTIONMAP_3D = false;
  86985. _this.REFLECTIONMAP_SPHERICAL = false;
  86986. _this.REFLECTIONMAP_PLANAR = false;
  86987. _this.REFLECTIONMAP_CUBIC = false;
  86988. _this.REFLECTIONMAP_PROJECTION = false;
  86989. _this.REFLECTIONMAP_SKYBOX = false;
  86990. _this.REFLECTIONMAP_EXPLICIT = false;
  86991. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86992. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86993. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86994. _this.INVERTCUBICMAP = false;
  86995. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86996. _this.LODINREFLECTIONALPHA = false;
  86997. _this.GAMMAREFLECTION = false;
  86998. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86999. // Default BJS.
  87000. _this.MAINUV1 = false;
  87001. _this.MAINUV2 = false;
  87002. _this.UV1 = false;
  87003. _this.UV2 = false;
  87004. _this.CLIPPLANE = false;
  87005. _this.POINTSIZE = false;
  87006. _this.FOG = false;
  87007. _this.NORMAL = false;
  87008. _this.NUM_BONE_INFLUENCERS = 0;
  87009. _this.BonesPerMesh = 0;
  87010. _this.INSTANCES = false;
  87011. _this.SHADOWFLOAT = false;
  87012. _this.rebuild();
  87013. return _this;
  87014. }
  87015. return BackgroundMaterialDefines;
  87016. }(BABYLON.MaterialDefines));
  87017. /**
  87018. * Background material used to create an efficient environement around your scene.
  87019. */
  87020. var BackgroundMaterial = /** @class */ (function (_super) {
  87021. __extends(BackgroundMaterial, _super);
  87022. /**
  87023. * Instantiates a Background Material in the given scene
  87024. * @param name The friendly name of the material
  87025. * @param scene The scene to add the material to
  87026. */
  87027. function BackgroundMaterial(name, scene) {
  87028. var _this = _super.call(this, name, scene) || this;
  87029. /**
  87030. * Key light Color (multiply against the R channel of the environement texture)
  87031. */
  87032. _this.primaryColor = BABYLON.Color3.White();
  87033. /**
  87034. * Key light Level (allowing HDR output of the background)
  87035. */
  87036. _this.primaryLevel = 1;
  87037. /**
  87038. * Secondary light Color (multiply against the G channel of the environement texture)
  87039. */
  87040. _this.secondaryColor = BABYLON.Color3.Gray();
  87041. /**
  87042. * Secondary light Level (allowing HDR output of the background)
  87043. */
  87044. _this.secondaryLevel = 1;
  87045. /**
  87046. * Tertiary light Color (multiply against the B channel of the environement texture)
  87047. */
  87048. _this.tertiaryColor = BABYLON.Color3.Black();
  87049. /**
  87050. * Tertiary light Level (allowing HDR output of the background)
  87051. */
  87052. _this.tertiaryLevel = 1;
  87053. /**
  87054. * Reflection Texture used in the material.
  87055. * Should be author in a specific way for the best result (refer to the documentation).
  87056. */
  87057. _this.reflectionTexture = null;
  87058. /**
  87059. * Reflection Texture level of blur.
  87060. *
  87061. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87062. * texture twice.
  87063. */
  87064. _this.reflectionBlur = 0;
  87065. /**
  87066. * Diffuse Texture used in the material.
  87067. * Should be author in a specific way for the best result (refer to the documentation).
  87068. */
  87069. _this.diffuseTexture = null;
  87070. _this._shadowLights = null;
  87071. /**
  87072. * Specify the list of lights casting shadow on the material.
  87073. * All scene shadow lights will be included if null.
  87074. */
  87075. _this.shadowLights = null;
  87076. /**
  87077. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87078. * soft lighting on the background.
  87079. */
  87080. _this.shadowBlurScale = 1;
  87081. /**
  87082. * Helps adjusting the shadow to a softer level if required.
  87083. * 0 means black shadows and 1 means no shadows.
  87084. */
  87085. _this.shadowLevel = 0;
  87086. /**
  87087. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87088. * It is usually zero but might be interesting to modify according to your setup.
  87089. */
  87090. _this.sceneCenter = BABYLON.Vector3.Zero();
  87091. /**
  87092. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87093. * This helps ensuring a nice transition when the camera goes under the ground.
  87094. */
  87095. _this.opacityFresnel = true;
  87096. /**
  87097. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87098. * This helps adding a mirror texture on the ground.
  87099. */
  87100. _this.reflectionFresnel = false;
  87101. /**
  87102. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87103. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87104. */
  87105. _this.reflectionFalloffDistance = 0.0;
  87106. /**
  87107. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87108. */
  87109. _this.reflectionAmount = 1.0;
  87110. /**
  87111. * This specifies the weight of the reflection at grazing angle.
  87112. */
  87113. _this.reflectionReflectance0 = 0.05;
  87114. /**
  87115. * This specifies the weight of the reflection at a perpendicular point of view.
  87116. */
  87117. _this.reflectionReflectance90 = 0.5;
  87118. /**
  87119. * Helps to directly use the maps channels instead of their level.
  87120. */
  87121. _this.useRGBColor = true;
  87122. /**
  87123. * This helps reducing the banding effect that could occur on the background.
  87124. */
  87125. _this.enableNoise = false;
  87126. _this._fovMultiplier = 1.0;
  87127. /**
  87128. * Enable the FOV adjustment feature controlled by fovMultiplier.
  87129. * @type {boolean}
  87130. */
  87131. _this.useEquirectangularFOV = false;
  87132. _this._maxSimultaneousLights = 4;
  87133. /**
  87134. * Number of Simultaneous lights allowed on the material.
  87135. */
  87136. _this.maxSimultaneousLights = 4;
  87137. /**
  87138. * Keep track of the image processing observer to allow dispose and replace.
  87139. */
  87140. _this._imageProcessingObserver = null;
  87141. // Temp values kept as cache in the material.
  87142. _this._renderTargets = new BABYLON.SmartArray(16);
  87143. _this._reflectionControls = BABYLON.Vector4.Zero();
  87144. // Setup the default processing configuration to the scene.
  87145. _this._attachImageProcessingConfiguration(null);
  87146. _this.getRenderTargetTextures = function () {
  87147. _this._renderTargets.reset();
  87148. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  87149. _this._renderTargets.push(_this._diffuseTexture);
  87150. }
  87151. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  87152. _this._renderTargets.push(_this._reflectionTexture);
  87153. }
  87154. return _this._renderTargets;
  87155. };
  87156. return _this;
  87157. }
  87158. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  87159. /**
  87160. * Sets the reflection reflectance fresnel values according to the default standard
  87161. * empirically know to work well :-)
  87162. */
  87163. set: function (value) {
  87164. var reflectionWeight = value;
  87165. if (reflectionWeight < 0.5) {
  87166. reflectionWeight = reflectionWeight * 2.0;
  87167. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  87168. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  87169. }
  87170. else {
  87171. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  87172. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  87173. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  87174. }
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  87180. /**
  87181. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  87182. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  87183. * Recommended to be keep at 1.0 except for special cases.
  87184. */
  87185. get: function () {
  87186. return this._fovMultiplier;
  87187. },
  87188. set: function (value) {
  87189. if (isNaN(value)) {
  87190. value = 1.0;
  87191. }
  87192. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  87193. },
  87194. enumerable: true,
  87195. configurable: true
  87196. });
  87197. /**
  87198. * Attaches a new image processing configuration to the PBR Material.
  87199. * @param configuration (if null the scene configuration will be use)
  87200. */
  87201. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  87202. var _this = this;
  87203. if (configuration === this._imageProcessingConfiguration) {
  87204. return;
  87205. }
  87206. // Detaches observer.
  87207. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87208. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87209. }
  87210. // Pick the scene configuration if needed.
  87211. if (!configuration) {
  87212. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  87213. }
  87214. else {
  87215. this._imageProcessingConfiguration = configuration;
  87216. }
  87217. // Attaches observer.
  87218. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87219. _this._markAllSubMeshesAsImageProcessingDirty();
  87220. });
  87221. };
  87222. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  87223. /**
  87224. * Gets the image processing configuration used either in this material.
  87225. */
  87226. get: function () {
  87227. return this._imageProcessingConfiguration;
  87228. },
  87229. /**
  87230. * Sets the Default image processing configuration used either in the this material.
  87231. *
  87232. * If sets to null, the scene one is in use.
  87233. */
  87234. set: function (value) {
  87235. this._attachImageProcessingConfiguration(value);
  87236. // Ensure the effect will be rebuilt.
  87237. this._markAllSubMeshesAsTexturesDirty();
  87238. },
  87239. enumerable: true,
  87240. configurable: true
  87241. });
  87242. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  87243. /**
  87244. * Gets wether the color curves effect is enabled.
  87245. */
  87246. get: function () {
  87247. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87248. },
  87249. /**
  87250. * Sets wether the color curves effect is enabled.
  87251. */
  87252. set: function (value) {
  87253. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87254. },
  87255. enumerable: true,
  87256. configurable: true
  87257. });
  87258. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87259. /**
  87260. * Gets wether the color grading effect is enabled.
  87261. */
  87262. get: function () {
  87263. return this.imageProcessingConfiguration.colorGradingEnabled;
  87264. },
  87265. /**
  87266. * Gets wether the color grading effect is enabled.
  87267. */
  87268. set: function (value) {
  87269. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87270. },
  87271. enumerable: true,
  87272. configurable: true
  87273. });
  87274. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87275. /**
  87276. * Gets wether tonemapping is enabled or not.
  87277. */
  87278. get: function () {
  87279. return this._imageProcessingConfiguration.toneMappingEnabled;
  87280. },
  87281. /**
  87282. * Sets wether tonemapping is enabled or not
  87283. */
  87284. set: function (value) {
  87285. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87286. },
  87287. enumerable: true,
  87288. configurable: true
  87289. });
  87290. ;
  87291. ;
  87292. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87293. /**
  87294. * The camera exposure used on this material.
  87295. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87296. * This corresponds to a photographic exposure.
  87297. */
  87298. get: function () {
  87299. return this._imageProcessingConfiguration.exposure;
  87300. },
  87301. /**
  87302. * The camera exposure used on this material.
  87303. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87304. * This corresponds to a photographic exposure.
  87305. */
  87306. set: function (value) {
  87307. this._imageProcessingConfiguration.exposure = value;
  87308. },
  87309. enumerable: true,
  87310. configurable: true
  87311. });
  87312. ;
  87313. ;
  87314. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87315. /**
  87316. * Gets The camera contrast used on this material.
  87317. */
  87318. get: function () {
  87319. return this._imageProcessingConfiguration.contrast;
  87320. },
  87321. /**
  87322. * Sets The camera contrast used on this material.
  87323. */
  87324. set: function (value) {
  87325. this._imageProcessingConfiguration.contrast = value;
  87326. },
  87327. enumerable: true,
  87328. configurable: true
  87329. });
  87330. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87331. /**
  87332. * Gets the Color Grading 2D Lookup Texture.
  87333. */
  87334. get: function () {
  87335. return this._imageProcessingConfiguration.colorGradingTexture;
  87336. },
  87337. /**
  87338. * Sets the Color Grading 2D Lookup Texture.
  87339. */
  87340. set: function (value) {
  87341. this.imageProcessingConfiguration.colorGradingTexture = value;
  87342. },
  87343. enumerable: true,
  87344. configurable: true
  87345. });
  87346. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87347. /**
  87348. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87349. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87350. * 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;
  87351. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87352. */
  87353. get: function () {
  87354. return this.imageProcessingConfiguration.colorCurves;
  87355. },
  87356. /**
  87357. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87358. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87359. * 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;
  87360. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87361. */
  87362. set: function (value) {
  87363. this.imageProcessingConfiguration.colorCurves = value;
  87364. },
  87365. enumerable: true,
  87366. configurable: true
  87367. });
  87368. /**
  87369. * The entire material has been created in order to prevent overdraw.
  87370. * @returns false
  87371. */
  87372. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87373. return true;
  87374. };
  87375. /**
  87376. * The entire material has been created in order to prevent overdraw.
  87377. * @returns true if blending is enable
  87378. */
  87379. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87380. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87381. };
  87382. /**
  87383. * Checks wether the material is ready to be rendered for a given mesh.
  87384. * @param mesh The mesh to render
  87385. * @param subMesh The submesh to check against
  87386. * @param useInstances Specify wether or not the material is used with instances
  87387. * @returns true if all the dependencies are ready (Textures, Effects...)
  87388. */
  87389. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87390. var _this = this;
  87391. if (useInstances === void 0) { useInstances = false; }
  87392. if (subMesh.effect && this.isFrozen) {
  87393. if (this._wasPreviouslyReady) {
  87394. return true;
  87395. }
  87396. }
  87397. if (!subMesh._materialDefines) {
  87398. subMesh._materialDefines = new BackgroundMaterialDefines();
  87399. }
  87400. var scene = this.getScene();
  87401. var defines = subMesh._materialDefines;
  87402. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87403. if (defines._renderId === scene.getRenderId()) {
  87404. return true;
  87405. }
  87406. }
  87407. var engine = scene.getEngine();
  87408. // Lights
  87409. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87410. defines._needNormals = true;
  87411. // Textures
  87412. if (defines._areTexturesDirty) {
  87413. defines._needUVs = false;
  87414. if (scene.texturesEnabled) {
  87415. if (scene.getEngine().getCaps().textureLOD) {
  87416. defines.TEXTURELODSUPPORT = true;
  87417. }
  87418. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87419. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87420. return false;
  87421. }
  87422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87423. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87424. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87425. defines.OPACITYFRESNEL = this._opacityFresnel;
  87426. }
  87427. else {
  87428. defines.DIFFUSE = false;
  87429. defines.DIFFUSEHASALPHA = false;
  87430. defines.GAMMADIFFUSE = false;
  87431. defines.OPACITYFRESNEL = false;
  87432. }
  87433. var reflectionTexture = this._reflectionTexture;
  87434. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87435. if (!reflectionTexture.isReadyOrNotBlocking()) {
  87436. return false;
  87437. }
  87438. defines.REFLECTION = true;
  87439. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  87440. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  87441. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  87442. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  87443. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  87444. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  87445. defines.INVERTCUBICMAP = true;
  87446. }
  87447. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  87448. switch (reflectionTexture.coordinatesMode) {
  87449. case BABYLON.Texture.CUBIC_MODE:
  87450. case BABYLON.Texture.INVCUBIC_MODE:
  87451. defines.REFLECTIONMAP_CUBIC = true;
  87452. break;
  87453. case BABYLON.Texture.EXPLICIT_MODE:
  87454. defines.REFLECTIONMAP_EXPLICIT = true;
  87455. break;
  87456. case BABYLON.Texture.PLANAR_MODE:
  87457. defines.REFLECTIONMAP_PLANAR = true;
  87458. break;
  87459. case BABYLON.Texture.PROJECTION_MODE:
  87460. defines.REFLECTIONMAP_PROJECTION = true;
  87461. break;
  87462. case BABYLON.Texture.SKYBOX_MODE:
  87463. defines.REFLECTIONMAP_SKYBOX = true;
  87464. break;
  87465. case BABYLON.Texture.SPHERICAL_MODE:
  87466. defines.REFLECTIONMAP_SPHERICAL = true;
  87467. break;
  87468. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87469. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87470. break;
  87471. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87472. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87473. break;
  87474. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87475. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87476. break;
  87477. }
  87478. if (this.reflectionFresnel) {
  87479. defines.REFLECTIONFRESNEL = true;
  87480. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87481. this._reflectionControls.x = this.reflectionAmount;
  87482. this._reflectionControls.y = this.reflectionReflectance0;
  87483. this._reflectionControls.z = this.reflectionReflectance90;
  87484. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87485. }
  87486. else {
  87487. defines.REFLECTIONFRESNEL = false;
  87488. defines.REFLECTIONFALLOFF = false;
  87489. }
  87490. }
  87491. else {
  87492. defines.REFLECTION = false;
  87493. defines.REFLECTIONFALLOFF = false;
  87494. defines.REFLECTIONBLUR = false;
  87495. defines.REFLECTIONMAP_3D = false;
  87496. defines.REFLECTIONMAP_SPHERICAL = false;
  87497. defines.REFLECTIONMAP_PLANAR = false;
  87498. defines.REFLECTIONMAP_CUBIC = false;
  87499. defines.REFLECTIONMAP_PROJECTION = false;
  87500. defines.REFLECTIONMAP_SKYBOX = false;
  87501. defines.REFLECTIONMAP_EXPLICIT = false;
  87502. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87503. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87504. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87505. defines.INVERTCUBICMAP = false;
  87506. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87507. defines.LODINREFLECTIONALPHA = false;
  87508. defines.GAMMAREFLECTION = false;
  87509. }
  87510. }
  87511. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87512. defines.USERGBCOLOR = this._useRGBColor;
  87513. defines.NOISE = this._enableNoise;
  87514. }
  87515. if (defines._areImageProcessingDirty) {
  87516. if (!this._imageProcessingConfiguration.isReady()) {
  87517. return false;
  87518. }
  87519. this._imageProcessingConfiguration.prepareDefines(defines);
  87520. }
  87521. // Misc.
  87522. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87523. // Values that need to be evaluated on every frame
  87524. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87525. // Attribs
  87526. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87527. if (mesh) {
  87528. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87529. mesh.createNormals(true);
  87530. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87531. }
  87532. }
  87533. }
  87534. // Get correct effect
  87535. if (defines.isDirty) {
  87536. defines.markAsProcessed();
  87537. scene.resetCachedMaterial();
  87538. // Fallbacks
  87539. var fallbacks = new BABYLON.EffectFallbacks();
  87540. if (defines.FOG) {
  87541. fallbacks.addFallback(0, "FOG");
  87542. }
  87543. if (defines.POINTSIZE) {
  87544. fallbacks.addFallback(1, "POINTSIZE");
  87545. }
  87546. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87547. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87548. fallbacks.addCPUSkinningFallback(0, mesh);
  87549. }
  87550. //Attributes
  87551. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87552. if (defines.NORMAL) {
  87553. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87554. }
  87555. if (defines.UV1) {
  87556. attribs.push(BABYLON.VertexBuffer.UVKind);
  87557. }
  87558. if (defines.UV2) {
  87559. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87560. }
  87561. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87562. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87563. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87564. "vFogInfos", "vFogColor", "pointSize",
  87565. "vClipPlane", "mBones",
  87566. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87567. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87568. "shadowLevel", "alpha",
  87569. "vBackgroundCenter", "vReflectionControl",
  87570. "vDiffuseInfos", "diffuseMatrix",
  87571. ];
  87572. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87573. var uniformBuffers = ["Material", "Scene"];
  87574. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87575. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87576. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87577. uniformsNames: uniforms,
  87578. uniformBuffersNames: uniformBuffers,
  87579. samplers: samplers,
  87580. defines: defines,
  87581. maxSimultaneousLights: this._maxSimultaneousLights
  87582. });
  87583. var onCompiled = function (effect) {
  87584. if (_this.onCompiled) {
  87585. _this.onCompiled(effect);
  87586. }
  87587. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87588. };
  87589. var join = defines.toString();
  87590. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87591. attributes: attribs,
  87592. uniformsNames: uniforms,
  87593. uniformBuffersNames: uniformBuffers,
  87594. samplers: samplers,
  87595. defines: join,
  87596. fallbacks: fallbacks,
  87597. onCompiled: onCompiled,
  87598. onError: this.onError,
  87599. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87600. }, engine), defines);
  87601. this.buildUniformLayout();
  87602. }
  87603. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87604. return false;
  87605. }
  87606. defines._renderId = scene.getRenderId();
  87607. this._wasPreviouslyReady = true;
  87608. return true;
  87609. };
  87610. /**
  87611. * Build the uniform buffer used in the material.
  87612. */
  87613. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87614. // Order is important !
  87615. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87616. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87617. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87618. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87619. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87620. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87621. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87622. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87623. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87624. this._uniformBuffer.addUniform("pointSize", 1);
  87625. this._uniformBuffer.addUniform("shadowLevel", 1);
  87626. this._uniformBuffer.addUniform("alpha", 1);
  87627. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87628. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87629. this._uniformBuffer.create();
  87630. };
  87631. /**
  87632. * Unbind the material.
  87633. */
  87634. BackgroundMaterial.prototype.unbind = function () {
  87635. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87636. this._uniformBuffer.setTexture("diffuseSampler", null);
  87637. }
  87638. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87639. this._uniformBuffer.setTexture("reflectionSampler", null);
  87640. }
  87641. _super.prototype.unbind.call(this);
  87642. };
  87643. /**
  87644. * Bind only the world matrix to the material.
  87645. * @param world The world matrix to bind.
  87646. */
  87647. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87648. this._activeEffect.setMatrix("world", world);
  87649. };
  87650. /**
  87651. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87652. * @param world The world matrix to bind.
  87653. * @param subMesh The submesh to bind for.
  87654. */
  87655. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87656. var scene = this.getScene();
  87657. var defines = subMesh._materialDefines;
  87658. if (!defines) {
  87659. return;
  87660. }
  87661. var effect = subMesh.effect;
  87662. if (!effect) {
  87663. return;
  87664. }
  87665. this._activeEffect = effect;
  87666. // Matrices
  87667. this.bindOnlyWorldMatrix(world);
  87668. // Bones
  87669. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87670. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87671. if (mustRebind) {
  87672. this._uniformBuffer.bindToEffect(effect, "Material");
  87673. this.bindViewProjection(effect);
  87674. var reflectionTexture = this._reflectionTexture;
  87675. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87676. // Texture uniforms
  87677. if (scene.texturesEnabled) {
  87678. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87679. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87680. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87681. }
  87682. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87683. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87684. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87685. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87686. }
  87687. }
  87688. if (this.shadowLevel > 0) {
  87689. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87690. }
  87691. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87692. // Point size
  87693. if (this.pointsCloud) {
  87694. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87695. }
  87696. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87697. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87698. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87699. }
  87700. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87701. // Textures
  87702. if (scene.texturesEnabled) {
  87703. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87704. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87705. }
  87706. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87707. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87708. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87709. }
  87710. else if (!defines.REFLECTIONBLUR) {
  87711. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87712. }
  87713. else {
  87714. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87715. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87716. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87717. }
  87718. if (defines.REFLECTIONFRESNEL) {
  87719. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87720. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87721. }
  87722. }
  87723. }
  87724. // Clip plane
  87725. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87726. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87727. }
  87728. if (mustRebind || !this.isFrozen) {
  87729. if (scene.lightsEnabled) {
  87730. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87731. }
  87732. // View
  87733. this.bindView(effect);
  87734. // Fog
  87735. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87736. // image processing
  87737. this._imageProcessingConfiguration.bind(this._activeEffect);
  87738. }
  87739. this._uniformBuffer.update();
  87740. this._afterBind(mesh);
  87741. };
  87742. /**
  87743. * Dispose the material.
  87744. * @param forceDisposeEffect Force disposal of the associated effect.
  87745. * @param forceDisposeTextures Force disposal of the associated textures.
  87746. */
  87747. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87748. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87749. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87750. if (forceDisposeTextures) {
  87751. if (this.diffuseTexture) {
  87752. this.diffuseTexture.dispose();
  87753. }
  87754. if (this.reflectionTexture) {
  87755. this.reflectionTexture.dispose();
  87756. }
  87757. }
  87758. this._renderTargets.dispose();
  87759. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87760. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87761. }
  87762. _super.prototype.dispose.call(this, forceDisposeEffect);
  87763. };
  87764. /**
  87765. * Clones the material.
  87766. * @param name The cloned name.
  87767. * @returns The cloned material.
  87768. */
  87769. BackgroundMaterial.prototype.clone = function (name) {
  87770. var _this = this;
  87771. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87772. };
  87773. /**
  87774. * Serializes the current material to its JSON representation.
  87775. * @returns The JSON representation.
  87776. */
  87777. BackgroundMaterial.prototype.serialize = function () {
  87778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87779. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87780. return serializationObject;
  87781. };
  87782. /**
  87783. * Gets the class name of the material
  87784. * @returns "BackgroundMaterial"
  87785. */
  87786. BackgroundMaterial.prototype.getClassName = function () {
  87787. return "BackgroundMaterial";
  87788. };
  87789. /**
  87790. * Parse a JSON input to create back a background material.
  87791. * @param source The JSON data to parse
  87792. * @param scene The scene to create the parsed material in
  87793. * @param rootUrl The root url of the assets the material depends upon
  87794. * @returns the instantiated BackgroundMaterial.
  87795. */
  87796. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87797. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87798. };
  87799. /**
  87800. * Standard reflectance value at parallel view angle.
  87801. */
  87802. BackgroundMaterial.StandardReflectance0 = 0.05;
  87803. /**
  87804. * Standard reflectance value at grazing angle.
  87805. */
  87806. BackgroundMaterial.StandardReflectance90 = 0.5;
  87807. __decorate([
  87808. BABYLON.serializeAsColor3()
  87809. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87810. __decorate([
  87811. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87812. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87813. __decorate([
  87814. BABYLON.serialize()
  87815. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87816. __decorate([
  87817. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87818. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87819. __decorate([
  87820. BABYLON.serializeAsColor3()
  87821. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87822. __decorate([
  87823. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87824. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87825. __decorate([
  87826. BABYLON.serialize()
  87827. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87828. __decorate([
  87829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87830. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87831. __decorate([
  87832. BABYLON.serializeAsColor3()
  87833. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87834. __decorate([
  87835. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87836. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87837. __decorate([
  87838. BABYLON.serialize()
  87839. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87840. __decorate([
  87841. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87842. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87843. __decorate([
  87844. BABYLON.serializeAsTexture()
  87845. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87846. __decorate([
  87847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87848. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87849. __decorate([
  87850. BABYLON.serialize()
  87851. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87852. __decorate([
  87853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87854. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87855. __decorate([
  87856. BABYLON.serializeAsTexture()
  87857. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87858. __decorate([
  87859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87860. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87861. __decorate([
  87862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87863. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87864. __decorate([
  87865. BABYLON.serialize()
  87866. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87867. __decorate([
  87868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87869. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87870. __decorate([
  87871. BABYLON.serialize()
  87872. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87873. __decorate([
  87874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87875. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87876. __decorate([
  87877. BABYLON.serializeAsVector3()
  87878. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87879. __decorate([
  87880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87881. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87882. __decorate([
  87883. BABYLON.serialize()
  87884. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87885. __decorate([
  87886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87887. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87888. __decorate([
  87889. BABYLON.serialize()
  87890. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87891. __decorate([
  87892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87893. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87894. __decorate([
  87895. BABYLON.serialize()
  87896. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87897. __decorate([
  87898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87899. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87900. __decorate([
  87901. BABYLON.serialize()
  87902. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87903. __decorate([
  87904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87905. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87906. __decorate([
  87907. BABYLON.serialize()
  87908. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87909. __decorate([
  87910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87911. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87912. __decorate([
  87913. BABYLON.serialize()
  87914. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87915. __decorate([
  87916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87917. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87918. __decorate([
  87919. BABYLON.serialize()
  87920. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87921. __decorate([
  87922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87923. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87924. __decorate([
  87925. BABYLON.serialize()
  87926. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87927. __decorate([
  87928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87929. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87930. __decorate([
  87931. BABYLON.serialize()
  87932. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87933. __decorate([
  87934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87935. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87936. __decorate([
  87937. BABYLON.serializeAsImageProcessingConfiguration()
  87938. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87939. return BackgroundMaterial;
  87940. }(BABYLON.PushMaterial));
  87941. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87942. })(BABYLON || (BABYLON = {}));
  87943. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87944. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87945. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87946. s = arguments[i];
  87947. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87948. t[p] = s[p];
  87949. }
  87950. return t;
  87951. };
  87952. var BABYLON;
  87953. (function (BABYLON) {
  87954. /**
  87955. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87956. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87957. * It also helps with the default setup of your imageProcessing configuration.
  87958. */
  87959. var EnvironmentHelper = /** @class */ (function () {
  87960. /**
  87961. * constructor
  87962. * @param options
  87963. * @param scene The scene to add the material to
  87964. */
  87965. function EnvironmentHelper(options, scene) {
  87966. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87967. this._scene = scene;
  87968. this._setupBackground();
  87969. this._setupImageProcessing();
  87970. }
  87971. /**
  87972. * Creates the default options for the helper.
  87973. */
  87974. EnvironmentHelper._getDefaultOptions = function () {
  87975. return {
  87976. createGround: true,
  87977. groundSize: 15,
  87978. groundTexture: this._groundTextureCDNUrl,
  87979. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87980. groundOpacity: 0.9,
  87981. enableGroundShadow: true,
  87982. groundShadowLevel: 0.5,
  87983. enableGroundMirror: false,
  87984. groundMirrorSizeRatio: 0.3,
  87985. groundMirrorBlurKernel: 64,
  87986. groundMirrorAmount: 1,
  87987. groundMirrorFresnelWeight: 1,
  87988. groundMirrorFallOffDistance: 0,
  87989. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87990. groundYBias: 0.00001,
  87991. createSkybox: true,
  87992. skyboxSize: 20,
  87993. skyboxTexture: this._skyboxTextureCDNUrl,
  87994. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87995. backgroundYRotation: 0,
  87996. sizeAuto: true,
  87997. rootPosition: BABYLON.Vector3.Zero(),
  87998. setupImageProcessing: true,
  87999. environmentTexture: this._environmentTextureCDNUrl,
  88000. cameraExposure: 0.8,
  88001. cameraContrast: 1.2,
  88002. toneMappingEnabled: true,
  88003. };
  88004. };
  88005. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88006. /**
  88007. * Gets the root mesh created by the helper.
  88008. */
  88009. get: function () {
  88010. return this._rootMesh;
  88011. },
  88012. enumerable: true,
  88013. configurable: true
  88014. });
  88015. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88016. /**
  88017. * Gets the skybox created by the helper.
  88018. */
  88019. get: function () {
  88020. return this._skybox;
  88021. },
  88022. enumerable: true,
  88023. configurable: true
  88024. });
  88025. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88026. /**
  88027. * Gets the skybox texture created by the helper.
  88028. */
  88029. get: function () {
  88030. return this._skyboxTexture;
  88031. },
  88032. enumerable: true,
  88033. configurable: true
  88034. });
  88035. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88036. /**
  88037. * Gets the skybox material created by the helper.
  88038. */
  88039. get: function () {
  88040. return this._skyboxMaterial;
  88041. },
  88042. enumerable: true,
  88043. configurable: true
  88044. });
  88045. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88046. /**
  88047. * Gets the ground mesh created by the helper.
  88048. */
  88049. get: function () {
  88050. return this._ground;
  88051. },
  88052. enumerable: true,
  88053. configurable: true
  88054. });
  88055. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88056. /**
  88057. * Gets the ground texture created by the helper.
  88058. */
  88059. get: function () {
  88060. return this._groundTexture;
  88061. },
  88062. enumerable: true,
  88063. configurable: true
  88064. });
  88065. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88066. /**
  88067. * Gets the ground mirror created by the helper.
  88068. */
  88069. get: function () {
  88070. return this._groundMirror;
  88071. },
  88072. enumerable: true,
  88073. configurable: true
  88074. });
  88075. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88076. /**
  88077. * Gets the ground mirror render list to helps pushing the meshes
  88078. * you wish in the ground reflection.
  88079. */
  88080. get: function () {
  88081. if (this._groundMirror) {
  88082. return this._groundMirror.renderList;
  88083. }
  88084. return null;
  88085. },
  88086. enumerable: true,
  88087. configurable: true
  88088. });
  88089. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88090. /**
  88091. * Gets the ground material created by the helper.
  88092. */
  88093. get: function () {
  88094. return this._groundMaterial;
  88095. },
  88096. enumerable: true,
  88097. configurable: true
  88098. });
  88099. /**
  88100. * Updates the background according to the new options
  88101. * @param options
  88102. */
  88103. EnvironmentHelper.prototype.updateOptions = function (options) {
  88104. var newOptions = __assign({}, this._options, options);
  88105. if (this._ground && !newOptions.createGround) {
  88106. this._ground.dispose();
  88107. this._ground = null;
  88108. }
  88109. if (this._groundMaterial && !newOptions.createGround) {
  88110. this._groundMaterial.dispose();
  88111. this._groundMaterial = null;
  88112. }
  88113. if (this._groundTexture) {
  88114. if (this._options.groundTexture != newOptions.groundTexture) {
  88115. this._groundTexture.dispose();
  88116. this._groundTexture = null;
  88117. }
  88118. }
  88119. if (this._skybox && !newOptions.createSkybox) {
  88120. this._skybox.dispose();
  88121. this._skybox = null;
  88122. }
  88123. if (this._skyboxMaterial && !newOptions.createSkybox) {
  88124. this._skyboxMaterial.dispose();
  88125. this._skyboxMaterial = null;
  88126. }
  88127. if (this._skyboxTexture) {
  88128. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  88129. this._skyboxTexture.dispose();
  88130. this._skyboxTexture = null;
  88131. }
  88132. }
  88133. if (this._groundMirror && !newOptions.enableGroundMirror) {
  88134. this._groundMirror.dispose();
  88135. this._groundMirror = null;
  88136. }
  88137. if (this._scene.environmentTexture) {
  88138. if (this._options.environmentTexture != newOptions.environmentTexture) {
  88139. this._scene.environmentTexture.dispose();
  88140. }
  88141. }
  88142. this._options = newOptions;
  88143. this._setupBackground();
  88144. this._setupImageProcessing();
  88145. };
  88146. /**
  88147. * Sets the primary color of all the available elements.
  88148. * @param color
  88149. */
  88150. EnvironmentHelper.prototype.setMainColor = function (color) {
  88151. if (this.groundMaterial) {
  88152. this.groundMaterial.primaryColor = color;
  88153. }
  88154. if (this.skyboxMaterial) {
  88155. this.skyboxMaterial.primaryColor = color;
  88156. }
  88157. if (this.groundMirror) {
  88158. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  88159. }
  88160. };
  88161. /**
  88162. * Setup the image processing according to the specified options.
  88163. */
  88164. EnvironmentHelper.prototype._setupImageProcessing = function () {
  88165. if (this._options.setupImageProcessing) {
  88166. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  88167. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  88168. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  88169. this._setupEnvironmentTexture();
  88170. }
  88171. };
  88172. /**
  88173. * Setup the environment texture according to the specified options.
  88174. */
  88175. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  88176. if (this._scene.environmentTexture) {
  88177. return;
  88178. }
  88179. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  88180. this._scene.environmentTexture = this._options.environmentTexture;
  88181. return;
  88182. }
  88183. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  88184. this._scene.environmentTexture = environmentTexture;
  88185. };
  88186. /**
  88187. * Setup the background according to the specified options.
  88188. */
  88189. EnvironmentHelper.prototype._setupBackground = function () {
  88190. if (!this._rootMesh) {
  88191. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  88192. }
  88193. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  88194. var sceneSize = this._getSceneSize();
  88195. if (this._options.createGround) {
  88196. this._setupGround(sceneSize);
  88197. this._setupGroundMaterial();
  88198. this._setupGroundDiffuseTexture();
  88199. if (this._options.enableGroundMirror) {
  88200. this._setupGroundMirrorTexture(sceneSize);
  88201. }
  88202. this._setupMirrorInGroundMaterial();
  88203. }
  88204. if (this._options.createSkybox) {
  88205. this._setupSkybox(sceneSize);
  88206. this._setupSkyboxMaterial();
  88207. this._setupSkyboxReflectionTexture();
  88208. }
  88209. this._rootMesh.position.x = sceneSize.rootPosition.x;
  88210. this._rootMesh.position.z = sceneSize.rootPosition.z;
  88211. this._rootMesh.position.y = sceneSize.rootPosition.y;
  88212. };
  88213. /**
  88214. * Get the scene sizes according to the setup.
  88215. */
  88216. EnvironmentHelper.prototype._getSceneSize = function () {
  88217. var groundSize = this._options.groundSize;
  88218. var skyboxSize = this._options.skyboxSize;
  88219. var rootPosition = this._options.rootPosition;
  88220. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  88221. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88222. }
  88223. var sceneExtends = this._scene.getWorldExtends();
  88224. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  88225. if (this._options.sizeAuto) {
  88226. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  88227. this._scene.activeCamera.upperRadiusLimit) {
  88228. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  88229. skyboxSize = groundSize;
  88230. }
  88231. var sceneDiagonalLenght = sceneDiagonal.length();
  88232. if (sceneDiagonalLenght > groundSize) {
  88233. groundSize = sceneDiagonalLenght * 2;
  88234. skyboxSize = groundSize;
  88235. }
  88236. // 10 % bigger.
  88237. groundSize *= 1.1;
  88238. skyboxSize *= 1.5;
  88239. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  88240. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  88241. }
  88242. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88243. };
  88244. /**
  88245. * Setup the ground according to the specified options.
  88246. */
  88247. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  88248. var _this = this;
  88249. if (!this._ground) {
  88250. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  88251. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88252. this._ground.parent = this._rootMesh;
  88253. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88254. }
  88255. this._ground.receiveShadows = this._options.enableGroundShadow;
  88256. };
  88257. /**
  88258. * Setup the ground material according to the specified options.
  88259. */
  88260. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88261. if (!this._groundMaterial) {
  88262. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88263. }
  88264. this._groundMaterial.alpha = this._options.groundOpacity;
  88265. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88266. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88267. this._groundMaterial.primaryLevel = 1;
  88268. this._groundMaterial.primaryColor = this._options.groundColor;
  88269. this._groundMaterial.secondaryLevel = 0;
  88270. this._groundMaterial.tertiaryLevel = 0;
  88271. this._groundMaterial.useRGBColor = false;
  88272. this._groundMaterial.enableNoise = true;
  88273. if (this._ground) {
  88274. this._ground.material = this._groundMaterial;
  88275. }
  88276. };
  88277. /**
  88278. * Setup the ground diffuse texture according to the specified options.
  88279. */
  88280. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88281. if (!this._groundMaterial) {
  88282. return;
  88283. }
  88284. if (this._groundTexture) {
  88285. return;
  88286. }
  88287. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88288. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88289. return;
  88290. }
  88291. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88292. diffuseTexture.gammaSpace = false;
  88293. diffuseTexture.hasAlpha = true;
  88294. this._groundMaterial.diffuseTexture = diffuseTexture;
  88295. };
  88296. /**
  88297. * Setup the ground mirror texture according to the specified options.
  88298. */
  88299. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88300. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88301. if (!this._groundMirror) {
  88302. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88303. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88304. this._groundMirror.anisotropicFilteringLevel = 1;
  88305. this._groundMirror.wrapU = wrapping;
  88306. this._groundMirror.wrapV = wrapping;
  88307. this._groundMirror.gammaSpace = false;
  88308. if (this._groundMirror.renderList) {
  88309. for (var i = 0; i < this._scene.meshes.length; i++) {
  88310. var mesh = this._scene.meshes[i];
  88311. if (mesh !== this._ground &&
  88312. mesh !== this._skybox &&
  88313. mesh !== this._rootMesh) {
  88314. this._groundMirror.renderList.push(mesh);
  88315. }
  88316. }
  88317. }
  88318. }
  88319. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88320. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88321. };
  88322. /**
  88323. * Setup the ground to receive the mirror texture.
  88324. */
  88325. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88326. if (this._groundMaterial) {
  88327. this._groundMaterial.reflectionTexture = this._groundMirror;
  88328. this._groundMaterial.reflectionFresnel = true;
  88329. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88330. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88331. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88332. }
  88333. };
  88334. /**
  88335. * Setup the skybox according to the specified options.
  88336. */
  88337. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88338. var _this = this;
  88339. if (!this._skybox) {
  88340. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88341. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88342. }
  88343. this._skybox.parent = this._rootMesh;
  88344. };
  88345. /**
  88346. * Setup the skybox material according to the specified options.
  88347. */
  88348. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88349. if (!this._skybox) {
  88350. return;
  88351. }
  88352. if (!this._skyboxMaterial) {
  88353. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88354. }
  88355. this._skyboxMaterial.useRGBColor = false;
  88356. this._skyboxMaterial.primaryLevel = 1;
  88357. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88358. this._skyboxMaterial.secondaryLevel = 0;
  88359. this._skyboxMaterial.tertiaryLevel = 0;
  88360. this._skyboxMaterial.enableNoise = true;
  88361. this._skybox.material = this._skyboxMaterial;
  88362. };
  88363. /**
  88364. * Setup the skybox reflection texture according to the specified options.
  88365. */
  88366. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88367. if (!this._skyboxMaterial) {
  88368. return;
  88369. }
  88370. if (this._skyboxTexture) {
  88371. return;
  88372. }
  88373. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88374. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88375. return;
  88376. }
  88377. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88378. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88379. this._skyboxTexture.gammaSpace = false;
  88380. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88381. };
  88382. /**
  88383. * Dispose all the elements created by the Helper.
  88384. */
  88385. EnvironmentHelper.prototype.dispose = function () {
  88386. if (this._groundMaterial) {
  88387. this._groundMaterial.dispose(true, true);
  88388. }
  88389. if (this._skyboxMaterial) {
  88390. this._skyboxMaterial.dispose(true, true);
  88391. }
  88392. this._rootMesh.dispose(false);
  88393. };
  88394. /**
  88395. * Default ground texture URL.
  88396. */
  88397. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88398. /**
  88399. * Default skybox texture URL.
  88400. */
  88401. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88402. /**
  88403. * Default environment texture URL.
  88404. */
  88405. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88406. return EnvironmentHelper;
  88407. }());
  88408. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88409. })(BABYLON || (BABYLON = {}));
  88410. //# sourceMappingURL=babylon.environmentHelper.js.map
  88411. var BABYLON;
  88412. (function (BABYLON) {
  88413. /**
  88414. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  88415. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  88416. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  88417. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  88418. */
  88419. var VideoDome = /** @class */ (function (_super) {
  88420. __extends(VideoDome, _super);
  88421. /**
  88422. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  88423. * @param name Element's name, child elements will append suffixes for their own names.
  88424. * @param urlsOrVideo
  88425. * @param options An object containing optional or exposed sub element properties:
  88426. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  88427. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  88428. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  88429. * @param options **loop=true** Automatically loop video on end.
  88430. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  88431. */
  88432. function VideoDome(name, urlsOrVideo, options, scene) {
  88433. var _this = _super.call(this, name, scene) || this;
  88434. // set defaults and manage values
  88435. name = name || "videoDome";
  88436. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  88437. options.clickToPlay = Boolean(options.clickToPlay);
  88438. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  88439. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  88440. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  88441. // create
  88442. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  88443. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  88444. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  88445. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  88446. flat: false,
  88447. radius: options.size,
  88448. subdivisions: options.resolution,
  88449. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  88450. }, scene);
  88451. // configure material
  88452. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  88453. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  88454. material.reflectionTexture = _this._videoTexture;
  88455. material.useEquirectangularFOV = true;
  88456. material.fovMultiplier = 1.0;
  88457. // configure mesh
  88458. _this._mesh.material = material;
  88459. _this._mesh.parent = _this;
  88460. // optional configuration
  88461. if (options.clickToPlay) {
  88462. scene.onPointerUp = function () {
  88463. _this._videoTexture.video.play();
  88464. };
  88465. }
  88466. return _this;
  88467. }
  88468. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  88469. /**
  88470. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88471. * Also see the options.resolution property.
  88472. */
  88473. get: function () {
  88474. return this._material.fovMultiplier;
  88475. },
  88476. set: function (value) {
  88477. this._material.fovMultiplier = value;
  88478. },
  88479. enumerable: true,
  88480. configurable: true
  88481. });
  88482. return VideoDome;
  88483. }(BABYLON.Node));
  88484. BABYLON.VideoDome = VideoDome;
  88485. })(BABYLON || (BABYLON = {}));
  88486. //# sourceMappingURL=babylon.videoDome.js.map
  88487. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88488. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  88489. (function universalModuleDefinition(root, factory) {
  88490. var f = factory();
  88491. if (root && root["BABYLON"]) {
  88492. return;
  88493. }
  88494. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88495. globalObject["BABYLON"] = f;
  88496. if(typeof exports === 'object' && typeof module === 'object')
  88497. module.exports = f;
  88498. else if(typeof define === 'function' && define.amd)
  88499. define(["BABYLON"], factory);
  88500. else if(typeof exports === 'object')
  88501. exports["BABYLON"] = f;
  88502. else {
  88503. root["BABYLON"] = f;
  88504. }
  88505. })(this, function() {
  88506. return BABYLON;
  88507. });